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