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