Tools.cpp revision 089f872fedb175f7569f24f1dba362ffbc403528
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/HostInfo.h"
20#include "clang/Driver/Option.h"
21#include "clang/Driver/Options.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Driver/Util.h"
24
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/Host.h"
32#include "llvm/Support/Process.h"
33
34#include "InputInfo.h"
35#include "ToolChains.h"
36
37using namespace clang::driver;
38using namespace clang::driver::tools;
39
40/// FindTargetProgramPath - Return path of the target specific version of
41/// ProgName.  If it doesn't exist, return path of ProgName itself.
42static std::string FindTargetProgramPath(const ToolChain &TheToolChain,
43                                         const char *ProgName) {
44  std::string Executable(TheToolChain.getTripleString() + "-" + ProgName);
45  std::string Path(TheToolChain.GetProgramPath(Executable.c_str()));
46  if (Path != Executable)
47    return Path;
48  return TheToolChain.GetProgramPath(ProgName);
49}
50
51/// CheckPreprocessingOptions - Perform some validation of preprocessing
52/// arguments that is shared with gcc.
53static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
55    if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP)
56      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
57        << A->getAsString(Args) << "-E";
58}
59
60/// CheckCodeGenerationOptions - Perform some validation of code generation
61/// arguments that is shared with gcc.
62static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
63  // In gcc, only ARM checks this, but it seems reasonable to check universally.
64  if (Args.hasArg(options::OPT_static))
65    if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
66                                       options::OPT_mdynamic_no_pic))
67      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
68        << A->getAsString(Args) << "-static";
69}
70
71// Quote target names for inclusion in GNU Make dependency files.
72// Only the characters '$', '#', ' ', '\t' are quoted.
73static void QuoteTarget(llvm::StringRef Target,
74                        llvm::SmallVectorImpl<char> &Res) {
75  for (unsigned i = 0, e = Target.size(); i != e; ++i) {
76    switch (Target[i]) {
77    case ' ':
78    case '\t':
79      // Escape the preceding backslashes
80      for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
81        Res.push_back('\\');
82
83      // Escape the space/tab
84      Res.push_back('\\');
85      break;
86    case '$':
87      Res.push_back('$');
88      break;
89    case '#':
90      Res.push_back('\\');
91      break;
92    default:
93      break;
94    }
95
96    Res.push_back(Target[i]);
97  }
98}
99
100static void AddLinkerInputs(const ToolChain &TC,
101                            const InputInfoList &Inputs, const ArgList &Args,
102                            ArgStringList &CmdArgs) {
103  const Driver &D = TC.getDriver();
104
105  // Add extra linker input arguments which are not treated as inputs
106  // (constructed via -Xarch_).
107  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
108
109  for (InputInfoList::const_iterator
110         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
111    const InputInfo &II = *it;
112
113    if (!TC.HasNativeLLVMSupport()) {
114      // Don't try to pass LLVM inputs unless we have native support.
115      if (II.getType() == types::TY_LLVM_IR ||
116          II.getType() == types::TY_LTO_IR ||
117          II.getType() == types::TY_LLVM_BC ||
118          II.getType() == types::TY_LTO_BC)
119        D.Diag(clang::diag::err_drv_no_linker_llvm_support)
120          << TC.getTripleString();
121    }
122
123    // Add filenames immediately.
124    if (II.isFilename()) {
125      CmdArgs.push_back(II.getFilename());
126      continue;
127    }
128
129    // Otherwise, this is a linker input argument.
130    const Arg &A = II.getInputArg();
131
132    // Handle reserved library options.
133    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
134      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
135    } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
136      TC.AddCCKextLibArgs(Args, CmdArgs);
137    } else
138      A.renderAsInput(Args, CmdArgs);
139  }
140}
141
142void Clang::AddPreprocessingOptions(const Driver &D,
143                                    const ArgList &Args,
144                                    ArgStringList &CmdArgs,
145                                    const InputInfo &Output,
146                                    const InputInfoList &Inputs) const {
147  Arg *A;
148
149  CheckPreprocessingOptions(D, Args);
150
151  Args.AddLastArg(CmdArgs, options::OPT_C);
152  Args.AddLastArg(CmdArgs, options::OPT_CC);
153
154  // Handle dependency file generation.
155  if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
156      (A = Args.getLastArg(options::OPT_MD)) ||
157      (A = Args.getLastArg(options::OPT_MMD))) {
158    // Determine the output location.
159    const char *DepFile;
160    if (Output.getType() == types::TY_Dependencies) {
161      DepFile = Output.getFilename();
162    } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
163      DepFile = MF->getValue(Args);
164    } else if (A->getOption().matches(options::OPT_M) ||
165               A->getOption().matches(options::OPT_MM)) {
166      DepFile = "-";
167    } else {
168      DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
169    }
170    CmdArgs.push_back("-dependency-file");
171    CmdArgs.push_back(DepFile);
172
173    // Add a default target if one wasn't specified.
174    if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
175      const char *DepTarget;
176
177      // If user provided -o, that is the dependency target, except
178      // when we are only generating a dependency file.
179      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
180      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
181        DepTarget = OutputOpt->getValue(Args);
182      } else {
183        // Otherwise derive from the base input.
184        //
185        // FIXME: This should use the computed output file location.
186        llvm::SmallString<128> P(Inputs[0].getBaseInput());
187        llvm::sys::path::replace_extension(P, "o");
188        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
189      }
190
191      CmdArgs.push_back("-MT");
192      llvm::SmallString<128> Quoted;
193      QuoteTarget(DepTarget, Quoted);
194      CmdArgs.push_back(Args.MakeArgString(Quoted));
195    }
196
197    if (A->getOption().matches(options::OPT_M) ||
198        A->getOption().matches(options::OPT_MD))
199      CmdArgs.push_back("-sys-header-deps");
200  }
201
202  Args.AddLastArg(CmdArgs, options::OPT_MP);
203
204  // Convert all -MQ <target> args to -MT <quoted target>
205  for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
206                                             options::OPT_MQ),
207         ie = Args.filtered_end(); it != ie; ++it) {
208    const Arg *A = *it;
209    A->claim();
210
211    if (A->getOption().matches(options::OPT_MQ)) {
212      CmdArgs.push_back("-MT");
213      llvm::SmallString<128> Quoted;
214      QuoteTarget(A->getValue(Args), Quoted);
215      CmdArgs.push_back(Args.MakeArgString(Quoted));
216
217    // -MT flag - no change
218    } else {
219      A->render(Args, CmdArgs);
220    }
221  }
222
223  // Add -i* options, and automatically translate to
224  // -include-pch/-include-pth for transparent PCH support. It's
225  // wonky, but we include looking for .gch so we can support seamless
226  // replacement into a build system already set up to be generating
227  // .gch files.
228  bool RenderedImplicitInclude = false;
229  for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
230         ie = Args.filtered_end(); it != ie; ++it) {
231    const Arg *A = it;
232
233    if (A->getOption().matches(options::OPT_include)) {
234      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
235      RenderedImplicitInclude = true;
236
237      // Use PCH if the user requested it.
238      bool UsePCH = D.CCCUsePCH;
239
240      bool FoundPTH = false;
241      bool FoundPCH = false;
242      llvm::sys::Path P(A->getValue(Args));
243      bool Exists;
244      if (UsePCH) {
245        P.appendSuffix("pch");
246        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
247          FoundPCH = true;
248        else
249          P.eraseSuffix();
250      }
251
252      if (!FoundPCH) {
253        P.appendSuffix("pth");
254        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
255          FoundPTH = true;
256        else
257          P.eraseSuffix();
258      }
259
260      if (!FoundPCH && !FoundPTH) {
261        P.appendSuffix("gch");
262        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
263          FoundPCH = UsePCH;
264          FoundPTH = !UsePCH;
265        }
266        else
267          P.eraseSuffix();
268      }
269
270      if (FoundPCH || FoundPTH) {
271        if (IsFirstImplicitInclude) {
272          A->claim();
273          if (UsePCH)
274            CmdArgs.push_back("-include-pch");
275          else
276            CmdArgs.push_back("-include-pth");
277          CmdArgs.push_back(Args.MakeArgString(P.str()));
278          continue;
279        } else {
280          // Ignore the PCH if not first on command line and emit warning.
281          D.Diag(clang::diag::warn_drv_pch_not_first_include)
282              << P.str() << A->getAsString(Args);
283        }
284      }
285    }
286
287    // Not translated, render as usual.
288    A->claim();
289    A->render(Args, CmdArgs);
290  }
291
292  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
293  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
294
295  // Add C++ include arguments, if needed.
296  types::ID InputType = Inputs[0].getType();
297  if (types::isCXX(InputType))
298    getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
299
300  // Add -Wp, and -Xassembler if using the preprocessor.
301
302  // FIXME: There is a very unfortunate problem here, some troubled
303  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
304  // really support that we would have to parse and then translate
305  // those options. :(
306  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
307                       options::OPT_Xpreprocessor);
308
309  // -I- is a deprecated GCC feature, reject it.
310  if (Arg *A = Args.getLastArg(options::OPT_I_))
311    D.Diag(clang::diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
312
313  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
314  // -isysroot to the CC1 invocation.
315  if (Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
316    if (!Args.hasArg(options::OPT_isysroot)) {
317      CmdArgs.push_back("-isysroot");
318      CmdArgs.push_back(A->getValue(Args));
319    }
320  }
321}
322
323/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targetting.
324//
325// FIXME: tblgen this.
326static const char *getARMTargetCPU(const ArgList &Args,
327                                   const llvm::Triple &Triple) {
328  // FIXME: Warn on inconsistent use of -mcpu and -march.
329
330  // If we have -mcpu=, use that.
331  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
332    return A->getValue(Args);
333
334  llvm::StringRef MArch;
335  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
336    // Otherwise, if we have -march= choose the base CPU for that arch.
337    MArch = A->getValue(Args);
338  } else {
339    // Otherwise, use the Arch from the triple.
340    MArch = Triple.getArchName();
341  }
342
343  if (MArch == "armv2" || MArch == "armv2a")
344    return "arm2";
345  if (MArch == "armv3")
346    return "arm6";
347  if (MArch == "armv3m")
348    return "arm7m";
349  if (MArch == "armv4" || MArch == "armv4t")
350    return "arm7tdmi";
351  if (MArch == "armv5" || MArch == "armv5t")
352    return "arm10tdmi";
353  if (MArch == "armv5e" || MArch == "armv5te")
354    return "arm1026ejs";
355  if (MArch == "armv5tej")
356    return "arm926ej-s";
357  if (MArch == "armv6" || MArch == "armv6k")
358    return "arm1136jf-s";
359  if (MArch == "armv6j")
360    return "arm1136j-s";
361  if (MArch == "armv6z" || MArch == "armv6zk")
362    return "arm1176jzf-s";
363  if (MArch == "armv6t2")
364    return "arm1156t2-s";
365  if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
366    return "cortex-a8";
367  if (MArch == "armv7r" || MArch == "armv7-r")
368    return "cortex-r4";
369  if (MArch == "armv7m" || MArch == "armv7-m")
370    return "cortex-m3";
371  if (MArch == "ep9312")
372    return "ep9312";
373  if (MArch == "iwmmxt")
374    return "iwmmxt";
375  if (MArch == "xscale")
376    return "xscale";
377  if (MArch == "armv6m" || MArch == "armv6-m")
378    return "cortex-m0";
379
380  // If all else failed, return the most base CPU LLVM supports.
381  return "arm7tdmi";
382}
383
384/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
385/// CPU.
386//
387// FIXME: This is redundant with -mcpu, why does LLVM use this.
388// FIXME: tblgen this, or kill it!
389static const char *getLLVMArchSuffixForARM(llvm::StringRef CPU) {
390  if (CPU == "arm7tdmi" || CPU == "arm7tdmi-s" || CPU == "arm710t" ||
391      CPU == "arm720t" || CPU == "arm9" || CPU == "arm9tdmi" ||
392      CPU == "arm920" || CPU == "arm920t" || CPU == "arm922t" ||
393      CPU == "arm940t" || CPU == "ep9312")
394    return "v4t";
395
396  if (CPU == "arm10tdmi" || CPU == "arm1020t")
397    return "v5";
398
399  if (CPU == "arm9e" || CPU == "arm926ej-s" || CPU == "arm946e-s" ||
400      CPU == "arm966e-s" || CPU == "arm968e-s" || CPU == "arm10e" ||
401      CPU == "arm1020e" || CPU == "arm1022e" || CPU == "xscale" ||
402      CPU == "iwmmxt")
403    return "v5e";
404
405  if (CPU == "arm1136j-s" || CPU == "arm1136jf-s" || CPU == "arm1176jz-s" ||
406      CPU == "arm1176jzf-s" || CPU == "mpcorenovfp" || CPU == "mpcore")
407    return "v6";
408
409  if (CPU == "arm1156t2-s" || CPU == "arm1156t2f-s")
410    return "v6t2";
411
412  if (CPU == "cortex-a8" || CPU == "cortex-a9")
413    return "v7";
414
415  return "";
416}
417
418// FIXME: Move to target hook.
419static bool isSignedCharDefault(const llvm::Triple &Triple) {
420  switch (Triple.getArch()) {
421  default:
422    return true;
423
424  case llvm::Triple::ppc:
425  case llvm::Triple::ppc64:
426    if (Triple.getOS() == llvm::Triple::Darwin)
427      return true;
428    return false;
429
430  case llvm::Triple::systemz:
431    return false;
432  }
433}
434
435void Clang::AddARMTargetArgs(const ArgList &Args,
436                             ArgStringList &CmdArgs,
437                             bool KernelOrKext) const {
438  const Driver &D = getToolChain().getDriver();
439  llvm::Triple Triple = getToolChain().getTriple();
440
441  // Disable movt generation, if requested.
442#ifdef DISABLE_ARM_DARWIN_USE_MOVT
443  CmdArgs.push_back("-backend-option");
444  CmdArgs.push_back("-arm-darwin-use-movt=0");
445#endif
446
447  // Select the ABI to use.
448  //
449  // FIXME: Support -meabi.
450  const char *ABIName = 0;
451  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
452    ABIName = A->getValue(Args);
453  } else {
454    // Select the default based on the platform.
455    switch(Triple.getEnvironment()) {
456    case llvm::Triple::GNUEABI:
457      ABIName = "aapcs-linux";
458      break;
459    case llvm::Triple::EABI:
460      ABIName = "aapcs";
461      break;
462    default:
463      ABIName = "apcs-gnu";
464    }
465  }
466  CmdArgs.push_back("-target-abi");
467  CmdArgs.push_back(ABIName);
468
469  // Set the CPU based on -march= and -mcpu=.
470  CmdArgs.push_back("-target-cpu");
471  CmdArgs.push_back(getARMTargetCPU(Args, Triple));
472
473  // Select the float ABI as determined by -msoft-float, -mhard-float, and
474  // -mfloat-abi=.
475  llvm::StringRef FloatABI;
476  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
477                               options::OPT_mhard_float,
478                               options::OPT_mfloat_abi_EQ)) {
479    if (A->getOption().matches(options::OPT_msoft_float))
480      FloatABI = "soft";
481    else if (A->getOption().matches(options::OPT_mhard_float))
482      FloatABI = "hard";
483    else {
484      FloatABI = A->getValue(Args);
485      if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
486        D.Diag(clang::diag::err_drv_invalid_mfloat_abi)
487          << A->getAsString(Args);
488        FloatABI = "soft";
489      }
490    }
491  }
492
493  // If unspecified, choose the default based on the platform.
494  if (FloatABI.empty()) {
495    const llvm::Triple &Triple = getToolChain().getTriple();
496    switch (Triple.getOS()) {
497    case llvm::Triple::Darwin: {
498      // Darwin defaults to "softfp" for v6 and v7.
499      //
500      // FIXME: Factor out an ARM class so we can cache the arch somewhere.
501      llvm::StringRef ArchName =
502        getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
503      if (ArchName.startswith("v6") || ArchName.startswith("v7"))
504        FloatABI = "softfp";
505      else
506        FloatABI = "soft";
507      break;
508    }
509
510    case llvm::Triple::Linux: {
511      if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUEABI) {
512        FloatABI = "softfp";
513        break;
514      }
515    }
516    // fall through
517
518    default:
519      switch(Triple.getEnvironment()) {
520      case llvm::Triple::GNUEABI:
521        FloatABI = "softfp";
522        break;
523      case llvm::Triple::EABI:
524        // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
525        FloatABI = "softfp";
526        break;
527      default:
528        // Assume "soft", but warn the user we are guessing.
529        FloatABI = "soft";
530        D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
531        break;
532      }
533    }
534  }
535
536  if (FloatABI == "soft") {
537    // Floating point operations and argument passing are soft.
538    //
539    // FIXME: This changes CPP defines, we need -target-soft-float.
540    CmdArgs.push_back("-msoft-float");
541    CmdArgs.push_back("-mfloat-abi");
542    CmdArgs.push_back("soft");
543  } else if (FloatABI == "softfp") {
544    // Floating point operations are hard, but argument passing is soft.
545    CmdArgs.push_back("-mfloat-abi");
546    CmdArgs.push_back("soft");
547  } else {
548    // Floating point operations and argument passing are hard.
549    assert(FloatABI == "hard" && "Invalid float abi!");
550    CmdArgs.push_back("-mfloat-abi");
551    CmdArgs.push_back("hard");
552  }
553
554  // Set appropriate target features for floating point mode.
555  //
556  // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
557  // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
558  // stripped out by the ARM target.
559
560  // Use software floating point operations?
561  if (FloatABI == "soft") {
562    CmdArgs.push_back("-target-feature");
563    CmdArgs.push_back("+soft-float");
564  }
565
566  // Use software floating point argument passing?
567  if (FloatABI != "hard") {
568    CmdArgs.push_back("-target-feature");
569    CmdArgs.push_back("+soft-float-abi");
570  }
571
572  // Honor -mfpu=.
573  //
574  // FIXME: Centralize feature selection, defaulting shouldn't be also in the
575  // frontend target.
576  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) {
577    llvm::StringRef FPU = A->getValue(Args);
578
579    // Set the target features based on the FPU.
580    if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
581      // Disable any default FPU support.
582      CmdArgs.push_back("-target-feature");
583      CmdArgs.push_back("-vfp2");
584      CmdArgs.push_back("-target-feature");
585      CmdArgs.push_back("-vfp3");
586      CmdArgs.push_back("-target-feature");
587      CmdArgs.push_back("-neon");
588    } else if (FPU == "vfp") {
589      CmdArgs.push_back("-target-feature");
590      CmdArgs.push_back("+vfp2");
591    } else if (FPU == "vfp3") {
592      CmdArgs.push_back("-target-feature");
593      CmdArgs.push_back("+vfp3");
594    } else if (FPU == "neon") {
595      CmdArgs.push_back("-target-feature");
596      CmdArgs.push_back("+neon");
597    } else
598      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
599  }
600
601  // Setting -msoft-float effectively disables NEON because of the GCC
602  // implementation, although the same isn't true of VFP or VFP3.
603  if (FloatABI == "soft") {
604    CmdArgs.push_back("-target-feature");
605    CmdArgs.push_back("-neon");
606  }
607
608  // Kernel code has more strict alignment requirements.
609  if (KernelOrKext) {
610    CmdArgs.push_back("-backend-option");
611    CmdArgs.push_back("-arm-long-calls");
612
613    CmdArgs.push_back("-backend-option");
614    CmdArgs.push_back("-arm-strict-align");
615  }
616}
617
618void Clang::AddMIPSTargetArgs(const ArgList &Args,
619                             ArgStringList &CmdArgs) const {
620  const Driver &D = getToolChain().getDriver();
621
622  // Select the ABI to use.
623  const char *ABIName = 0;
624  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
625    ABIName = A->getValue(Args);
626  } else {
627    ABIName = "o32";
628  }
629
630  CmdArgs.push_back("-target-abi");
631  CmdArgs.push_back(ABIName);
632
633  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
634    llvm::StringRef MArch = A->getValue(Args);
635    CmdArgs.push_back("-target-cpu");
636
637    if ((MArch == "r2000") || (MArch == "r3000"))
638      CmdArgs.push_back("mips1");
639    else if (MArch == "r6000")
640      CmdArgs.push_back("mips2");
641    else
642      CmdArgs.push_back(MArch.str().c_str());
643  }
644
645  // Select the float ABI as determined by -msoft-float, -mhard-float, and
646  llvm::StringRef FloatABI;
647  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
648                               options::OPT_mhard_float)) {
649    if (A->getOption().matches(options::OPT_msoft_float))
650      FloatABI = "soft";
651    else if (A->getOption().matches(options::OPT_mhard_float))
652      FloatABI = "hard";
653  }
654
655  // If unspecified, choose the default based on the platform.
656  if (FloatABI.empty()) {
657    // Assume "soft", but warn the user we are guessing.
658    FloatABI = "soft";
659    D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
660  }
661
662  if (FloatABI == "soft") {
663    // Floating point operations and argument passing are soft.
664    //
665    // FIXME: This changes CPP defines, we need -target-soft-float.
666    CmdArgs.push_back("-msoft-float");
667  } else {
668    assert(FloatABI == "hard" && "Invalid float abi!");
669    CmdArgs.push_back("-mhard-float");
670  }
671}
672
673void Clang::AddSparcTargetArgs(const ArgList &Args,
674                             ArgStringList &CmdArgs) const {
675  const Driver &D = getToolChain().getDriver();
676
677  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
678    llvm::StringRef MArch = A->getValue(Args);
679    CmdArgs.push_back("-target-cpu");
680    CmdArgs.push_back(MArch.str().c_str());
681  }
682
683  // Select the float ABI as determined by -msoft-float, -mhard-float, and
684  llvm::StringRef FloatABI;
685  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
686                               options::OPT_mhard_float)) {
687    if (A->getOption().matches(options::OPT_msoft_float))
688      FloatABI = "soft";
689    else if (A->getOption().matches(options::OPT_mhard_float))
690      FloatABI = "hard";
691  }
692
693  // If unspecified, choose the default based on the platform.
694  if (FloatABI.empty()) {
695    switch (getToolChain().getTriple().getOS()) {
696    default:
697      // Assume "soft", but warn the user we are guessing.
698      FloatABI = "soft";
699      D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
700      break;
701    }
702  }
703
704  if (FloatABI == "soft") {
705    // Floating point operations and argument passing are soft.
706    //
707    // FIXME: This changes CPP defines, we need -target-soft-float.
708    CmdArgs.push_back("-msoft-float");
709    CmdArgs.push_back("soft");
710    CmdArgs.push_back("-target-feature");
711    CmdArgs.push_back("+soft-float");
712  } else {
713    assert(FloatABI == "hard" && "Invalid float abi!");
714    CmdArgs.push_back("-mhard-float");
715  }
716}
717
718void Clang::AddX86TargetArgs(const ArgList &Args,
719                             ArgStringList &CmdArgs) const {
720  if (!Args.hasFlag(options::OPT_mred_zone,
721                    options::OPT_mno_red_zone,
722                    true) ||
723      Args.hasArg(options::OPT_mkernel) ||
724      Args.hasArg(options::OPT_fapple_kext))
725    CmdArgs.push_back("-disable-red-zone");
726
727  if (Args.hasFlag(options::OPT_msoft_float,
728                   options::OPT_mno_soft_float,
729                   false))
730    CmdArgs.push_back("-no-implicit-float");
731
732  const char *CPUName = 0;
733  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
734    if (llvm::StringRef(A->getValue(Args)) == "native") {
735      // FIXME: Reject attempts to use -march=native unless the target matches
736      // the host.
737      //
738      // FIXME: We should also incorporate the detected target features for use
739      // with -native.
740      std::string CPU = llvm::sys::getHostCPUName();
741      if (!CPU.empty())
742        CPUName = Args.MakeArgString(CPU);
743    } else
744      CPUName = A->getValue(Args);
745  }
746
747  // Select the default CPU if none was given (or detection failed).
748  if (!CPUName) {
749    // FIXME: Need target hooks.
750    if (getToolChain().getOS().startswith("darwin")) {
751      if (getToolChain().getArchName() == "x86_64")
752        CPUName = "core2";
753      else if (getToolChain().getArchName() == "i386")
754        CPUName = "yonah";
755    } else if (getToolChain().getOS().startswith("haiku"))  {
756      if (getToolChain().getArchName() == "x86_64")
757        CPUName = "x86-64";
758      else if (getToolChain().getArchName() == "i386")
759        CPUName = "i586";
760    } else if (getToolChain().getOS().startswith("openbsd"))  {
761      if (getToolChain().getArchName() == "x86_64")
762        CPUName = "x86-64";
763      else if (getToolChain().getArchName() == "i386")
764        CPUName = "i486";
765    } else if (getToolChain().getOS().startswith("freebsd"))  {
766      if (getToolChain().getArchName() == "x86_64")
767        CPUName = "x86-64";
768      else if (getToolChain().getArchName() == "i386")
769        CPUName = "i486";
770    } else if (getToolChain().getOS().startswith("netbsd"))  {
771      if (getToolChain().getArchName() == "x86_64")
772        CPUName = "x86-64";
773      else if (getToolChain().getArchName() == "i386")
774        CPUName = "i486";
775    } else {
776      if (getToolChain().getArchName() == "x86_64")
777        CPUName = "x86-64";
778      else if (getToolChain().getArchName() == "i386")
779        CPUName = "pentium4";
780    }
781  }
782
783  if (CPUName) {
784    CmdArgs.push_back("-target-cpu");
785    CmdArgs.push_back(CPUName);
786  }
787
788  for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
789         ie = Args.filtered_end(); it != ie; ++it) {
790    llvm::StringRef Name = (*it)->getOption().getName();
791    (*it)->claim();
792
793    // Skip over "-m".
794    assert(Name.startswith("-m") && "Invalid feature name.");
795    Name = Name.substr(2);
796
797    bool IsNegative = Name.startswith("no-");
798    if (IsNegative)
799      Name = Name.substr(3);
800
801    CmdArgs.push_back("-target-feature");
802    CmdArgs.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
803  }
804}
805
806static bool
807shouldUseExceptionTablesForObjCExceptions(const ArgList &Args,
808                                          const llvm::Triple &Triple) {
809  // We use the zero-cost exception tables for Objective-C if the non-fragile
810  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
811  // later.
812
813  if (Args.hasArg(options::OPT_fobjc_nonfragile_abi))
814    return true;
815
816  if (Triple.getOS() != llvm::Triple::Darwin)
817    return false;
818
819  return (Triple.getDarwinMajorNumber() >= 9 &&
820          (Triple.getArch() == llvm::Triple::x86_64 ||
821           Triple.getArch() == llvm::Triple::arm));
822}
823
824/// addExceptionArgs - Adds exception related arguments to the driver command
825/// arguments. There's a master flag, -fexceptions and also language specific
826/// flags to enable/disable C++ and Objective-C exceptions.
827/// This makes it possible to for example disable C++ exceptions but enable
828/// Objective-C exceptions.
829static void addExceptionArgs(const ArgList &Args, types::ID InputType,
830                             const llvm::Triple &Triple,
831                             bool KernelOrKext, bool IsRewriter,
832                             ArgStringList &CmdArgs) {
833  if (KernelOrKext)
834    return;
835
836  // Exceptions are enabled by default.
837  bool ExceptionsEnabled = true;
838
839  // This keeps track of whether exceptions were explicitly turned on or off.
840  bool DidHaveExplicitExceptionFlag = false;
841
842  if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
843                               options::OPT_fno_exceptions)) {
844    if (A->getOption().matches(options::OPT_fexceptions))
845      ExceptionsEnabled = true;
846    else
847      ExceptionsEnabled = false;
848
849    DidHaveExplicitExceptionFlag = true;
850  }
851
852  bool ShouldUseExceptionTables = false;
853
854  // Exception tables and cleanups can be enabled with -fexceptions even if the
855  // language itself doesn't support exceptions.
856  if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
857    ShouldUseExceptionTables = true;
858
859  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
860  // is not necessarily sensible, but follows GCC.
861  if (types::isObjC(InputType) &&
862      Args.hasFlag(options::OPT_fobjc_exceptions,
863                   options::OPT_fno_objc_exceptions,
864                   true)) {
865    CmdArgs.push_back("-fobjc-exceptions");
866
867    ShouldUseExceptionTables |=
868      shouldUseExceptionTablesForObjCExceptions(Args, Triple);
869  }
870
871  if (types::isCXX(InputType)) {
872    bool CXXExceptionsEnabled = ExceptionsEnabled;
873
874    if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
875                                 options::OPT_fno_cxx_exceptions,
876                                 options::OPT_fexceptions,
877                                 options::OPT_fno_exceptions)) {
878      if (A->getOption().matches(options::OPT_fcxx_exceptions))
879        CXXExceptionsEnabled = true;
880      else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
881        CXXExceptionsEnabled = false;
882    }
883
884    if (CXXExceptionsEnabled) {
885      CmdArgs.push_back("-fcxx-exceptions");
886
887      ShouldUseExceptionTables = true;
888    }
889  }
890
891  if (ShouldUseExceptionTables)
892    CmdArgs.push_back("-fexceptions");
893}
894
895void Clang::ConstructJob(Compilation &C, const JobAction &JA,
896                         const InputInfo &Output,
897                         const InputInfoList &Inputs,
898                         const ArgList &Args,
899                         const char *LinkingOutput) const {
900  bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
901                                  options::OPT_fapple_kext);
902  const Driver &D = getToolChain().getDriver();
903  ArgStringList CmdArgs;
904
905  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
906
907  // Invoke ourselves in -cc1 mode.
908  //
909  // FIXME: Implement custom jobs for internal actions.
910  CmdArgs.push_back("-cc1");
911
912  // Add the "effective" target triple.
913  CmdArgs.push_back("-triple");
914  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
915  CmdArgs.push_back(Args.MakeArgString(TripleStr));
916
917  // Select the appropriate action.
918  bool IsRewriter = false;
919  if (isa<AnalyzeJobAction>(JA)) {
920    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
921    CmdArgs.push_back("-analyze");
922  } else if (isa<PreprocessJobAction>(JA)) {
923    if (Output.getType() == types::TY_Dependencies)
924      CmdArgs.push_back("-Eonly");
925    else
926      CmdArgs.push_back("-E");
927  } else if (isa<AssembleJobAction>(JA)) {
928    CmdArgs.push_back("-emit-obj");
929
930    // At -O0, we use -mrelax-all by default.
931    bool IsOpt = false;
932    if (Arg *A = Args.getLastArg(options::OPT_O_Group))
933      IsOpt = !A->getOption().matches(options::OPT_O0);
934    if (Args.hasFlag(options::OPT_mrelax_all,
935                      options::OPT_mno_relax_all,
936                      !IsOpt))
937      CmdArgs.push_back("-mrelax-all");
938
939    // When using an integrated assembler, translate -Wa, and -Xassembler
940    // options.
941    for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
942                                               options::OPT_Xassembler),
943           ie = Args.filtered_end(); it != ie; ++it) {
944      const Arg *A = *it;
945      A->claim();
946
947      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
948        llvm::StringRef Value = A->getValue(Args, i);
949
950        if (Value == "-force_cpusubtype_ALL") {
951          // Do nothing, this is the default and we don't support anything else.
952        } else if (Value == "-L") {
953          CmdArgs.push_back("-msave-temp-labels");
954        } else {
955          D.Diag(clang::diag::err_drv_unsupported_option_argument)
956            << A->getOption().getName() << Value;
957        }
958      }
959    }
960
961    // Also ignore explicit -force_cpusubtype_ALL option.
962    (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
963  } else if (isa<PrecompileJobAction>(JA)) {
964    // Use PCH if the user requested it.
965    bool UsePCH = D.CCCUsePCH;
966
967    if (UsePCH)
968      CmdArgs.push_back("-emit-pch");
969    else
970      CmdArgs.push_back("-emit-pth");
971  } else {
972    assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
973
974    if (JA.getType() == types::TY_Nothing) {
975      CmdArgs.push_back("-fsyntax-only");
976    } else if (JA.getType() == types::TY_LLVM_IR ||
977               JA.getType() == types::TY_LTO_IR) {
978      CmdArgs.push_back("-emit-llvm");
979    } else if (JA.getType() == types::TY_LLVM_BC ||
980               JA.getType() == types::TY_LTO_BC) {
981      CmdArgs.push_back("-emit-llvm-bc");
982    } else if (JA.getType() == types::TY_PP_Asm) {
983      CmdArgs.push_back("-S");
984    } else if (JA.getType() == types::TY_AST) {
985      CmdArgs.push_back("-emit-pch");
986    } else if (JA.getType() == types::TY_RewrittenObjC) {
987      CmdArgs.push_back("-rewrite-objc");
988      IsRewriter = true;
989    } else {
990      assert(JA.getType() == types::TY_PP_Asm &&
991             "Unexpected output type!");
992    }
993  }
994
995  // The make clang go fast button.
996  CmdArgs.push_back("-disable-free");
997
998  // Disable the verification pass in -asserts builds.
999#ifdef NDEBUG
1000  CmdArgs.push_back("-disable-llvm-verifier");
1001#endif
1002
1003  // Set the main file name, so that debug info works even with
1004  // -save-temps.
1005  CmdArgs.push_back("-main-file-name");
1006  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
1007
1008  // Some flags which affect the language (via preprocessor
1009  // defines). See darwin::CC1::AddCPPArgs.
1010  if (Args.hasArg(options::OPT_static))
1011    CmdArgs.push_back("-static-define");
1012
1013  if (isa<AnalyzeJobAction>(JA)) {
1014    // Enable region store model by default.
1015    CmdArgs.push_back("-analyzer-store=region");
1016
1017    // Treat blocks as analysis entry points.
1018    CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
1019
1020    CmdArgs.push_back("-analyzer-eagerly-assume");
1021
1022    // Add default argument set.
1023    if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
1024      CmdArgs.push_back("-analyzer-checker=core");
1025      CmdArgs.push_back("-analyzer-checker=deadcode");
1026      CmdArgs.push_back("-analyzer-checker=security");
1027
1028      if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
1029        CmdArgs.push_back("-analyzer-checker=unix");
1030
1031      if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
1032        CmdArgs.push_back("-analyzer-checker=osx");
1033    }
1034
1035    // Set the output format. The default is plist, for (lame) historical
1036    // reasons.
1037    CmdArgs.push_back("-analyzer-output");
1038    if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
1039      CmdArgs.push_back(A->getValue(Args));
1040    else
1041      CmdArgs.push_back("plist");
1042
1043    // Disable the presentation of standard compiler warnings when
1044    // using --analyze.  We only want to show static analyzer diagnostics
1045    // or frontend errors.
1046    CmdArgs.push_back("-w");
1047
1048    // Add -Xanalyzer arguments when running as analyzer.
1049    Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
1050  }
1051
1052  CheckCodeGenerationOptions(D, Args);
1053
1054  // Perform argument translation for LLVM backend. This
1055  // takes some care in reconciling with llvm-gcc. The
1056  // issue is that llvm-gcc translates these options based on
1057  // the values in cc1, whereas we are processing based on
1058  // the driver arguments.
1059
1060  // This comes from the default translation the driver + cc1
1061  // would do to enable flag_pic.
1062  //
1063  // FIXME: Centralize this code.
1064  bool PICEnabled = (Args.hasArg(options::OPT_fPIC) ||
1065                     Args.hasArg(options::OPT_fpic) ||
1066                     Args.hasArg(options::OPT_fPIE) ||
1067                     Args.hasArg(options::OPT_fpie));
1068  bool PICDisabled = (Args.hasArg(options::OPT_mkernel) ||
1069                      Args.hasArg(options::OPT_static));
1070  const char *Model = getToolChain().GetForcedPicModel();
1071  if (!Model) {
1072    if (Args.hasArg(options::OPT_mdynamic_no_pic))
1073      Model = "dynamic-no-pic";
1074    else if (PICDisabled)
1075      Model = "static";
1076    else if (PICEnabled)
1077      Model = "pic";
1078    else
1079      Model = getToolChain().GetDefaultRelocationModel();
1080  }
1081  if (llvm::StringRef(Model) != "pic") {
1082    CmdArgs.push_back("-mrelocation-model");
1083    CmdArgs.push_back(Model);
1084  }
1085
1086  // Infer the __PIC__ value.
1087  //
1088  // FIXME:  This isn't quite right on Darwin, which always sets
1089  // __PIC__=2.
1090  if (strcmp(Model, "pic") == 0 || strcmp(Model, "dynamic-no-pic") == 0) {
1091    CmdArgs.push_back("-pic-level");
1092    CmdArgs.push_back(Args.hasArg(options::OPT_fPIC) ? "2" : "1");
1093  }
1094  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
1095                    options::OPT_fno_merge_all_constants))
1096    CmdArgs.push_back("-no-merge-all-constants");
1097
1098  // LLVM Code Generator Options.
1099
1100  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1101    CmdArgs.push_back("-mregparm");
1102    CmdArgs.push_back(A->getValue(Args));
1103  }
1104
1105  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
1106    CmdArgs.push_back("-mrtd");
1107
1108  // FIXME: Set --enable-unsafe-fp-math.
1109  if (Args.hasFlag(options::OPT_fno_omit_frame_pointer,
1110                   options::OPT_fomit_frame_pointer))
1111    CmdArgs.push_back("-mdisable-fp-elim");
1112  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
1113                    options::OPT_fno_zero_initialized_in_bss))
1114    CmdArgs.push_back("-mno-zero-initialized-in-bss");
1115  if (!Args.hasFlag(options::OPT_fstrict_aliasing,
1116                    options::OPT_fno_strict_aliasing,
1117                    getToolChain().IsStrictAliasingDefault()))
1118    CmdArgs.push_back("-relaxed-aliasing");
1119
1120  // Decide whether to use verbose asm. Verbose assembly is the default on
1121  // toolchains which have the integrated assembler on by default.
1122  bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
1123  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
1124                   IsVerboseAsmDefault) ||
1125      Args.hasArg(options::OPT_dA))
1126    CmdArgs.push_back("-masm-verbose");
1127
1128  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
1129    CmdArgs.push_back("-mdebug-pass");
1130    CmdArgs.push_back("Structure");
1131  }
1132  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
1133    CmdArgs.push_back("-mdebug-pass");
1134    CmdArgs.push_back("Arguments");
1135  }
1136
1137  // Enable -mconstructor-aliases except on darwin, where we have to
1138  // work around a linker bug;  see <rdar://problem/7651567>.
1139  if (getToolChain().getTriple().getOS() != llvm::Triple::Darwin)
1140    CmdArgs.push_back("-mconstructor-aliases");
1141
1142  // Darwin's kernel doesn't support guard variables; just die if we
1143  // try to use them.
1144  if (KernelOrKext &&
1145      getToolChain().getTriple().getOS() == llvm::Triple::Darwin)
1146    CmdArgs.push_back("-fforbid-guard-variables");
1147
1148  if (Args.hasArg(options::OPT_mms_bitfields)) {
1149    CmdArgs.push_back("-mms-bitfields");
1150  }
1151
1152  // This is a coarse approximation of what llvm-gcc actually does, both
1153  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
1154  // complicated ways.
1155  bool AsynchronousUnwindTables =
1156    Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
1157                 options::OPT_fno_asynchronous_unwind_tables,
1158                 getToolChain().IsUnwindTablesDefault() &&
1159                 !KernelOrKext);
1160  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
1161                   AsynchronousUnwindTables))
1162    CmdArgs.push_back("-munwind-tables");
1163
1164  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
1165    CmdArgs.push_back("-mlimit-float-precision");
1166    CmdArgs.push_back(A->getValue(Args));
1167  }
1168
1169  // FIXME: Handle -mtune=.
1170  (void) Args.hasArg(options::OPT_mtune_EQ);
1171
1172  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
1173    CmdArgs.push_back("-mcode-model");
1174    CmdArgs.push_back(A->getValue(Args));
1175  }
1176
1177  // Add target specific cpu and features flags.
1178  switch(getToolChain().getTriple().getArch()) {
1179  default:
1180    break;
1181
1182  case llvm::Triple::arm:
1183  case llvm::Triple::thumb:
1184    AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
1185    break;
1186
1187  case llvm::Triple::mips:
1188  case llvm::Triple::mipsel:
1189    AddMIPSTargetArgs(Args, CmdArgs);
1190    break;
1191
1192  case llvm::Triple::sparc:
1193    AddSparcTargetArgs(Args, CmdArgs);
1194    break;
1195
1196  case llvm::Triple::x86:
1197  case llvm::Triple::x86_64:
1198    AddX86TargetArgs(Args, CmdArgs);
1199    break;
1200  }
1201
1202  // Pass the linker version in use.
1203  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
1204    CmdArgs.push_back("-target-linker-version");
1205    CmdArgs.push_back(A->getValue(Args));
1206  }
1207
1208  // -mno-omit-leaf-frame-pointer is the default on Darwin.
1209  if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1210                   options::OPT_mno_omit_leaf_frame_pointer,
1211                   getToolChain().getTriple().getOS() != llvm::Triple::Darwin))
1212    CmdArgs.push_back("-momit-leaf-frame-pointer");
1213
1214  // -fno-math-errno is default.
1215  if (Args.hasFlag(options::OPT_fmath_errno,
1216                   options::OPT_fno_math_errno,
1217                   false))
1218    CmdArgs.push_back("-fmath-errno");
1219
1220  // Explicitly error on some things we know we don't support and can't just
1221  // ignore.
1222  types::ID InputType = Inputs[0].getType();
1223  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
1224    Arg *Unsupported;
1225    if ((Unsupported = Args.getLastArg(options::OPT_MG)) ||
1226        (Unsupported = Args.getLastArg(options::OPT_iframework)))
1227      D.Diag(clang::diag::err_drv_clang_unsupported)
1228        << Unsupported->getOption().getName();
1229
1230    if (types::isCXX(InputType) &&
1231        getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1232        getToolChain().getTriple().getArch() == llvm::Triple::x86) {
1233      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)))
1234        D.Diag(clang::diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
1235          << Unsupported->getOption().getName();
1236    }
1237  }
1238
1239  Args.AddAllArgs(CmdArgs, options::OPT_v);
1240  Args.AddLastArg(CmdArgs, options::OPT_H);
1241  if (D.CCPrintHeaders) {
1242    CmdArgs.push_back("-header-include-file");
1243    CmdArgs.push_back(D.CCPrintHeadersFilename ?
1244                      D.CCPrintHeadersFilename : "-");
1245  }
1246  Args.AddLastArg(CmdArgs, options::OPT_P);
1247  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
1248
1249  if (D.CCLogDiagnostics) {
1250    CmdArgs.push_back("-diagnostic-log-file");
1251    CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
1252                      D.CCLogDiagnosticsFilename : "-");
1253  }
1254
1255  // Special case debug options to only pass -g to clang. This is
1256  // wrong.
1257  Args.ClaimAllArgs(options::OPT_g_Group);
1258  if (Arg *A = Args.getLastArg(options::OPT_g_Group))
1259    if (!A->getOption().matches(options::OPT_g0))
1260      CmdArgs.push_back("-g");
1261
1262  Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
1263  Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
1264
1265  Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
1266
1267  Args.AddLastArg(CmdArgs, options::OPT_nostdinc);
1268  Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
1269  Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
1270
1271  // Pass the path to compiler resource files.
1272  CmdArgs.push_back("-resource-dir");
1273  CmdArgs.push_back(D.ResourceDir.c_str());
1274
1275  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
1276
1277  // Add preprocessing options like -I, -D, etc. if we are using the
1278  // preprocessor.
1279  //
1280  // FIXME: Support -fpreprocessed
1281  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
1282    AddPreprocessingOptions(D, Args, CmdArgs, Output, Inputs);
1283
1284  // Manually translate -O to -O2 and -O4 to -O3; let clang reject
1285  // others.
1286  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1287    if (A->getOption().matches(options::OPT_O4))
1288      CmdArgs.push_back("-O3");
1289    else if (A->getOption().matches(options::OPT_O) &&
1290             A->getValue(Args)[0] == '\0')
1291      CmdArgs.push_back("-O2");
1292    else if (A->getOption().matches(options::OPT_O) &&
1293             A->getValue(Args)[0] == 'z' &&
1294             A->getValue(Args)[1] == '\0')
1295      CmdArgs.push_back("-Os");
1296    else
1297      A->render(Args, CmdArgs);
1298  }
1299
1300  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
1301  Args.AddLastArg(CmdArgs, options::OPT_pedantic);
1302  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
1303  Args.AddLastArg(CmdArgs, options::OPT_w);
1304
1305  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
1306  // (-ansi is equivalent to -std=c89).
1307  //
1308  // If a std is supplied, only add -trigraphs if it follows the
1309  // option.
1310  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1311    if (Std->getOption().matches(options::OPT_ansi))
1312      if (types::isCXX(InputType))
1313        CmdArgs.push_back("-std=c++98");
1314      else
1315        CmdArgs.push_back("-std=c89");
1316    else
1317      Std->render(Args, CmdArgs);
1318
1319    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
1320                                 options::OPT_trigraphs))
1321      if (A != Std)
1322        A->render(Args, CmdArgs);
1323  } else {
1324    // Honor -std-default.
1325    //
1326    // FIXME: Clang doesn't correctly handle -std= when the input language
1327    // doesn't match. For the time being just ignore this for C++ inputs;
1328    // eventually we want to do all the standard defaulting here instead of
1329    // splitting it between the driver and clang -cc1.
1330    if (!types::isCXX(InputType))
1331        Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1332                                  "-std=", /*Joined=*/true);
1333    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
1334  }
1335
1336  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
1337  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
1338    if (Asm->getOption().matches(options::OPT_fasm))
1339      CmdArgs.push_back("-fgnu-keywords");
1340    else
1341      CmdArgs.push_back("-fno-gnu-keywords");
1342  }
1343
1344  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_)) {
1345    CmdArgs.push_back("-ftemplate-depth");
1346    CmdArgs.push_back(A->getValue(Args));
1347  }
1348
1349  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
1350                               options::OPT_Wlarge_by_value_copy_def)) {
1351    CmdArgs.push_back("-Wlarge-by-value-copy");
1352    if (A->getNumValues())
1353      CmdArgs.push_back(A->getValue(Args));
1354    else
1355      CmdArgs.push_back("64"); // default value for -Wlarge-by-value-copy.
1356  }
1357
1358  if (Args.hasArg(options::OPT__relocatable_pch))
1359    CmdArgs.push_back("-relocatable-pch");
1360
1361  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
1362    CmdArgs.push_back("-fconstant-string-class");
1363    CmdArgs.push_back(A->getValue(Args));
1364  }
1365
1366  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
1367    CmdArgs.push_back("-ftabstop");
1368    CmdArgs.push_back(A->getValue(Args));
1369  }
1370
1371  CmdArgs.push_back("-ferror-limit");
1372  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
1373    CmdArgs.push_back(A->getValue(Args));
1374  else
1375    CmdArgs.push_back("19");
1376
1377  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
1378    CmdArgs.push_back("-fmacro-backtrace-limit");
1379    CmdArgs.push_back(A->getValue(Args));
1380  }
1381
1382  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
1383    CmdArgs.push_back("-ftemplate-backtrace-limit");
1384    CmdArgs.push_back(A->getValue(Args));
1385  }
1386
1387  // Pass -fmessage-length=.
1388  CmdArgs.push_back("-fmessage-length");
1389  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
1390    CmdArgs.push_back(A->getValue(Args));
1391  } else {
1392    // If -fmessage-length=N was not specified, determine whether this is a
1393    // terminal and, if so, implicitly define -fmessage-length appropriately.
1394    unsigned N = llvm::sys::Process::StandardErrColumns();
1395    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(N)));
1396  }
1397
1398  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
1399    CmdArgs.push_back("-fvisibility");
1400    CmdArgs.push_back(A->getValue(Args));
1401  }
1402
1403  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
1404
1405  // -fhosted is default.
1406  if (KernelOrKext || Args.hasFlag(options::OPT_ffreestanding,
1407                                   options::OPT_fhosted,
1408                                   false))
1409    CmdArgs.push_back("-ffreestanding");
1410
1411  // Forward -f (flag) options which we can pass directly.
1412  Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
1413  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
1414  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
1415  Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
1416  if (getToolChain().SupportsProfiling())
1417    Args.AddLastArg(CmdArgs, options::OPT_pg);
1418
1419  // -flax-vector-conversions is default.
1420  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
1421                    options::OPT_fno_lax_vector_conversions))
1422    CmdArgs.push_back("-fno-lax-vector-conversions");
1423
1424  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
1425  // takes precedence.
1426  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
1427  if (!GCArg)
1428    GCArg = Args.getLastArg(options::OPT_fobjc_gc);
1429  if (GCArg) {
1430    if (getToolChain().SupportsObjCGC()) {
1431      GCArg->render(Args, CmdArgs);
1432    } else {
1433      // FIXME: We should move this to a hard error.
1434      D.Diag(clang::diag::warn_drv_objc_gc_unsupported)
1435        << GCArg->getAsString(Args);
1436    }
1437  }
1438
1439  if (Args.getLastArg(options::OPT_fapple_kext))
1440    CmdArgs.push_back("-fapple-kext");
1441
1442  Args.AddLastArg(CmdArgs, options::OPT_fno_show_column);
1443  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
1444  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
1445  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
1446  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
1447  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
1448
1449  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
1450    CmdArgs.push_back("-ftrapv-handler");
1451    CmdArgs.push_back(A->getValue(Args));
1452  }
1453
1454  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
1455  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
1456  if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
1457                               options::OPT_fno_wrapv)) {
1458    if (A->getOption().matches(options::OPT_fwrapv))
1459      CmdArgs.push_back("-fwrapv");
1460  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
1461                                      options::OPT_fno_strict_overflow)) {
1462    if (A->getOption().matches(options::OPT_fno_strict_overflow))
1463      CmdArgs.push_back("-fwrapv");
1464  }
1465  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
1466  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
1467
1468  Args.AddLastArg(CmdArgs, options::OPT_pthread);
1469
1470  // -stack-protector=0 is default.
1471  unsigned StackProtectorLevel = 0;
1472  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
1473                               options::OPT_fstack_protector_all,
1474                               options::OPT_fstack_protector)) {
1475    if (A->getOption().matches(options::OPT_fstack_protector))
1476      StackProtectorLevel = 1;
1477    else if (A->getOption().matches(options::OPT_fstack_protector_all))
1478      StackProtectorLevel = 2;
1479  } else
1480    StackProtectorLevel = getToolChain().GetDefaultStackProtectorLevel();
1481  if (StackProtectorLevel) {
1482    CmdArgs.push_back("-stack-protector");
1483    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(StackProtectorLevel)));
1484  }
1485
1486  // Forward -f options with positive and negative forms; we translate
1487  // these by hand.
1488
1489  if (Args.hasArg(options::OPT_mkernel)) {
1490    if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
1491      CmdArgs.push_back("-fapple-kext");
1492    if (!Args.hasArg(options::OPT_fbuiltin))
1493      CmdArgs.push_back("-fno-builtin");
1494  }
1495  // -fbuiltin is default.
1496  else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
1497    CmdArgs.push_back("-fno-builtin");
1498
1499  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1500                    options::OPT_fno_assume_sane_operator_new))
1501    CmdArgs.push_back("-fno-assume-sane-operator-new");
1502
1503  // -fblocks=0 is default.
1504  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
1505                   getToolChain().IsBlocksDefault()) ||
1506        (Args.hasArg(options::OPT_fgnu_runtime) &&
1507         Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
1508         !Args.hasArg(options::OPT_fno_blocks))) {
1509    CmdArgs.push_back("-fblocks");
1510  }
1511
1512  // -faccess-control is default.
1513  if (Args.hasFlag(options::OPT_fno_access_control,
1514                   options::OPT_faccess_control,
1515                   false))
1516    CmdArgs.push_back("-fno-access-control");
1517
1518  // -felide-constructors is the default.
1519  if (Args.hasFlag(options::OPT_fno_elide_constructors,
1520                   options::OPT_felide_constructors,
1521                   false))
1522    CmdArgs.push_back("-fno-elide-constructors");
1523
1524  // Add exception args.
1525  addExceptionArgs(Args, InputType, getToolChain().getTriple(),
1526                   KernelOrKext, IsRewriter, CmdArgs);
1527
1528  if (getToolChain().UseSjLjExceptions())
1529    CmdArgs.push_back("-fsjlj-exceptions");
1530
1531  // -frtti is default.
1532  if (KernelOrKext ||
1533      !Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti))
1534    CmdArgs.push_back("-fno-rtti");
1535
1536  // -fshort-enums=0 is default.
1537  // FIXME: Are there targers where -fshort-enums is on by default ?
1538  if (Args.hasFlag(options::OPT_fshort_enums,
1539                   options::OPT_fno_short_enums, false))
1540    CmdArgs.push_back("-fshort-enums");
1541
1542  // -fsigned-char is default.
1543  if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
1544                    isSignedCharDefault(getToolChain().getTriple())))
1545    CmdArgs.push_back("-fno-signed-char");
1546
1547  // -fthreadsafe-static is default.
1548  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
1549                    options::OPT_fno_threadsafe_statics))
1550    CmdArgs.push_back("-fno-threadsafe-statics");
1551
1552  // -fuse-cxa-atexit is default.
1553  if (KernelOrKext ||
1554    !Args.hasFlag(options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
1555                  getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
1556                  getToolChain().getTriple().getOS() != llvm::Triple::MinGW32))
1557    CmdArgs.push_back("-fno-use-cxa-atexit");
1558
1559  // -fms-extensions=0 is default.
1560  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1561                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
1562    CmdArgs.push_back("-fms-extensions");
1563
1564  // -fmsc-version=1300 is default.
1565  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1566                   getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
1567      Args.hasArg(options::OPT_fmsc_version)) {
1568    llvm::StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
1569    if (msc_ver.empty())
1570      CmdArgs.push_back("-fmsc-version=1300");
1571    else
1572      CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
1573  }
1574
1575
1576  // -fborland-extensions=0 is default.
1577  if (Args.hasFlag(options::OPT_fborland_extensions,
1578                   options::OPT_fno_borland_extensions, false))
1579    CmdArgs.push_back("-fborland-extensions");
1580
1581  // -fgnu-keywords default varies depending on language; only pass if
1582  // specified.
1583  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
1584                               options::OPT_fno_gnu_keywords))
1585    A->render(Args, CmdArgs);
1586
1587  // -fnext-runtime defaults to on Darwin and when rewriting Objective-C, and is
1588  // -the -cc1 default.
1589  bool NeXTRuntimeIsDefault =
1590    IsRewriter || getToolChain().getTriple().getOS() == llvm::Triple::Darwin;
1591  if (!Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
1592                    NeXTRuntimeIsDefault))
1593    CmdArgs.push_back("-fgnu-runtime");
1594
1595  // -fobjc-nonfragile-abi=0 is default.
1596  if (types::isObjC(InputType)) {
1597    // Compute the Objective-C ABI "version" to use. Version numbers are
1598    // slightly confusing for historical reasons:
1599    //   1 - Traditional "fragile" ABI
1600    //   2 - Non-fragile ABI, version 1
1601    //   3 - Non-fragile ABI, version 2
1602    unsigned Version = 1;
1603    // If -fobjc-abi-version= is present, use that to set the version.
1604    if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
1605      if (llvm::StringRef(A->getValue(Args)) == "1")
1606        Version = 1;
1607      else if (llvm::StringRef(A->getValue(Args)) == "2")
1608        Version = 2;
1609      else if (llvm::StringRef(A->getValue(Args)) == "3")
1610        Version = 3;
1611      else
1612        D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1613    } else {
1614      // Otherwise, determine if we are using the non-fragile ABI.
1615      if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi,
1616                       options::OPT_fno_objc_nonfragile_abi,
1617                       getToolChain().IsObjCNonFragileABIDefault())) {
1618        // Determine the non-fragile ABI version to use.
1619#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
1620        unsigned NonFragileABIVersion = 1;
1621#else
1622        unsigned NonFragileABIVersion = 2;
1623#endif
1624
1625        if (Arg *A = Args.getLastArg(
1626              options::OPT_fobjc_nonfragile_abi_version_EQ)) {
1627          if (llvm::StringRef(A->getValue(Args)) == "1")
1628            NonFragileABIVersion = 1;
1629          else if (llvm::StringRef(A->getValue(Args)) == "2")
1630            NonFragileABIVersion = 2;
1631          else
1632            D.Diag(clang::diag::err_drv_clang_unsupported)
1633              << A->getAsString(Args);
1634        }
1635
1636        Version = 1 + NonFragileABIVersion;
1637      } else {
1638        Version = 1;
1639      }
1640    }
1641
1642    if (Version == 2 || Version == 3) {
1643      CmdArgs.push_back("-fobjc-nonfragile-abi");
1644
1645      // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
1646      // legacy is the default.
1647      if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
1648                        options::OPT_fno_objc_legacy_dispatch,
1649                        getToolChain().IsObjCLegacyDispatchDefault())) {
1650        if (getToolChain().UseObjCMixedDispatch())
1651          CmdArgs.push_back("-fobjc-dispatch-method=mixed");
1652        else
1653          CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
1654      }
1655    }
1656
1657    // -fobjc-default-synthesize-properties=0 is default.
1658    if (Args.hasFlag(options::OPT_fobjc_default_synthesize_properties,
1659                     options::OPT_fno_objc_default_synthesize_properties,
1660                     getToolChain().IsObjCDefaultSynthPropertiesDefault())) {
1661      CmdArgs.push_back("-fobjc-default-synthesize-properties");
1662    }
1663  }
1664
1665  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1666                    options::OPT_fno_assume_sane_operator_new))
1667    CmdArgs.push_back("-fno-assume-sane-operator-new");
1668
1669  // -fconstant-cfstrings is default, and may be subject to argument translation
1670  // on Darwin.
1671  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
1672                    options::OPT_fno_constant_cfstrings) ||
1673      !Args.hasFlag(options::OPT_mconstant_cfstrings,
1674                    options::OPT_mno_constant_cfstrings))
1675    CmdArgs.push_back("-fno-constant-cfstrings");
1676
1677  // -fshort-wchar default varies depending on platform; only
1678  // pass if specified.
1679  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
1680    A->render(Args, CmdArgs);
1681
1682  // -fno-pascal-strings is default, only pass non-default. If the tool chain
1683  // happened to translate to -mpascal-strings, we want to back translate here.
1684  //
1685  // FIXME: This is gross; that translation should be pulled from the
1686  // tool chain.
1687  if (Args.hasFlag(options::OPT_fpascal_strings,
1688                   options::OPT_fno_pascal_strings,
1689                   false) ||
1690      Args.hasFlag(options::OPT_mpascal_strings,
1691                   options::OPT_mno_pascal_strings,
1692                   false))
1693    CmdArgs.push_back("-fpascal-strings");
1694
1695  if (Args.hasArg(options::OPT_mkernel) ||
1696      Args.hasArg(options::OPT_fapple_kext)) {
1697    if (!Args.hasArg(options::OPT_fcommon))
1698      CmdArgs.push_back("-fno-common");
1699  }
1700  // -fcommon is default, only pass non-default.
1701  else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
1702    CmdArgs.push_back("-fno-common");
1703
1704  // -fsigned-bitfields is default, and clang doesn't yet support
1705  // -funsigned-bitfields.
1706  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
1707                    options::OPT_funsigned_bitfields))
1708    D.Diag(clang::diag::warn_drv_clang_unsupported)
1709      << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
1710
1711  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
1712  if (!Args.hasFlag(options::OPT_ffor_scope,
1713                    options::OPT_fno_for_scope))
1714    D.Diag(clang::diag::err_drv_clang_unsupported)
1715      << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
1716
1717  // -fcaret-diagnostics is default.
1718  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
1719                    options::OPT_fno_caret_diagnostics, true))
1720    CmdArgs.push_back("-fno-caret-diagnostics");
1721
1722  // -fdiagnostics-fixit-info is default, only pass non-default.
1723  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
1724                    options::OPT_fno_diagnostics_fixit_info))
1725    CmdArgs.push_back("-fno-diagnostics-fixit-info");
1726
1727  // Enable -fdiagnostics-show-option by default.
1728  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
1729                   options::OPT_fno_diagnostics_show_option))
1730    CmdArgs.push_back("-fdiagnostics-show-option");
1731
1732  if (const Arg *A =
1733        Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
1734    CmdArgs.push_back("-fdiagnostics-show-category");
1735    CmdArgs.push_back(A->getValue(Args));
1736  }
1737
1738  if (Arg *A = Args.getLastArg(
1739      options::OPT_fdiagnostics_show_note_include_stack,
1740      options::OPT_fno_diagnostics_show_note_include_stack)) {
1741    if (A->getOption().matches(
1742        options::OPT_fdiagnostics_show_note_include_stack))
1743      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
1744    else
1745      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
1746  }
1747
1748  // Color diagnostics are the default, unless the terminal doesn't support
1749  // them.
1750  if (Args.hasFlag(options::OPT_fcolor_diagnostics,
1751                   options::OPT_fno_color_diagnostics,
1752                   llvm::sys::Process::StandardErrHasColors()))
1753    CmdArgs.push_back("-fcolor-diagnostics");
1754
1755  if (!Args.hasFlag(options::OPT_fshow_source_location,
1756                    options::OPT_fno_show_source_location))
1757    CmdArgs.push_back("-fno-show-source-location");
1758
1759  if (!Args.hasFlag(options::OPT_fspell_checking,
1760                    options::OPT_fno_spell_checking))
1761    CmdArgs.push_back("-fno-spell-checking");
1762
1763
1764  // Silently ignore -fasm-blocks for now.
1765  (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
1766                      false);
1767
1768  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
1769    A->render(Args, CmdArgs);
1770
1771  // -fdollars-in-identifiers default varies depending on platform and
1772  // language; only pass if specified.
1773  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
1774                               options::OPT_fno_dollars_in_identifiers)) {
1775    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
1776      CmdArgs.push_back("-fdollars-in-identifiers");
1777    else
1778      CmdArgs.push_back("-fno-dollars-in-identifiers");
1779  }
1780
1781  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
1782  // practical purposes.
1783  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
1784                               options::OPT_fno_unit_at_a_time)) {
1785    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
1786      D.Diag(clang::diag::warn_drv_clang_unsupported) << A->getAsString(Args);
1787  }
1788
1789  // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
1790  //
1791  // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
1792#if 0
1793  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1794      (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
1795       getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
1796    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
1797      CmdArgs.push_back("-fno-builtin-strcat");
1798    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
1799      CmdArgs.push_back("-fno-builtin-strcpy");
1800  }
1801#endif
1802
1803  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
1804  if (Arg *A = Args.getLastArg(options::OPT_traditional,
1805                               options::OPT_traditional_cpp)) {
1806    if (isa<PreprocessJobAction>(JA))
1807      CmdArgs.push_back("-traditional-cpp");
1808    else
1809      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1810  }
1811
1812  Args.AddLastArg(CmdArgs, options::OPT_dM);
1813  Args.AddLastArg(CmdArgs, options::OPT_dD);
1814
1815  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
1816  // parser.
1817  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
1818  for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
1819         ie = Args.filtered_end(); it != ie; ++it) {
1820    (*it)->claim();
1821
1822    // We translate this by hand to the -cc1 argument, since nightly test uses
1823    // it and developers have been trained to spell it with -mllvm.
1824    if (llvm::StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
1825      CmdArgs.push_back("-disable-llvm-optzns");
1826    else
1827      (*it)->render(Args, CmdArgs);
1828  }
1829
1830  if (Output.getType() == types::TY_Dependencies) {
1831    // Handled with other dependency code.
1832  } else if (Output.isFilename()) {
1833    CmdArgs.push_back("-o");
1834    CmdArgs.push_back(Output.getFilename());
1835  } else {
1836    assert(Output.isNothing() && "Invalid output.");
1837  }
1838
1839  for (InputInfoList::const_iterator
1840         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
1841    const InputInfo &II = *it;
1842    CmdArgs.push_back("-x");
1843    CmdArgs.push_back(types::getTypeName(II.getType()));
1844    if (II.isFilename())
1845      CmdArgs.push_back(II.getFilename());
1846    else
1847      II.getInputArg().renderAsInput(Args, CmdArgs);
1848  }
1849
1850  Args.AddAllArgs(CmdArgs, options::OPT_undef);
1851
1852  const char *Exec = getToolChain().getDriver().getClangProgramPath();
1853
1854  // Optionally embed the -cc1 level arguments into the debug info, for build
1855  // analysis.
1856  if (getToolChain().UseDwarfDebugFlags()) {
1857    ArgStringList OriginalArgs;
1858    for (ArgList::const_iterator it = Args.begin(),
1859           ie = Args.end(); it != ie; ++it)
1860      (*it)->render(Args, OriginalArgs);
1861
1862    llvm::SmallString<256> Flags;
1863    Flags += Exec;
1864    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
1865      Flags += " ";
1866      Flags += OriginalArgs[i];
1867    }
1868    CmdArgs.push_back("-dwarf-debug-flags");
1869    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
1870  }
1871
1872  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
1873
1874  if (Arg *A = Args.getLastArg(options::OPT_pg))
1875    if (Args.hasArg(options::OPT_fomit_frame_pointer))
1876      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
1877        << "-fomit-frame-pointer" << A->getAsString(Args);
1878
1879  // Claim some arguments which clang supports automatically.
1880
1881  // -fpch-preprocess is used with gcc to add a special marker in the output to
1882  // include the PCH file. Clang's PTH solution is completely transparent, so we
1883  // do not need to deal with it at all.
1884  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
1885
1886  // Claim some arguments which clang doesn't support, but we don't
1887  // care to warn the user about.
1888  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
1889  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
1890
1891  // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
1892  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
1893  Args.ClaimAllArgs(options::OPT_emit_llvm);
1894}
1895
1896void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
1897                           const InputInfo &Output,
1898                           const InputInfoList &Inputs,
1899                           const ArgList &Args,
1900                           const char *LinkingOutput) const {
1901  ArgStringList CmdArgs;
1902
1903  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
1904  const InputInfo &Input = Inputs[0];
1905
1906  // Don't warn about "clang -w -c foo.s"
1907  Args.ClaimAllArgs(options::OPT_w);
1908  // and "clang -emit-llvm -c foo.s"
1909  Args.ClaimAllArgs(options::OPT_emit_llvm);
1910  // and "clang -use-gold-plugin -c foo.s"
1911  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
1912
1913  // Invoke ourselves in -cc1as mode.
1914  //
1915  // FIXME: Implement custom jobs for internal actions.
1916  CmdArgs.push_back("-cc1as");
1917
1918  // Add the "effective" target triple.
1919  CmdArgs.push_back("-triple");
1920  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1921  CmdArgs.push_back(Args.MakeArgString(TripleStr));
1922
1923  // Set the output mode, we currently only expect to be used as a real
1924  // assembler.
1925  CmdArgs.push_back("-filetype");
1926  CmdArgs.push_back("obj");
1927
1928  // At -O0, we use -mrelax-all by default.
1929  bool IsOpt = false;
1930  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1931    IsOpt = !A->getOption().matches(options::OPT_O0);
1932  if (Args.hasFlag(options::OPT_mrelax_all,
1933                    options::OPT_mno_relax_all,
1934                    !IsOpt))
1935    CmdArgs.push_back("-relax-all");
1936
1937  // Ignore explicit -force_cpusubtype_ALL option.
1938  (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
1939
1940  // FIXME: Add -g support, once we have it.
1941
1942  // FIXME: Add -static support, once we have it.
1943
1944  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
1945                       options::OPT_Xassembler);
1946
1947  assert(Output.isFilename() && "Unexpected lipo output.");
1948  CmdArgs.push_back("-o");
1949  CmdArgs.push_back(Output.getFilename());
1950
1951  assert(Input.isFilename() && "Invalid input.");
1952  CmdArgs.push_back(Input.getFilename());
1953
1954  const char *Exec = getToolChain().getDriver().getClangProgramPath();
1955  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
1956}
1957
1958void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
1959                               const InputInfo &Output,
1960                               const InputInfoList &Inputs,
1961                               const ArgList &Args,
1962                               const char *LinkingOutput) const {
1963  const Driver &D = getToolChain().getDriver();
1964  ArgStringList CmdArgs;
1965
1966  for (ArgList::const_iterator
1967         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
1968    Arg *A = *it;
1969    if (A->getOption().hasForwardToGCC()) {
1970      // Don't forward any -g arguments to assembly steps.
1971      if (isa<AssembleJobAction>(JA) &&
1972          A->getOption().matches(options::OPT_g_Group))
1973        continue;
1974
1975      // It is unfortunate that we have to claim here, as this means
1976      // we will basically never report anything interesting for
1977      // platforms using a generic gcc, even if we are just using gcc
1978      // to get to the assembler.
1979      A->claim();
1980      A->render(Args, CmdArgs);
1981    }
1982  }
1983
1984  RenderExtraToolArgs(JA, CmdArgs);
1985
1986  // If using a driver driver, force the arch.
1987  const std::string &Arch = getToolChain().getArchName();
1988  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin) {
1989    CmdArgs.push_back("-arch");
1990
1991    // FIXME: Remove these special cases.
1992    if (Arch == "powerpc")
1993      CmdArgs.push_back("ppc");
1994    else if (Arch == "powerpc64")
1995      CmdArgs.push_back("ppc64");
1996    else
1997      CmdArgs.push_back(Args.MakeArgString(Arch));
1998  }
1999
2000  // Try to force gcc to match the tool chain we want, if we recognize
2001  // the arch.
2002  //
2003  // FIXME: The triple class should directly provide the information we want
2004  // here.
2005  if (Arch == "i386" || Arch == "powerpc")
2006    CmdArgs.push_back("-m32");
2007  else if (Arch == "x86_64" || Arch == "powerpc64")
2008    CmdArgs.push_back("-m64");
2009
2010  if (Output.isFilename()) {
2011    CmdArgs.push_back("-o");
2012    CmdArgs.push_back(Output.getFilename());
2013  } else {
2014    assert(Output.isNothing() && "Unexpected output");
2015    CmdArgs.push_back("-fsyntax-only");
2016  }
2017
2018
2019  // Only pass -x if gcc will understand it; otherwise hope gcc
2020  // understands the suffix correctly. The main use case this would go
2021  // wrong in is for linker inputs if they happened to have an odd
2022  // suffix; really the only way to get this to happen is a command
2023  // like '-x foobar a.c' which will treat a.c like a linker input.
2024  //
2025  // FIXME: For the linker case specifically, can we safely convert
2026  // inputs into '-Wl,' options?
2027  for (InputInfoList::const_iterator
2028         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2029    const InputInfo &II = *it;
2030
2031    // Don't try to pass LLVM or AST inputs to a generic gcc.
2032    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
2033        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
2034      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2035        << getToolChain().getTripleString();
2036    else if (II.getType() == types::TY_AST)
2037      D.Diag(clang::diag::err_drv_no_ast_support)
2038        << getToolChain().getTripleString();
2039
2040    if (types::canTypeBeUserSpecified(II.getType())) {
2041      CmdArgs.push_back("-x");
2042      CmdArgs.push_back(types::getTypeName(II.getType()));
2043    }
2044
2045    if (II.isFilename())
2046      CmdArgs.push_back(II.getFilename());
2047    else {
2048      const Arg &A = II.getInputArg();
2049
2050      // Reverse translate some rewritten options.
2051      if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
2052        CmdArgs.push_back("-lstdc++");
2053        continue;
2054      }
2055
2056      // Don't render as input, we need gcc to do the translations.
2057      A.render(Args, CmdArgs);
2058    }
2059  }
2060
2061  const char *GCCName = getToolChain().getDriver().getCCCGenericGCCName().c_str();
2062  const char *Exec =
2063    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
2064  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2065}
2066
2067void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
2068                                          ArgStringList &CmdArgs) const {
2069  CmdArgs.push_back("-E");
2070}
2071
2072void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
2073                                          ArgStringList &CmdArgs) const {
2074  // The type is good enough.
2075}
2076
2077void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
2078                                       ArgStringList &CmdArgs) const {
2079  const Driver &D = getToolChain().getDriver();
2080
2081  // If -flto, etc. are present then make sure not to force assembly output.
2082  if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
2083      JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
2084    CmdArgs.push_back("-c");
2085  else {
2086    if (JA.getType() != types::TY_PP_Asm)
2087      D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2088        << getTypeName(JA.getType());
2089
2090    CmdArgs.push_back("-S");
2091  }
2092}
2093
2094void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
2095                                        ArgStringList &CmdArgs) const {
2096  CmdArgs.push_back("-c");
2097}
2098
2099void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
2100                                    ArgStringList &CmdArgs) const {
2101  // The types are (hopefully) good enough.
2102}
2103
2104const char *darwin::CC1::getCC1Name(types::ID Type) const {
2105  switch (Type) {
2106  default:
2107    assert(0 && "Unexpected type for Darwin CC1 tool.");
2108  case types::TY_Asm:
2109  case types::TY_C: case types::TY_CHeader:
2110  case types::TY_PP_C: case types::TY_PP_CHeader:
2111    return "cc1";
2112  case types::TY_ObjC: case types::TY_ObjCHeader:
2113  case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader:
2114    return "cc1obj";
2115  case types::TY_CXX: case types::TY_CXXHeader:
2116  case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
2117    return "cc1plus";
2118  case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
2119  case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader:
2120    return "cc1objplus";
2121  }
2122}
2123
2124const char *darwin::CC1::getBaseInputName(const ArgList &Args,
2125                                          const InputInfoList &Inputs) {
2126  return Args.MakeArgString(
2127    llvm::sys::path::filename(Inputs[0].getBaseInput()));
2128}
2129
2130const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
2131                                          const InputInfoList &Inputs) {
2132  const char *Str = getBaseInputName(Args, Inputs);
2133
2134  if (const char *End = strrchr(Str, '.'))
2135    return Args.MakeArgString(std::string(Str, End));
2136
2137  return Str;
2138}
2139
2140const char *
2141darwin::CC1::getDependencyFileName(const ArgList &Args,
2142                                   const InputInfoList &Inputs) {
2143  // FIXME: Think about this more.
2144  std::string Res;
2145
2146  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2147    std::string Str(OutputOpt->getValue(Args));
2148
2149    Res = Str.substr(0, Str.rfind('.'));
2150  } else
2151    Res = darwin::CC1::getBaseInputStem(Args, Inputs);
2152
2153  return Args.MakeArgString(Res + ".d");
2154}
2155
2156void darwin::CC1::AddCC1Args(const ArgList &Args,
2157                             ArgStringList &CmdArgs) const {
2158  const Driver &D = getToolChain().getDriver();
2159
2160  CheckCodeGenerationOptions(D, Args);
2161
2162  // Derived from cc1 spec.
2163  if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
2164      !Args.hasArg(options::OPT_mdynamic_no_pic))
2165    CmdArgs.push_back("-fPIC");
2166
2167  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2168      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2169    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2170      CmdArgs.push_back("-fno-builtin-strcat");
2171    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2172      CmdArgs.push_back("-fno-builtin-strcpy");
2173  }
2174
2175  // gcc has some code here to deal with when no -mmacosx-version-min
2176  // and no -miphoneos-version-min is present, but this never happens
2177  // due to tool chain specific argument translation.
2178
2179  if (Args.hasArg(options::OPT_g_Flag) &&
2180      !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
2181    CmdArgs.push_back("-feliminate-unused-debug-symbols");
2182}
2183
2184void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2185                                    const InputInfoList &Inputs,
2186                                    const ArgStringList &OutputArgs) const {
2187  const Driver &D = getToolChain().getDriver();
2188
2189  // Derived from cc1_options spec.
2190  if (Args.hasArg(options::OPT_fast) ||
2191      Args.hasArg(options::OPT_fastf) ||
2192      Args.hasArg(options::OPT_fastcp))
2193    CmdArgs.push_back("-O3");
2194
2195  if (Arg *A = Args.getLastArg(options::OPT_pg))
2196    if (Args.hasArg(options::OPT_fomit_frame_pointer))
2197      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2198        << A->getAsString(Args) << "-fomit-frame-pointer";
2199
2200  AddCC1Args(Args, CmdArgs);
2201
2202  if (!Args.hasArg(options::OPT_Q))
2203    CmdArgs.push_back("-quiet");
2204
2205  CmdArgs.push_back("-dumpbase");
2206  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
2207
2208  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2209
2210  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2211  Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
2212
2213  // FIXME: The goal is to use the user provided -o if that is our
2214  // final output, otherwise to drive from the original input
2215  // name. Find a clean way to go about this.
2216  if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
2217      Args.hasArg(options::OPT_o)) {
2218    Arg *OutputOpt = Args.getLastArg(options::OPT_o);
2219    CmdArgs.push_back("-auxbase-strip");
2220    CmdArgs.push_back(OutputOpt->getValue(Args));
2221  } else {
2222    CmdArgs.push_back("-auxbase");
2223    CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
2224  }
2225
2226  Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
2227
2228  Args.AddAllArgs(CmdArgs, options::OPT_O);
2229  // FIXME: -Wall is getting some special treatment. Investigate.
2230  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2231  Args.AddLastArg(CmdArgs, options::OPT_w);
2232  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2233                  options::OPT_trigraphs);
2234  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2235    // Honor -std-default.
2236    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2237                              "-std=", /*Joined=*/true);
2238  }
2239
2240  if (Args.hasArg(options::OPT_v))
2241    CmdArgs.push_back("-version");
2242  if (Args.hasArg(options::OPT_pg) &&
2243      getToolChain().SupportsProfiling())
2244    CmdArgs.push_back("-p");
2245  Args.AddLastArg(CmdArgs, options::OPT_p);
2246
2247  // The driver treats -fsyntax-only specially.
2248  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2249      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2250    // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
2251    // used to inhibit the default -fno-builtin-str{cat,cpy}.
2252    //
2253    // FIXME: Should we grow a better way to deal with "removing" args?
2254    for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
2255                                               options::OPT_fsyntax_only),
2256           ie = Args.filtered_end(); it != ie; ++it) {
2257      if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
2258          !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
2259        (*it)->claim();
2260        (*it)->render(Args, CmdArgs);
2261      }
2262    }
2263  } else
2264    Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2265
2266  // Claim Clang only -f options, they aren't worth warning about.
2267  Args.ClaimAllArgs(options::OPT_f_clang_Group);
2268
2269  Args.AddAllArgs(CmdArgs, options::OPT_undef);
2270  if (Args.hasArg(options::OPT_Qn))
2271    CmdArgs.push_back("-fno-ident");
2272
2273  // FIXME: This isn't correct.
2274  //Args.AddLastArg(CmdArgs, options::OPT__help)
2275  //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
2276
2277  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2278
2279  // FIXME: Still don't get what is happening here. Investigate.
2280  Args.AddAllArgs(CmdArgs, options::OPT__param);
2281
2282  if (Args.hasArg(options::OPT_fmudflap) ||
2283      Args.hasArg(options::OPT_fmudflapth)) {
2284    CmdArgs.push_back("-fno-builtin");
2285    CmdArgs.push_back("-fno-merge-constants");
2286  }
2287
2288  if (Args.hasArg(options::OPT_coverage)) {
2289    CmdArgs.push_back("-fprofile-arcs");
2290    CmdArgs.push_back("-ftest-coverage");
2291  }
2292
2293  if (types::isCXX(Inputs[0].getType()))
2294    CmdArgs.push_back("-D__private_extern__=extern");
2295}
2296
2297void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2298                                    const InputInfoList &Inputs,
2299                                    const ArgStringList &OutputArgs) const {
2300  // Derived from cpp_options
2301  AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2302
2303  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2304
2305  AddCC1Args(Args, CmdArgs);
2306
2307  // NOTE: The code below has some commonality with cpp_options, but
2308  // in classic gcc style ends up sending things in different
2309  // orders. This may be a good merge candidate once we drop pedantic
2310  // compatibility.
2311
2312  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2313  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2314                  options::OPT_trigraphs);
2315  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2316    // Honor -std-default.
2317    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2318                              "-std=", /*Joined=*/true);
2319  }
2320  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2321  Args.AddLastArg(CmdArgs, options::OPT_w);
2322
2323  // The driver treats -fsyntax-only specially.
2324  Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2325
2326  // Claim Clang only -f options, they aren't worth warning about.
2327  Args.ClaimAllArgs(options::OPT_f_clang_Group);
2328
2329  if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
2330      !Args.hasArg(options::OPT_fno_working_directory))
2331    CmdArgs.push_back("-fworking-directory");
2332
2333  Args.AddAllArgs(CmdArgs, options::OPT_O);
2334  Args.AddAllArgs(CmdArgs, options::OPT_undef);
2335  if (Args.hasArg(options::OPT_save_temps))
2336    CmdArgs.push_back("-fpch-preprocess");
2337}
2338
2339void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
2340                                          ArgStringList &CmdArgs,
2341                                          const InputInfoList &Inputs) const {
2342  const Driver &D = getToolChain().getDriver();
2343
2344  CheckPreprocessingOptions(D, Args);
2345
2346  // Derived from cpp_unique_options.
2347  // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
2348  Args.AddLastArg(CmdArgs, options::OPT_C);
2349  Args.AddLastArg(CmdArgs, options::OPT_CC);
2350  if (!Args.hasArg(options::OPT_Q))
2351    CmdArgs.push_back("-quiet");
2352  Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
2353  Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
2354  Args.AddLastArg(CmdArgs, options::OPT_v);
2355  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
2356  Args.AddLastArg(CmdArgs, options::OPT_P);
2357
2358  // FIXME: Handle %I properly.
2359  if (getToolChain().getArchName() == "x86_64") {
2360    CmdArgs.push_back("-imultilib");
2361    CmdArgs.push_back("x86_64");
2362  }
2363
2364  if (Args.hasArg(options::OPT_MD)) {
2365    CmdArgs.push_back("-MD");
2366    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2367  }
2368
2369  if (Args.hasArg(options::OPT_MMD)) {
2370    CmdArgs.push_back("-MMD");
2371    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2372  }
2373
2374  Args.AddLastArg(CmdArgs, options::OPT_M);
2375  Args.AddLastArg(CmdArgs, options::OPT_MM);
2376  Args.AddAllArgs(CmdArgs, options::OPT_MF);
2377  Args.AddLastArg(CmdArgs, options::OPT_MG);
2378  Args.AddLastArg(CmdArgs, options::OPT_MP);
2379  Args.AddAllArgs(CmdArgs, options::OPT_MQ);
2380  Args.AddAllArgs(CmdArgs, options::OPT_MT);
2381  if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
2382      (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
2383    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2384      CmdArgs.push_back("-MQ");
2385      CmdArgs.push_back(OutputOpt->getValue(Args));
2386    }
2387  }
2388
2389  Args.AddLastArg(CmdArgs, options::OPT_remap);
2390  if (Args.hasArg(options::OPT_g3))
2391    CmdArgs.push_back("-dD");
2392  Args.AddLastArg(CmdArgs, options::OPT_H);
2393
2394  AddCPPArgs(Args, CmdArgs);
2395
2396  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
2397  Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
2398
2399  for (InputInfoList::const_iterator
2400         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2401    const InputInfo &II = *it;
2402
2403    CmdArgs.push_back(II.getFilename());
2404  }
2405
2406  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
2407                       options::OPT_Xpreprocessor);
2408
2409  if (Args.hasArg(options::OPT_fmudflap)) {
2410    CmdArgs.push_back("-D_MUDFLAP");
2411    CmdArgs.push_back("-include");
2412    CmdArgs.push_back("mf-runtime.h");
2413  }
2414
2415  if (Args.hasArg(options::OPT_fmudflapth)) {
2416    CmdArgs.push_back("-D_MUDFLAP");
2417    CmdArgs.push_back("-D_MUDFLAPTH");
2418    CmdArgs.push_back("-include");
2419    CmdArgs.push_back("mf-runtime.h");
2420  }
2421}
2422
2423void darwin::CC1::AddCPPArgs(const ArgList &Args,
2424                             ArgStringList &CmdArgs) const {
2425  // Derived from cpp spec.
2426
2427  if (Args.hasArg(options::OPT_static)) {
2428    // The gcc spec is broken here, it refers to dynamic but
2429    // that has been translated. Start by being bug compatible.
2430
2431    // if (!Args.hasArg(arglist.parser.dynamicOption))
2432    CmdArgs.push_back("-D__STATIC__");
2433  } else
2434    CmdArgs.push_back("-D__DYNAMIC__");
2435
2436  if (Args.hasArg(options::OPT_pthread))
2437    CmdArgs.push_back("-D_REENTRANT");
2438}
2439
2440void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
2441                                      const InputInfo &Output,
2442                                      const InputInfoList &Inputs,
2443                                      const ArgList &Args,
2444                                      const char *LinkingOutput) const {
2445  ArgStringList CmdArgs;
2446
2447  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2448
2449  CmdArgs.push_back("-E");
2450
2451  if (Args.hasArg(options::OPT_traditional) ||
2452      Args.hasArg(options::OPT_traditional_cpp))
2453    CmdArgs.push_back("-traditional-cpp");
2454
2455  ArgStringList OutputArgs;
2456  assert(Output.isFilename() && "Unexpected CC1 output.");
2457  OutputArgs.push_back("-o");
2458  OutputArgs.push_back(Output.getFilename());
2459
2460  if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
2461    AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2462  } else {
2463    AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2464    CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2465  }
2466
2467  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2468
2469  const char *CC1Name = getCC1Name(Inputs[0].getType());
2470  const char *Exec =
2471    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2472  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2473}
2474
2475void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
2476                                   const InputInfo &Output,
2477                                   const InputInfoList &Inputs,
2478                                   const ArgList &Args,
2479                                   const char *LinkingOutput) const {
2480  const Driver &D = getToolChain().getDriver();
2481  ArgStringList CmdArgs;
2482
2483  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2484
2485  types::ID InputType = Inputs[0].getType();
2486  const Arg *A;
2487  if ((A = Args.getLastArg(options::OPT_traditional)))
2488    D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2489      << A->getAsString(Args) << "-E";
2490
2491  if (JA.getType() == types::TY_LLVM_IR ||
2492      JA.getType() == types::TY_LTO_IR)
2493    CmdArgs.push_back("-emit-llvm");
2494  else if (JA.getType() == types::TY_LLVM_BC ||
2495           JA.getType() == types::TY_LTO_BC)
2496    CmdArgs.push_back("-emit-llvm-bc");
2497  else if (Output.getType() == types::TY_AST)
2498    D.Diag(clang::diag::err_drv_no_ast_support)
2499      << getToolChain().getTripleString();
2500  else if (JA.getType() != types::TY_PP_Asm &&
2501           JA.getType() != types::TY_PCH)
2502    D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2503      << getTypeName(JA.getType());
2504
2505  ArgStringList OutputArgs;
2506  if (Output.getType() != types::TY_PCH) {
2507    OutputArgs.push_back("-o");
2508    if (Output.isNothing())
2509      OutputArgs.push_back("/dev/null");
2510    else
2511      OutputArgs.push_back(Output.getFilename());
2512  }
2513
2514  // There is no need for this level of compatibility, but it makes
2515  // diffing easier.
2516  bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
2517                          Args.hasArg(options::OPT_S));
2518
2519  if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
2520    AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2521    if (OutputArgsEarly) {
2522      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2523    } else {
2524      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2525      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2526    }
2527  } else {
2528    CmdArgs.push_back("-fpreprocessed");
2529
2530    for (InputInfoList::const_iterator
2531           it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2532      const InputInfo &II = *it;
2533
2534      // Reject AST inputs.
2535      if (II.getType() == types::TY_AST) {
2536        D.Diag(clang::diag::err_drv_no_ast_support)
2537          << getToolChain().getTripleString();
2538        return;
2539      }
2540
2541      CmdArgs.push_back(II.getFilename());
2542    }
2543
2544    if (OutputArgsEarly) {
2545      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2546    } else {
2547      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2548      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2549    }
2550  }
2551
2552  if (Output.getType() == types::TY_PCH) {
2553    assert(Output.isFilename() && "Invalid PCH output.");
2554
2555    CmdArgs.push_back("-o");
2556    // NOTE: gcc uses a temp .s file for this, but there doesn't seem
2557    // to be a good reason.
2558    CmdArgs.push_back("/dev/null");
2559
2560    CmdArgs.push_back("--output-pch=");
2561    CmdArgs.push_back(Output.getFilename());
2562  }
2563
2564  const char *CC1Name = getCC1Name(Inputs[0].getType());
2565  const char *Exec =
2566    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2567  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2568}
2569
2570void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2571                                    const InputInfo &Output,
2572                                    const InputInfoList &Inputs,
2573                                    const ArgList &Args,
2574                                    const char *LinkingOutput) const {
2575  ArgStringList CmdArgs;
2576
2577  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
2578  const InputInfo &Input = Inputs[0];
2579
2580  // Bit of a hack, this is only used for original inputs.
2581  //
2582  // FIXME: This is broken for preprocessed .s inputs.
2583  if (Input.isFilename() &&
2584      strcmp(Input.getFilename(), Input.getBaseInput()) == 0) {
2585    if (Args.hasArg(options::OPT_gstabs))
2586      CmdArgs.push_back("--gstabs");
2587    else if (Args.hasArg(options::OPT_g_Group))
2588      CmdArgs.push_back("--gdwarf2");
2589  }
2590
2591  // Derived from asm spec.
2592  AddDarwinArch(Args, CmdArgs);
2593
2594  // Use -force_cpusubtype_ALL on x86 by default.
2595  if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
2596      getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
2597      Args.hasArg(options::OPT_force__cpusubtype__ALL))
2598    CmdArgs.push_back("-force_cpusubtype_ALL");
2599
2600  if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
2601      (Args.hasArg(options::OPT_mkernel) ||
2602       Args.hasArg(options::OPT_static) ||
2603       Args.hasArg(options::OPT_fapple_kext)))
2604    CmdArgs.push_back("-static");
2605
2606  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2607                       options::OPT_Xassembler);
2608
2609  assert(Output.isFilename() && "Unexpected lipo output.");
2610  CmdArgs.push_back("-o");
2611  CmdArgs.push_back(Output.getFilename());
2612
2613  assert(Input.isFilename() && "Invalid input.");
2614  CmdArgs.push_back(Input.getFilename());
2615
2616  // asm_final spec is empty.
2617
2618  const char *Exec =
2619    Args.MakeArgString(getToolChain().GetProgramPath("as"));
2620  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2621}
2622
2623void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
2624                                       ArgStringList &CmdArgs) const {
2625  llvm::StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
2626
2627  // Derived from darwin_arch spec.
2628  CmdArgs.push_back("-arch");
2629  CmdArgs.push_back(Args.MakeArgString(ArchName));
2630
2631  // FIXME: Is this needed anymore?
2632  if (ArchName == "arm")
2633    CmdArgs.push_back("-force_cpusubtype_ALL");
2634}
2635
2636void darwin::Link::AddLinkArgs(Compilation &C,
2637                               const ArgList &Args,
2638                               ArgStringList &CmdArgs) const {
2639  const Driver &D = getToolChain().getDriver();
2640
2641  unsigned Version[3] = { 0, 0, 0 };
2642  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2643    bool HadExtra;
2644    if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
2645                                   Version[1], Version[2], HadExtra) ||
2646        HadExtra)
2647      D.Diag(clang::diag::err_drv_invalid_version_number)
2648        << A->getAsString(Args);
2649  }
2650
2651  // Newer linkers support -demangle, pass it if supported and not disabled by
2652  // the user.
2653  //
2654  // FIXME: We temporarily avoid passing -demangle to any iOS linker, because
2655  // unfortunately we can't be guaranteed that the linker version used there
2656  // will match the linker version detected at configure time. We need the
2657  // universal driver.
2658  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle) &&
2659      !getDarwinToolChain().isTargetIPhoneOS()) {
2660    // Don't pass -demangle to ld_classic.
2661    //
2662    // FIXME: This is a temporary workaround, ld should be handling this.
2663    bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
2664                          Args.hasArg(options::OPT_static));
2665    if (getToolChain().getArch() == llvm::Triple::x86) {
2666      for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
2667                                                 options::OPT_Wl_COMMA),
2668             ie = Args.filtered_end(); it != ie; ++it) {
2669        const Arg *A = *it;
2670        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
2671          if (llvm::StringRef(A->getValue(Args, i)) == "-kext")
2672            UsesLdClassic = true;
2673      }
2674    }
2675    if (!UsesLdClassic)
2676      CmdArgs.push_back("-demangle");
2677  }
2678
2679  // Derived from the "link" spec.
2680  Args.AddAllArgs(CmdArgs, options::OPT_static);
2681  if (!Args.hasArg(options::OPT_static))
2682    CmdArgs.push_back("-dynamic");
2683  if (Args.hasArg(options::OPT_fgnu_runtime)) {
2684    // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
2685    // here. How do we wish to handle such things?
2686  }
2687
2688  if (!Args.hasArg(options::OPT_dynamiclib)) {
2689    AddDarwinArch(Args, CmdArgs);
2690    // FIXME: Why do this only on this path?
2691    Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
2692
2693    Args.AddLastArg(CmdArgs, options::OPT_bundle);
2694    Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
2695    Args.AddAllArgs(CmdArgs, options::OPT_client__name);
2696
2697    Arg *A;
2698    if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
2699        (A = Args.getLastArg(options::OPT_current__version)) ||
2700        (A = Args.getLastArg(options::OPT_install__name)))
2701      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2702        << A->getAsString(Args) << "-dynamiclib";
2703
2704    Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
2705    Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
2706    Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
2707  } else {
2708    CmdArgs.push_back("-dylib");
2709
2710    Arg *A;
2711    if ((A = Args.getLastArg(options::OPT_bundle)) ||
2712        (A = Args.getLastArg(options::OPT_bundle__loader)) ||
2713        (A = Args.getLastArg(options::OPT_client__name)) ||
2714        (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
2715        (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
2716        (A = Args.getLastArg(options::OPT_private__bundle)))
2717      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2718        << A->getAsString(Args) << "-dynamiclib";
2719
2720    Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
2721                              "-dylib_compatibility_version");
2722    Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
2723                              "-dylib_current_version");
2724
2725    AddDarwinArch(Args, CmdArgs);
2726
2727    Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
2728                              "-dylib_install_name");
2729  }
2730
2731  Args.AddLastArg(CmdArgs, options::OPT_all__load);
2732  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
2733  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
2734  if (getDarwinToolChain().isTargetIPhoneOS())
2735    Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
2736  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
2737  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
2738  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
2739  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
2740  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
2741  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
2742  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
2743  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
2744  Args.AddAllArgs(CmdArgs, options::OPT_init);
2745
2746  // Adding all arguments doesn't make sense here but this is what gcc does. One
2747  // of this should always be present thanks to argument translation.
2748  assert((Args.hasArg(options::OPT_mmacosx_version_min_EQ) ||
2749          Args.hasArg(options::OPT_miphoneos_version_min_EQ)) &&
2750         "Missing version argument (lost in translation)?");
2751  Args.AddAllArgsTranslated(CmdArgs, options::OPT_mmacosx_version_min_EQ,
2752                            "-macosx_version_min");
2753  Args.AddAllArgsTranslated(CmdArgs, options::OPT_miphoneos_version_min_EQ,
2754                            "-iphoneos_version_min");
2755  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
2756  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
2757  Args.AddLastArg(CmdArgs, options::OPT_single__module);
2758  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
2759  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
2760
2761  if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
2762                                     options::OPT_fno_pie,
2763                                     options::OPT_fno_PIE)) {
2764    if (A->getOption().matches(options::OPT_fpie) ||
2765        A->getOption().matches(options::OPT_fPIE))
2766      CmdArgs.push_back("-pie");
2767    else
2768      CmdArgs.push_back("-no_pie");
2769  }
2770
2771  Args.AddLastArg(CmdArgs, options::OPT_prebind);
2772  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
2773  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
2774  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
2775  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
2776  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
2777  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
2778  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
2779  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
2780  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
2781  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
2782  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
2783  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
2784  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
2785  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
2786  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
2787
2788  Args.AddAllArgsTranslated(CmdArgs, options::OPT_isysroot, "-syslibroot");
2789  if (getDarwinToolChain().isTargetIPhoneOS()) {
2790    if (!Args.hasArg(options::OPT_isysroot)) {
2791      CmdArgs.push_back("-syslibroot");
2792      CmdArgs.push_back("/Developer/SDKs/Extra");
2793    }
2794  }
2795
2796  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
2797  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
2798  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
2799  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
2800  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
2801  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
2802  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
2803  Args.AddAllArgs(CmdArgs, options::OPT_y);
2804  Args.AddLastArg(CmdArgs, options::OPT_w);
2805  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
2806  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
2807  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
2808  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
2809  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
2810  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
2811  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
2812  Args.AddLastArg(CmdArgs, options::OPT_whyload);
2813  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
2814  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
2815  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
2816  Args.AddLastArg(CmdArgs, options::OPT_Mach);
2817}
2818
2819void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
2820                                const InputInfo &Output,
2821                                const InputInfoList &Inputs,
2822                                const ArgList &Args,
2823                                const char *LinkingOutput) const {
2824  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
2825
2826  // The logic here is derived from gcc's behavior; most of which
2827  // comes from specs (starting with link_command). Consult gcc for
2828  // more information.
2829  ArgStringList CmdArgs;
2830
2831  // I'm not sure why this particular decomposition exists in gcc, but
2832  // we follow suite for ease of comparison.
2833  AddLinkArgs(C, Args, CmdArgs);
2834
2835  Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
2836  Args.AddAllArgs(CmdArgs, options::OPT_s);
2837  Args.AddAllArgs(CmdArgs, options::OPT_t);
2838  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
2839  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
2840  Args.AddAllArgs(CmdArgs, options::OPT_A);
2841  Args.AddLastArg(CmdArgs, options::OPT_e);
2842  Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
2843  Args.AddAllArgs(CmdArgs, options::OPT_r);
2844
2845  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
2846  // members of static archive libraries which implement Objective-C classes or
2847  // categories.
2848  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
2849    CmdArgs.push_back("-ObjC");
2850
2851  CmdArgs.push_back("-o");
2852  CmdArgs.push_back(Output.getFilename());
2853
2854  if (!Args.hasArg(options::OPT_A) &&
2855      !Args.hasArg(options::OPT_nostdlib) &&
2856      !Args.hasArg(options::OPT_nostartfiles)) {
2857    // Derived from startfile spec.
2858    if (Args.hasArg(options::OPT_dynamiclib)) {
2859      // Derived from darwin_dylib1 spec.
2860      if (getDarwinToolChain().isTargetIOSSimulator()) {
2861        // The simulator doesn't have a versioned crt1 file.
2862        CmdArgs.push_back("-ldylib1.o");
2863      } else if (getDarwinToolChain().isTargetIPhoneOS()) {
2864        if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2865          CmdArgs.push_back("-ldylib1.o");
2866      } else {
2867        if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2868          CmdArgs.push_back("-ldylib1.o");
2869        else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2870          CmdArgs.push_back("-ldylib1.10.5.o");
2871      }
2872    } else {
2873      if (Args.hasArg(options::OPT_bundle)) {
2874        if (!Args.hasArg(options::OPT_static)) {
2875          // Derived from darwin_bundle1 spec.
2876          if (getDarwinToolChain().isTargetIOSSimulator()) {
2877            // The simulator doesn't have a versioned crt1 file.
2878            CmdArgs.push_back("-lbundle1.o");
2879          } else if (getDarwinToolChain().isTargetIPhoneOS()) {
2880            if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2881              CmdArgs.push_back("-lbundle1.o");
2882          } else {
2883            if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2884              CmdArgs.push_back("-lbundle1.o");
2885          }
2886        }
2887      } else {
2888        if (Args.hasArg(options::OPT_pg) &&
2889            getToolChain().SupportsProfiling()) {
2890          if (Args.hasArg(options::OPT_static) ||
2891              Args.hasArg(options::OPT_object) ||
2892              Args.hasArg(options::OPT_preload)) {
2893            CmdArgs.push_back("-lgcrt0.o");
2894          } else {
2895            CmdArgs.push_back("-lgcrt1.o");
2896
2897            // darwin_crt2 spec is empty.
2898          }
2899        } else {
2900          if (Args.hasArg(options::OPT_static) ||
2901              Args.hasArg(options::OPT_object) ||
2902              Args.hasArg(options::OPT_preload)) {
2903            CmdArgs.push_back("-lcrt0.o");
2904          } else {
2905            // Derived from darwin_crt1 spec.
2906            if (getDarwinToolChain().isTargetIOSSimulator()) {
2907              // The simulator doesn't have a versioned crt1 file.
2908              CmdArgs.push_back("-lcrt1.o");
2909            } else if (getDarwinToolChain().isTargetIPhoneOS()) {
2910              if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2911                CmdArgs.push_back("-lcrt1.o");
2912              else
2913                CmdArgs.push_back("-lcrt1.3.1.o");
2914            } else {
2915              if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2916                CmdArgs.push_back("-lcrt1.o");
2917              else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2918                CmdArgs.push_back("-lcrt1.10.5.o");
2919              else
2920                CmdArgs.push_back("-lcrt1.10.6.o");
2921
2922              // darwin_crt2 spec is empty.
2923            }
2924          }
2925        }
2926      }
2927    }
2928
2929    if (!getDarwinToolChain().isTargetIPhoneOS() &&
2930        Args.hasArg(options::OPT_shared_libgcc) &&
2931        getDarwinToolChain().isMacosxVersionLT(10, 5)) {
2932      const char *Str =
2933        Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
2934      CmdArgs.push_back(Str);
2935    }
2936  }
2937
2938  Args.AddAllArgs(CmdArgs, options::OPT_L);
2939
2940  if (Args.hasArg(options::OPT_fopenmp))
2941    // This is more complicated in gcc...
2942    CmdArgs.push_back("-lgomp");
2943
2944  getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs);
2945
2946  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
2947
2948  if (LinkingOutput) {
2949    CmdArgs.push_back("-arch_multiple");
2950    CmdArgs.push_back("-final_output");
2951    CmdArgs.push_back(LinkingOutput);
2952  }
2953
2954  if (Args.hasArg(options::OPT_fprofile_arcs) ||
2955      Args.hasArg(options::OPT_fprofile_generate) ||
2956      Args.hasArg(options::OPT_fcreate_profile) ||
2957      Args.hasArg(options::OPT_coverage))
2958    CmdArgs.push_back("-lgcov");
2959
2960  if (Args.hasArg(options::OPT_fnested_functions))
2961    CmdArgs.push_back("-allow_stack_execute");
2962
2963  if (!Args.hasArg(options::OPT_nostdlib) &&
2964      !Args.hasArg(options::OPT_nodefaultlibs)) {
2965    if (getToolChain().getDriver().CCCIsCXX)
2966      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
2967
2968    // link_ssp spec is empty.
2969
2970    // Let the tool chain choose which runtime library to link.
2971    getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
2972  }
2973
2974  if (!Args.hasArg(options::OPT_A) &&
2975      !Args.hasArg(options::OPT_nostdlib) &&
2976      !Args.hasArg(options::OPT_nostartfiles)) {
2977    // endfile_spec is empty.
2978  }
2979
2980  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2981  Args.AddAllArgs(CmdArgs, options::OPT_F);
2982
2983  const char *Exec =
2984    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
2985  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2986}
2987
2988void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
2989                                const InputInfo &Output,
2990                                const InputInfoList &Inputs,
2991                                const ArgList &Args,
2992                                const char *LinkingOutput) const {
2993  ArgStringList CmdArgs;
2994
2995  CmdArgs.push_back("-create");
2996  assert(Output.isFilename() && "Unexpected lipo output.");
2997
2998  CmdArgs.push_back("-output");
2999  CmdArgs.push_back(Output.getFilename());
3000
3001  for (InputInfoList::const_iterator
3002         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3003    const InputInfo &II = *it;
3004    assert(II.isFilename() && "Unexpected lipo input.");
3005    CmdArgs.push_back(II.getFilename());
3006  }
3007  const char *Exec =
3008    Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
3009  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3010}
3011
3012void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
3013                                    const InputInfo &Output,
3014                                    const InputInfoList &Inputs,
3015                                    const ArgList &Args,
3016                                    const char *LinkingOutput) const {
3017  ArgStringList CmdArgs;
3018
3019  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
3020  const InputInfo &Input = Inputs[0];
3021  assert(Input.isFilename() && "Unexpected dsymutil input.");
3022  CmdArgs.push_back(Input.getFilename());
3023
3024  CmdArgs.push_back("-o");
3025  CmdArgs.push_back(Output.getFilename());
3026
3027  const char *Exec =
3028    Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
3029  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3030}
3031
3032void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3033                                      const InputInfo &Output,
3034                                      const InputInfoList &Inputs,
3035                                      const ArgList &Args,
3036                                      const char *LinkingOutput) const {
3037  ArgStringList CmdArgs;
3038
3039  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3040                       options::OPT_Xassembler);
3041
3042  CmdArgs.push_back("-o");
3043  CmdArgs.push_back(Output.getFilename());
3044
3045  for (InputInfoList::const_iterator
3046         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3047    const InputInfo &II = *it;
3048    CmdArgs.push_back(II.getFilename());
3049  }
3050
3051  const char *Exec =
3052    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
3053  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3054}
3055
3056void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
3057                                  const InputInfo &Output,
3058                                  const InputInfoList &Inputs,
3059                                  const ArgList &Args,
3060                                  const char *LinkingOutput) const {
3061  ArgStringList CmdArgs;
3062
3063  if ((!Args.hasArg(options::OPT_nostdlib)) &&
3064      (!Args.hasArg(options::OPT_shared))) {
3065    CmdArgs.push_back("-e");
3066    CmdArgs.push_back("_start");
3067  }
3068
3069  if (Args.hasArg(options::OPT_static)) {
3070    CmdArgs.push_back("-Bstatic");
3071    CmdArgs.push_back("-dn");
3072  } else {
3073//    CmdArgs.push_back("--eh-frame-hdr");
3074    CmdArgs.push_back("-Bdynamic");
3075    if (Args.hasArg(options::OPT_shared)) {
3076      CmdArgs.push_back("-shared");
3077    } else {
3078      CmdArgs.push_back("--dynamic-linker");
3079      CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
3080    }
3081  }
3082
3083  if (Output.isFilename()) {
3084    CmdArgs.push_back("-o");
3085    CmdArgs.push_back(Output.getFilename());
3086  } else {
3087    assert(Output.isNothing() && "Invalid output.");
3088  }
3089
3090  if (!Args.hasArg(options::OPT_nostdlib) &&
3091      !Args.hasArg(options::OPT_nostartfiles)) {
3092    if (!Args.hasArg(options::OPT_shared)) {
3093      CmdArgs.push_back(Args.MakeArgString(
3094                                getToolChain().GetFilePath("crt1.o")));
3095      CmdArgs.push_back(Args.MakeArgString(
3096                                getToolChain().GetFilePath("crti.o")));
3097      CmdArgs.push_back(Args.MakeArgString(
3098                                getToolChain().GetFilePath("crtbegin.o")));
3099    } else {
3100      CmdArgs.push_back(Args.MakeArgString(
3101                                getToolChain().GetFilePath("crti.o")));
3102    }
3103    CmdArgs.push_back(Args.MakeArgString(
3104                                getToolChain().GetFilePath("crtn.o")));
3105  }
3106
3107  CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
3108                                       + getToolChain().getTripleString()
3109                                       + "/4.2.4"));
3110
3111  Args.AddAllArgs(CmdArgs, options::OPT_L);
3112  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3113  Args.AddAllArgs(CmdArgs, options::OPT_e);
3114
3115  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3116
3117  if (!Args.hasArg(options::OPT_nostdlib) &&
3118      !Args.hasArg(options::OPT_nodefaultlibs)) {
3119    // FIXME: For some reason GCC passes -lgcc before adding
3120    // the default system libraries. Just mimic this for now.
3121    CmdArgs.push_back("-lgcc");
3122
3123    if (Args.hasArg(options::OPT_pthread))
3124      CmdArgs.push_back("-pthread");
3125    if (!Args.hasArg(options::OPT_shared))
3126      CmdArgs.push_back("-lc");
3127    CmdArgs.push_back("-lgcc");
3128  }
3129
3130  if (!Args.hasArg(options::OPT_nostdlib) &&
3131      !Args.hasArg(options::OPT_nostartfiles)) {
3132    if (!Args.hasArg(options::OPT_shared))
3133      CmdArgs.push_back(Args.MakeArgString(
3134                                getToolChain().GetFilePath("crtend.o")));
3135  }
3136
3137  const char *Exec =
3138    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3139  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3140}
3141
3142void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3143                                     const InputInfo &Output,
3144                                     const InputInfoList &Inputs,
3145                                     const ArgList &Args,
3146                                     const char *LinkingOutput) const {
3147  ArgStringList CmdArgs;
3148
3149  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3150                       options::OPT_Xassembler);
3151
3152  CmdArgs.push_back("-o");
3153  CmdArgs.push_back(Output.getFilename());
3154
3155  for (InputInfoList::const_iterator
3156         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3157    const InputInfo &II = *it;
3158    CmdArgs.push_back(II.getFilename());
3159  }
3160
3161  const char *Exec =
3162    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3163  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3164}
3165
3166void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3167                                 const InputInfo &Output,
3168                                 const InputInfoList &Inputs,
3169                                 const ArgList &Args,
3170                                 const char *LinkingOutput) const {
3171  const Driver &D = getToolChain().getDriver();
3172  ArgStringList CmdArgs;
3173
3174  if ((!Args.hasArg(options::OPT_nostdlib)) &&
3175      (!Args.hasArg(options::OPT_shared))) {
3176    CmdArgs.push_back("-e");
3177    CmdArgs.push_back("__start");
3178  }
3179
3180  if (Args.hasArg(options::OPT_static)) {
3181    CmdArgs.push_back("-Bstatic");
3182  } else {
3183    if (Args.hasArg(options::OPT_rdynamic))
3184      CmdArgs.push_back("-export-dynamic");
3185    CmdArgs.push_back("--eh-frame-hdr");
3186    CmdArgs.push_back("-Bdynamic");
3187    if (Args.hasArg(options::OPT_shared)) {
3188      CmdArgs.push_back("-shared");
3189    } else {
3190      CmdArgs.push_back("-dynamic-linker");
3191      CmdArgs.push_back("/usr/libexec/ld.so");
3192    }
3193  }
3194
3195  if (Output.isFilename()) {
3196    CmdArgs.push_back("-o");
3197    CmdArgs.push_back(Output.getFilename());
3198  } else {
3199    assert(Output.isNothing() && "Invalid output.");
3200  }
3201
3202  if (!Args.hasArg(options::OPT_nostdlib) &&
3203      !Args.hasArg(options::OPT_nostartfiles)) {
3204    if (!Args.hasArg(options::OPT_shared)) {
3205      CmdArgs.push_back(Args.MakeArgString(
3206                              getToolChain().GetFilePath("crt0.o")));
3207      CmdArgs.push_back(Args.MakeArgString(
3208                              getToolChain().GetFilePath("crtbegin.o")));
3209    } else {
3210      CmdArgs.push_back(Args.MakeArgString(
3211                              getToolChain().GetFilePath("crtbeginS.o")));
3212    }
3213  }
3214
3215  std::string Triple = getToolChain().getTripleString();
3216  if (Triple.substr(0, 6) == "x86_64")
3217    Triple.replace(0, 6, "amd64");
3218  CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
3219                                       "/4.2.1"));
3220
3221  Args.AddAllArgs(CmdArgs, options::OPT_L);
3222  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3223  Args.AddAllArgs(CmdArgs, options::OPT_e);
3224
3225  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3226
3227  if (!Args.hasArg(options::OPT_nostdlib) &&
3228      !Args.hasArg(options::OPT_nodefaultlibs)) {
3229    if (D.CCCIsCXX) {
3230      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3231      CmdArgs.push_back("-lm");
3232    }
3233
3234    // FIXME: For some reason GCC passes -lgcc before adding
3235    // the default system libraries. Just mimic this for now.
3236    CmdArgs.push_back("-lgcc");
3237
3238    if (Args.hasArg(options::OPT_pthread))
3239      CmdArgs.push_back("-lpthread");
3240    if (!Args.hasArg(options::OPT_shared))
3241      CmdArgs.push_back("-lc");
3242    CmdArgs.push_back("-lgcc");
3243  }
3244
3245  if (!Args.hasArg(options::OPT_nostdlib) &&
3246      !Args.hasArg(options::OPT_nostartfiles)) {
3247    if (!Args.hasArg(options::OPT_shared))
3248      CmdArgs.push_back(Args.MakeArgString(
3249                              getToolChain().GetFilePath("crtend.o")));
3250    else
3251      CmdArgs.push_back(Args.MakeArgString(
3252                              getToolChain().GetFilePath("crtendS.o")));
3253  }
3254
3255  const char *Exec =
3256    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3257  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3258}
3259
3260void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3261                                     const InputInfo &Output,
3262                                     const InputInfoList &Inputs,
3263                                     const ArgList &Args,
3264                                     const char *LinkingOutput) const {
3265  ArgStringList CmdArgs;
3266
3267  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3268  // instruct as in the base system to assemble 32-bit code.
3269  if (getToolChain().getArchName() == "i386")
3270    CmdArgs.push_back("--32");
3271
3272
3273  // Set byte order explicitly
3274  if (getToolChain().getArchName() == "mips")
3275    CmdArgs.push_back("-EB");
3276  else if (getToolChain().getArchName() == "mipsel")
3277    CmdArgs.push_back("-EL");
3278
3279  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3280                       options::OPT_Xassembler);
3281
3282  CmdArgs.push_back("-o");
3283  CmdArgs.push_back(Output.getFilename());
3284
3285  for (InputInfoList::const_iterator
3286         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3287    const InputInfo &II = *it;
3288    CmdArgs.push_back(II.getFilename());
3289  }
3290
3291  const char *Exec =
3292    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3293  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3294}
3295
3296void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3297                                 const InputInfo &Output,
3298                                 const InputInfoList &Inputs,
3299                                 const ArgList &Args,
3300                                 const char *LinkingOutput) const {
3301  const Driver &D = getToolChain().getDriver();
3302  ArgStringList CmdArgs;
3303
3304  if (!D.SysRoot.empty())
3305    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3306
3307  if (Args.hasArg(options::OPT_static)) {
3308    CmdArgs.push_back("-Bstatic");
3309  } else {
3310    if (Args.hasArg(options::OPT_rdynamic))
3311      CmdArgs.push_back("-export-dynamic");
3312    CmdArgs.push_back("--eh-frame-hdr");
3313    if (Args.hasArg(options::OPT_shared)) {
3314      CmdArgs.push_back("-Bshareable");
3315    } else {
3316      CmdArgs.push_back("-dynamic-linker");
3317      CmdArgs.push_back("/libexec/ld-elf.so.1");
3318    }
3319  }
3320
3321  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3322  // instruct ld in the base system to link 32-bit code.
3323  if (getToolChain().getArchName() == "i386") {
3324    CmdArgs.push_back("-m");
3325    CmdArgs.push_back("elf_i386_fbsd");
3326  }
3327
3328  if (Output.isFilename()) {
3329    CmdArgs.push_back("-o");
3330    CmdArgs.push_back(Output.getFilename());
3331  } else {
3332    assert(Output.isNothing() && "Invalid output.");
3333  }
3334
3335  if (!Args.hasArg(options::OPT_nostdlib) &&
3336      !Args.hasArg(options::OPT_nostartfiles)) {
3337    if (!Args.hasArg(options::OPT_shared)) {
3338      if (Args.hasArg(options::OPT_pg))
3339        CmdArgs.push_back(Args.MakeArgString(
3340                                getToolChain().GetFilePath("gcrt1.o")));
3341      else
3342        CmdArgs.push_back(Args.MakeArgString(
3343                                getToolChain().GetFilePath("crt1.o")));
3344      CmdArgs.push_back(Args.MakeArgString(
3345                              getToolChain().GetFilePath("crti.o")));
3346      CmdArgs.push_back(Args.MakeArgString(
3347                              getToolChain().GetFilePath("crtbegin.o")));
3348    } else {
3349      CmdArgs.push_back(Args.MakeArgString(
3350                              getToolChain().GetFilePath("crti.o")));
3351      CmdArgs.push_back(Args.MakeArgString(
3352                              getToolChain().GetFilePath("crtbeginS.o")));
3353    }
3354  }
3355
3356  Args.AddAllArgs(CmdArgs, options::OPT_L);
3357  const ToolChain::path_list Paths = getToolChain().getFilePaths();
3358  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
3359       i != e; ++i)
3360    CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
3361  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3362  Args.AddAllArgs(CmdArgs, options::OPT_e);
3363  Args.AddAllArgs(CmdArgs, options::OPT_s);
3364  Args.AddAllArgs(CmdArgs, options::OPT_t);
3365  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3366  Args.AddAllArgs(CmdArgs, options::OPT_r);
3367
3368  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3369
3370  if (!Args.hasArg(options::OPT_nostdlib) &&
3371      !Args.hasArg(options::OPT_nodefaultlibs)) {
3372    if (D.CCCIsCXX) {
3373      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3374      if (Args.hasArg(options::OPT_pg))
3375        CmdArgs.push_back("-lm_p");
3376      else
3377        CmdArgs.push_back("-lm");
3378    }
3379    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3380    // the default system libraries. Just mimic this for now.
3381    if (Args.hasArg(options::OPT_pg))
3382      CmdArgs.push_back("-lgcc_p");
3383    else
3384      CmdArgs.push_back("-lgcc");
3385    if (Args.hasArg(options::OPT_static)) {
3386      CmdArgs.push_back("-lgcc_eh");
3387    } else if (Args.hasArg(options::OPT_pg)) {
3388      CmdArgs.push_back("-lgcc_eh_p");
3389    } else {
3390      CmdArgs.push_back("--as-needed");
3391      CmdArgs.push_back("-lgcc_s");
3392      CmdArgs.push_back("--no-as-needed");
3393    }
3394
3395    if (Args.hasArg(options::OPT_pthread)) {
3396      if (Args.hasArg(options::OPT_pg))
3397        CmdArgs.push_back("-lpthread_p");
3398      else
3399        CmdArgs.push_back("-lpthread");
3400    }
3401
3402    if (Args.hasArg(options::OPT_pg)) {
3403      if (Args.hasArg(options::OPT_shared))
3404        CmdArgs.push_back("-lc");
3405      else
3406        CmdArgs.push_back("-lc_p");
3407      CmdArgs.push_back("-lgcc_p");
3408    } else {
3409      CmdArgs.push_back("-lc");
3410      CmdArgs.push_back("-lgcc");
3411    }
3412
3413    if (Args.hasArg(options::OPT_static)) {
3414      CmdArgs.push_back("-lgcc_eh");
3415    } else if (Args.hasArg(options::OPT_pg)) {
3416      CmdArgs.push_back("-lgcc_eh_p");
3417    } else {
3418      CmdArgs.push_back("--as-needed");
3419      CmdArgs.push_back("-lgcc_s");
3420      CmdArgs.push_back("--no-as-needed");
3421    }
3422  }
3423
3424  if (!Args.hasArg(options::OPT_nostdlib) &&
3425      !Args.hasArg(options::OPT_nostartfiles)) {
3426    if (!Args.hasArg(options::OPT_shared))
3427      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3428                                                                  "crtend.o")));
3429    else
3430      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3431                                                                 "crtendS.o")));
3432    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3433                                                                    "crtn.o")));
3434  }
3435
3436  const char *Exec =
3437    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3438  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3439}
3440
3441void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3442                                     const InputInfo &Output,
3443                                     const InputInfoList &Inputs,
3444                                     const ArgList &Args,
3445                                     const char *LinkingOutput) const {
3446  ArgStringList CmdArgs;
3447
3448  // When building 32-bit code on NetBSD/amd64, we have to explicitly
3449  // instruct as in the base system to assemble 32-bit code.
3450  if (getToolChain().getArchName() == "i386")
3451    CmdArgs.push_back("--32");
3452
3453
3454  // Set byte order explicitly
3455  if (getToolChain().getArchName() == "mips")
3456    CmdArgs.push_back("-EB");
3457  else if (getToolChain().getArchName() == "mipsel")
3458    CmdArgs.push_back("-EL");
3459
3460  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3461                       options::OPT_Xassembler);
3462
3463  CmdArgs.push_back("-o");
3464  CmdArgs.push_back(Output.getFilename());
3465
3466  for (InputInfoList::const_iterator
3467         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3468    const InputInfo &II = *it;
3469    CmdArgs.push_back(II.getFilename());
3470  }
3471
3472  const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3473                                                              "as"));
3474  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3475}
3476
3477void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3478                                 const InputInfo &Output,
3479                                 const InputInfoList &Inputs,
3480                                 const ArgList &Args,
3481                                 const char *LinkingOutput) const {
3482  const Driver &D = getToolChain().getDriver();
3483  ArgStringList CmdArgs;
3484
3485  if (!D.SysRoot.empty())
3486    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3487
3488  if (Args.hasArg(options::OPT_static)) {
3489    CmdArgs.push_back("-Bstatic");
3490  } else {
3491    if (Args.hasArg(options::OPT_rdynamic))
3492      CmdArgs.push_back("-export-dynamic");
3493    CmdArgs.push_back("--eh-frame-hdr");
3494    if (Args.hasArg(options::OPT_shared)) {
3495      CmdArgs.push_back("-Bshareable");
3496    } else {
3497      CmdArgs.push_back("-dynamic-linker");
3498      CmdArgs.push_back("/libexec/ld.elf_so");
3499    }
3500  }
3501
3502  // When building 32-bit code on NetBSD/amd64, we have to explicitly
3503  // instruct ld in the base system to link 32-bit code.
3504  if (getToolChain().getArchName() == "i386") {
3505    CmdArgs.push_back("-m");
3506    CmdArgs.push_back("elf_i386");
3507  }
3508
3509  if (Output.isFilename()) {
3510    CmdArgs.push_back("-o");
3511    CmdArgs.push_back(Output.getFilename());
3512  } else {
3513    assert(Output.isNothing() && "Invalid output.");
3514  }
3515
3516  if (!Args.hasArg(options::OPT_nostdlib) &&
3517      !Args.hasArg(options::OPT_nostartfiles)) {
3518    if (!Args.hasArg(options::OPT_shared)) {
3519      CmdArgs.push_back(Args.MakeArgString(
3520                              getToolChain().GetFilePath("crt0.o")));
3521      CmdArgs.push_back(Args.MakeArgString(
3522                              getToolChain().GetFilePath("crti.o")));
3523      CmdArgs.push_back(Args.MakeArgString(
3524                              getToolChain().GetFilePath("crtbegin.o")));
3525    } else {
3526      CmdArgs.push_back(Args.MakeArgString(
3527                              getToolChain().GetFilePath("crti.o")));
3528      CmdArgs.push_back(Args.MakeArgString(
3529                              getToolChain().GetFilePath("crtbeginS.o")));
3530    }
3531  }
3532
3533  Args.AddAllArgs(CmdArgs, options::OPT_L);
3534  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3535  Args.AddAllArgs(CmdArgs, options::OPT_e);
3536  Args.AddAllArgs(CmdArgs, options::OPT_s);
3537  Args.AddAllArgs(CmdArgs, options::OPT_t);
3538  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3539  Args.AddAllArgs(CmdArgs, options::OPT_r);
3540
3541  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3542
3543  if (!Args.hasArg(options::OPT_nostdlib) &&
3544      !Args.hasArg(options::OPT_nodefaultlibs)) {
3545    if (D.CCCIsCXX) {
3546      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3547      CmdArgs.push_back("-lm");
3548    }
3549    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3550    // the default system libraries. Just mimic this for now.
3551    CmdArgs.push_back("-lgcc");
3552    if (Args.hasArg(options::OPT_static)) {
3553      CmdArgs.push_back("-lgcc_eh");
3554    } else {
3555      CmdArgs.push_back("--as-needed");
3556      CmdArgs.push_back("-lgcc_s");
3557      CmdArgs.push_back("--no-as-needed");
3558    }
3559
3560    if (Args.hasArg(options::OPT_pthread))
3561      CmdArgs.push_back("-lpthread");
3562    CmdArgs.push_back("-lc");
3563
3564    CmdArgs.push_back("-lgcc");
3565    if (Args.hasArg(options::OPT_static)) {
3566      CmdArgs.push_back("-lgcc_eh");
3567    } else {
3568      CmdArgs.push_back("--as-needed");
3569      CmdArgs.push_back("-lgcc_s");
3570      CmdArgs.push_back("--no-as-needed");
3571    }
3572  }
3573
3574  if (!Args.hasArg(options::OPT_nostdlib) &&
3575      !Args.hasArg(options::OPT_nostartfiles)) {
3576    if (!Args.hasArg(options::OPT_shared))
3577      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3578                                                                  "crtend.o")));
3579    else
3580      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3581                                                                 "crtendS.o")));
3582    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3583                                                                    "crtn.o")));
3584  }
3585
3586  const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3587                                                              "ld"));
3588  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3589}
3590
3591void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3592                                        const InputInfo &Output,
3593                                        const InputInfoList &Inputs,
3594                                        const ArgList &Args,
3595                                        const char *LinkingOutput) const {
3596  ArgStringList CmdArgs;
3597
3598  // Add --32/--64 to make sure we get the format we want.
3599  // This is incomplete
3600  if (getToolChain().getArch() == llvm::Triple::x86) {
3601    CmdArgs.push_back("--32");
3602  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
3603    CmdArgs.push_back("--64");
3604  } else if (getToolChain().getArch() == llvm::Triple::arm) {
3605    llvm::StringRef MArch = getToolChain().getArchName();
3606    if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
3607      CmdArgs.push_back("-mfpu=neon");
3608  }
3609
3610  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3611                       options::OPT_Xassembler);
3612
3613  CmdArgs.push_back("-o");
3614  CmdArgs.push_back(Output.getFilename());
3615
3616  for (InputInfoList::const_iterator
3617         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3618    const InputInfo &II = *it;
3619    CmdArgs.push_back(II.getFilename());
3620  }
3621
3622  const char *Exec =
3623    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3624  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3625}
3626
3627void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
3628                                    const InputInfo &Output,
3629                                    const InputInfoList &Inputs,
3630                                    const ArgList &Args,
3631                                    const char *LinkingOutput) const {
3632  const toolchains::Linux& ToolChain =
3633    static_cast<const toolchains::Linux&>(getToolChain());
3634  const Driver &D = ToolChain.getDriver();
3635  ArgStringList CmdArgs;
3636
3637  // Silence warning for "clang -g foo.o -o foo"
3638  Args.ClaimAllArgs(options::OPT_g_Group);
3639  // and "clang -emit-llvm foo.o -o foo"
3640  Args.ClaimAllArgs(options::OPT_emit_llvm);
3641  // and for "clang -g foo.o -o foo". Other warning options are already
3642  // handled somewhere else.
3643  Args.ClaimAllArgs(options::OPT_w);
3644
3645  if (!D.SysRoot.empty())
3646    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3647
3648  if (Args.hasArg(options::OPT_pie))
3649    CmdArgs.push_back("-pie");
3650
3651  if (Args.hasArg(options::OPT_rdynamic))
3652    CmdArgs.push_back("-export-dynamic");
3653
3654  if (Args.hasArg(options::OPT_s))
3655    CmdArgs.push_back("-s");
3656
3657  for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
3658         e = ToolChain.ExtraOpts.end();
3659       i != e; ++i)
3660    CmdArgs.push_back(i->c_str());
3661
3662  if (!Args.hasArg(options::OPT_static)) {
3663    CmdArgs.push_back("--eh-frame-hdr");
3664  }
3665
3666  CmdArgs.push_back("-m");
3667  if (ToolChain.getArch() == llvm::Triple::x86)
3668    CmdArgs.push_back("elf_i386");
3669  else if (ToolChain.getArch() == llvm::Triple::arm
3670           ||  ToolChain.getArch() == llvm::Triple::thumb)
3671    CmdArgs.push_back("armelf_linux_eabi");
3672  else if (ToolChain.getArch() == llvm::Triple::ppc)
3673    CmdArgs.push_back("elf32ppclinux");
3674  else if (ToolChain.getArch() == llvm::Triple::ppc64)
3675    CmdArgs.push_back("elf64ppc");
3676  else
3677    CmdArgs.push_back("elf_x86_64");
3678
3679  if (Args.hasArg(options::OPT_static)) {
3680    if (ToolChain.getArch() == llvm::Triple::arm
3681        || ToolChain.getArch() == llvm::Triple::thumb)
3682      CmdArgs.push_back("-Bstatic");
3683    else
3684      CmdArgs.push_back("-static");
3685  } else if (Args.hasArg(options::OPT_shared)) {
3686    CmdArgs.push_back("-shared");
3687  }
3688
3689  if (ToolChain.getArch() == llvm::Triple::arm ||
3690      ToolChain.getArch() == llvm::Triple::thumb ||
3691      (!Args.hasArg(options::OPT_static) &&
3692       !Args.hasArg(options::OPT_shared))) {
3693    CmdArgs.push_back("-dynamic-linker");
3694    if (ToolChain.getArch() == llvm::Triple::x86)
3695      CmdArgs.push_back("/lib/ld-linux.so.2");
3696    else if (ToolChain.getArch() == llvm::Triple::arm ||
3697             ToolChain.getArch() == llvm::Triple::thumb)
3698      CmdArgs.push_back("/lib/ld-linux.so.3");
3699    else if (ToolChain.getArch() == llvm::Triple::ppc)
3700      CmdArgs.push_back("/lib/ld.so");
3701    else if (ToolChain.getArch() == llvm::Triple::ppc64)
3702      CmdArgs.push_back("/lib64/ld64.so");
3703    else
3704      CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
3705  }
3706
3707  CmdArgs.push_back("-o");
3708  CmdArgs.push_back(Output.getFilename());
3709
3710  if (!Args.hasArg(options::OPT_nostdlib) &&
3711      !Args.hasArg(options::OPT_nostartfiles)) {
3712    const char *crt1 = NULL;
3713    if (!Args.hasArg(options::OPT_shared)){
3714      if (Args.hasArg(options::OPT_pie))
3715        crt1 = "Scrt1.o";
3716      else
3717        crt1 = "crt1.o";
3718    }
3719    if (crt1)
3720      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
3721
3722    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
3723
3724    const char *crtbegin;
3725    if (Args.hasArg(options::OPT_static))
3726      crtbegin = "crtbeginT.o";
3727    else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
3728      crtbegin = "crtbeginS.o";
3729    else
3730      crtbegin = "crtbegin.o";
3731    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
3732  }
3733
3734  Args.AddAllArgs(CmdArgs, options::OPT_L);
3735
3736  const ToolChain::path_list Paths = ToolChain.getFilePaths();
3737
3738  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
3739       i != e; ++i)
3740    CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
3741
3742  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
3743
3744  if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) {
3745    ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
3746    CmdArgs.push_back("-lm");
3747  }
3748
3749  if (Args.hasArg(options::OPT_static))
3750    CmdArgs.push_back("--start-group");
3751
3752  if (!Args.hasArg(options::OPT_nostdlib)) {
3753    if (!D.CCCIsCXX)
3754      CmdArgs.push_back("-lgcc");
3755
3756    if (Args.hasArg(options::OPT_static)) {
3757      if (D.CCCIsCXX)
3758        CmdArgs.push_back("-lgcc");
3759    } else {
3760      if (!D.CCCIsCXX)
3761        CmdArgs.push_back("--as-needed");
3762      CmdArgs.push_back("-lgcc_s");
3763      if (!D.CCCIsCXX)
3764        CmdArgs.push_back("--no-as-needed");
3765    }
3766
3767    if (Args.hasArg(options::OPT_static))
3768      CmdArgs.push_back("-lgcc_eh");
3769    else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
3770      CmdArgs.push_back("-lgcc");
3771
3772    if (Args.hasArg(options::OPT_pthread) ||
3773        Args.hasArg(options::OPT_pthreads))
3774      CmdArgs.push_back("-lpthread");
3775
3776    CmdArgs.push_back("-lc");
3777
3778    if (Args.hasArg(options::OPT_static))
3779      CmdArgs.push_back("--end-group");
3780    else {
3781      if (!D.CCCIsCXX)
3782        CmdArgs.push_back("-lgcc");
3783
3784      if (!D.CCCIsCXX)
3785        CmdArgs.push_back("--as-needed");
3786      CmdArgs.push_back("-lgcc_s");
3787      if (!D.CCCIsCXX)
3788        CmdArgs.push_back("--no-as-needed");
3789
3790      if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
3791        CmdArgs.push_back("-lgcc");
3792    }
3793
3794
3795    if (!Args.hasArg(options::OPT_nostartfiles)) {
3796      const char *crtend;
3797      if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
3798        crtend = "crtendS.o";
3799      else
3800        crtend = "crtend.o";
3801
3802      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
3803      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
3804    }
3805  }
3806
3807  if (Args.hasArg(options::OPT_use_gold_plugin)) {
3808    CmdArgs.push_back("-plugin");
3809    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
3810    CmdArgs.push_back(Args.MakeArgString(Plugin));
3811  }
3812
3813  C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
3814}
3815
3816void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3817                                   const InputInfo &Output,
3818                                   const InputInfoList &Inputs,
3819                                   const ArgList &Args,
3820                                   const char *LinkingOutput) const {
3821  ArgStringList CmdArgs;
3822
3823  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3824                       options::OPT_Xassembler);
3825
3826  CmdArgs.push_back("-o");
3827  CmdArgs.push_back(Output.getFilename());
3828
3829  for (InputInfoList::const_iterator
3830         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3831    const InputInfo &II = *it;
3832    CmdArgs.push_back(II.getFilename());
3833  }
3834
3835  const char *Exec =
3836    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
3837  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3838}
3839
3840void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
3841                               const InputInfo &Output,
3842                               const InputInfoList &Inputs,
3843                               const ArgList &Args,
3844                               const char *LinkingOutput) const {
3845  const Driver &D = getToolChain().getDriver();
3846  ArgStringList CmdArgs;
3847
3848  if (Output.isFilename()) {
3849    CmdArgs.push_back("-o");
3850    CmdArgs.push_back(Output.getFilename());
3851  } else {
3852    assert(Output.isNothing() && "Invalid output.");
3853  }
3854
3855  if (!Args.hasArg(options::OPT_nostdlib) &&
3856      !Args.hasArg(options::OPT_nostartfiles))
3857    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3858                                                      "/usr/gnu/lib/crtso.o")));
3859
3860  Args.AddAllArgs(CmdArgs, options::OPT_L);
3861  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3862  Args.AddAllArgs(CmdArgs, options::OPT_e);
3863
3864  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3865
3866  if (!Args.hasArg(options::OPT_nostdlib) &&
3867      !Args.hasArg(options::OPT_nodefaultlibs)) {
3868    if (D.CCCIsCXX) {
3869      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3870      CmdArgs.push_back("-lm");
3871    }
3872
3873    if (Args.hasArg(options::OPT_pthread))
3874      CmdArgs.push_back("-lpthread");
3875    CmdArgs.push_back("-lc");
3876    CmdArgs.push_back("-lgcc");
3877    CmdArgs.push_back("-L/usr/gnu/lib");
3878    // FIXME: fill in the correct search path for the final
3879    // support libraries.
3880    CmdArgs.push_back("-L/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
3881  }
3882
3883  if (!Args.hasArg(options::OPT_nostdlib) &&
3884      !Args.hasArg(options::OPT_nostartfiles)) {
3885    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3886                                              "/usr/gnu/lib/libend.a")));
3887  }
3888
3889  const char *Exec =
3890    Args.MakeArgString(getToolChain().GetProgramPath("/usr/gnu/bin/gld"));
3891  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3892}
3893
3894/// DragonFly Tools
3895
3896// For now, DragonFly Assemble does just about the same as for
3897// FreeBSD, but this may change soon.
3898void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3899                                       const InputInfo &Output,
3900                                       const InputInfoList &Inputs,
3901                                       const ArgList &Args,
3902                                       const char *LinkingOutput) const {
3903  ArgStringList CmdArgs;
3904
3905  // When building 32-bit code on DragonFly/pc64, we have to explicitly
3906  // instruct as in the base system to assemble 32-bit code.
3907  if (getToolChain().getArchName() == "i386")
3908    CmdArgs.push_back("--32");
3909
3910  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3911                       options::OPT_Xassembler);
3912
3913  CmdArgs.push_back("-o");
3914  CmdArgs.push_back(Output.getFilename());
3915
3916  for (InputInfoList::const_iterator
3917         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3918    const InputInfo &II = *it;
3919    CmdArgs.push_back(II.getFilename());
3920  }
3921
3922  const char *Exec =
3923    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3924  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3925}
3926
3927void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
3928                                   const InputInfo &Output,
3929                                   const InputInfoList &Inputs,
3930                                   const ArgList &Args,
3931                                   const char *LinkingOutput) const {
3932  const Driver &D = getToolChain().getDriver();
3933  ArgStringList CmdArgs;
3934
3935  if (!D.SysRoot.empty())
3936    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3937
3938  if (Args.hasArg(options::OPT_static)) {
3939    CmdArgs.push_back("-Bstatic");
3940  } else {
3941    if (Args.hasArg(options::OPT_shared))
3942      CmdArgs.push_back("-Bshareable");
3943    else {
3944      CmdArgs.push_back("-dynamic-linker");
3945      CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
3946    }
3947  }
3948
3949  // When building 32-bit code on DragonFly/pc64, we have to explicitly
3950  // instruct ld in the base system to link 32-bit code.
3951  if (getToolChain().getArchName() == "i386") {
3952    CmdArgs.push_back("-m");
3953    CmdArgs.push_back("elf_i386");
3954  }
3955
3956  if (Output.isFilename()) {
3957    CmdArgs.push_back("-o");
3958    CmdArgs.push_back(Output.getFilename());
3959  } else {
3960    assert(Output.isNothing() && "Invalid output.");
3961  }
3962
3963  if (!Args.hasArg(options::OPT_nostdlib) &&
3964      !Args.hasArg(options::OPT_nostartfiles)) {
3965    if (!Args.hasArg(options::OPT_shared)) {
3966      CmdArgs.push_back(
3967            Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
3968      CmdArgs.push_back(
3969            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
3970      CmdArgs.push_back(
3971            Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
3972    } else {
3973      CmdArgs.push_back(
3974            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
3975      CmdArgs.push_back(
3976            Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
3977    }
3978  }
3979
3980  Args.AddAllArgs(CmdArgs, options::OPT_L);
3981  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3982  Args.AddAllArgs(CmdArgs, options::OPT_e);
3983
3984  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3985
3986  if (!Args.hasArg(options::OPT_nostdlib) &&
3987      !Args.hasArg(options::OPT_nodefaultlibs)) {
3988    // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
3989    //         rpaths
3990    CmdArgs.push_back("-L/usr/lib/gcc41");
3991
3992    if (!Args.hasArg(options::OPT_static)) {
3993      CmdArgs.push_back("-rpath");
3994      CmdArgs.push_back("/usr/lib/gcc41");
3995
3996      CmdArgs.push_back("-rpath-link");
3997      CmdArgs.push_back("/usr/lib/gcc41");
3998
3999      CmdArgs.push_back("-rpath");
4000      CmdArgs.push_back("/usr/lib");
4001
4002      CmdArgs.push_back("-rpath-link");
4003      CmdArgs.push_back("/usr/lib");
4004    }
4005
4006    if (D.CCCIsCXX) {
4007      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4008      CmdArgs.push_back("-lm");
4009    }
4010
4011    if (Args.hasArg(options::OPT_shared)) {
4012      CmdArgs.push_back("-lgcc_pic");
4013    } else {
4014      CmdArgs.push_back("-lgcc");
4015    }
4016
4017
4018    if (Args.hasArg(options::OPT_pthread))
4019      CmdArgs.push_back("-lpthread");
4020
4021    if (!Args.hasArg(options::OPT_nolibc)) {
4022      CmdArgs.push_back("-lc");
4023    }
4024
4025    if (Args.hasArg(options::OPT_shared)) {
4026      CmdArgs.push_back("-lgcc_pic");
4027    } else {
4028      CmdArgs.push_back("-lgcc");
4029    }
4030  }
4031
4032  if (!Args.hasArg(options::OPT_nostdlib) &&
4033      !Args.hasArg(options::OPT_nostartfiles)) {
4034    if (!Args.hasArg(options::OPT_shared))
4035      CmdArgs.push_back(Args.MakeArgString(
4036                              getToolChain().GetFilePath("crtend.o")));
4037    else
4038      CmdArgs.push_back(Args.MakeArgString(
4039                              getToolChain().GetFilePath("crtendS.o")));
4040    CmdArgs.push_back(Args.MakeArgString(
4041                              getToolChain().GetFilePath("crtn.o")));
4042  }
4043
4044  const char *Exec =
4045    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4046  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4047}
4048
4049void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
4050                                      const InputInfo &Output,
4051                                      const InputInfoList &Inputs,
4052                                      const ArgList &Args,
4053                                      const char *LinkingOutput) const {
4054  ArgStringList CmdArgs;
4055
4056  if (Output.isFilename()) {
4057    CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
4058                                         Output.getFilename()));
4059  } else {
4060    assert(Output.isNothing() && "Invalid output.");
4061  }
4062
4063  if (!Args.hasArg(options::OPT_nostdlib) &&
4064    !Args.hasArg(options::OPT_nostartfiles)) {
4065    CmdArgs.push_back("-defaultlib:libcmt");
4066  }
4067
4068  CmdArgs.push_back("-nologo");
4069
4070  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4071
4072  const char *Exec =
4073    Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
4074  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4075}
4076