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