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