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