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