]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Driver/Tools.cpp
Vendor import of clang trunk r178860:
[FreeBSD/FreeBSD.git] / 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_fheinous_gnu_extensions);
2701   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
2702   Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
2703   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
2704   Args.AddLastArg(CmdArgs, options::OPT_faltivec);
2705   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
2706   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
2707
2708   SanitizerArgs Sanitize(D, Args);
2709   Sanitize.addArgs(Args, CmdArgs);
2710
2711   if (!Args.hasFlag(options::OPT_fsanitize_recover,
2712                     options::OPT_fno_sanitize_recover,
2713                     true))
2714     CmdArgs.push_back("-fno-sanitize-recover");
2715
2716   if (Args.hasArg(options::OPT_fcatch_undefined_behavior) ||
2717       Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
2718                    options::OPT_fno_sanitize_undefined_trap_on_error, false))
2719     CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
2720
2721   // Report an error for -faltivec on anything other than PowerPC.
2722   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
2723     if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc ||
2724           getToolChain().getTriple().getArch() == llvm::Triple::ppc64))
2725       D.Diag(diag::err_drv_argument_only_allowed_with)
2726         << A->getAsString(Args) << "ppc/ppc64";
2727
2728   if (getToolChain().SupportsProfiling())
2729     Args.AddLastArg(CmdArgs, options::OPT_pg);
2730
2731   // -flax-vector-conversions is default.
2732   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
2733                     options::OPT_fno_lax_vector_conversions))
2734     CmdArgs.push_back("-fno-lax-vector-conversions");
2735
2736   if (Args.getLastArg(options::OPT_fapple_kext))
2737     CmdArgs.push_back("-fapple-kext");
2738
2739   if (Args.hasFlag(options::OPT_frewrite_includes,
2740                    options::OPT_fno_rewrite_includes, false))
2741     CmdArgs.push_back("-frewrite-includes");
2742
2743   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
2744   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
2745   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
2746   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
2747   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
2748
2749   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
2750     CmdArgs.push_back("-ftrapv-handler");
2751     CmdArgs.push_back(A->getValue());
2752   }
2753
2754   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
2755
2756   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
2757   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
2758   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
2759                                options::OPT_fno_wrapv)) {
2760     if (A->getOption().matches(options::OPT_fwrapv))
2761       CmdArgs.push_back("-fwrapv");
2762   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
2763                                       options::OPT_fno_strict_overflow)) {
2764     if (A->getOption().matches(options::OPT_fno_strict_overflow))
2765       CmdArgs.push_back("-fwrapv");
2766   }
2767   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
2768   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
2769
2770   Args.AddLastArg(CmdArgs, options::OPT_pthread);
2771
2772
2773   // -stack-protector=0 is default.
2774   unsigned StackProtectorLevel = 0;
2775   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2776                                options::OPT_fstack_protector_all,
2777                                options::OPT_fstack_protector)) {
2778     if (A->getOption().matches(options::OPT_fstack_protector))
2779       StackProtectorLevel = 1;
2780     else if (A->getOption().matches(options::OPT_fstack_protector_all))
2781       StackProtectorLevel = 2;
2782   } else {
2783     StackProtectorLevel =
2784       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
2785   }
2786   if (StackProtectorLevel) {
2787     CmdArgs.push_back("-stack-protector");
2788     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2789   }
2790
2791   // --param ssp-buffer-size=
2792   for (arg_iterator it = Args.filtered_begin(options::OPT__param),
2793        ie = Args.filtered_end(); it != ie; ++it) {
2794     StringRef Str((*it)->getValue());
2795     if (Str.startswith("ssp-buffer-size=")) {
2796       if (StackProtectorLevel) {
2797         CmdArgs.push_back("-stack-protector-buffer-size");
2798         // FIXME: Verify the argument is a valid integer.
2799         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2800       }
2801       (*it)->claim();
2802     }
2803   }
2804
2805   // Translate -mstackrealign
2806   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
2807                    false)) {
2808     CmdArgs.push_back("-backend-option");
2809     CmdArgs.push_back("-force-align-stack");
2810   }
2811   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
2812                    false)) {
2813     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
2814   }
2815
2816   if (Args.hasArg(options::OPT_mstack_alignment)) {
2817     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
2818     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
2819   }
2820   // -mkernel implies -mstrict-align; don't add the redundant option.
2821   if (Args.hasArg(options::OPT_mstrict_align) && !KernelOrKext) {
2822     CmdArgs.push_back("-backend-option");
2823     CmdArgs.push_back("-arm-strict-align");
2824   }
2825
2826   // Forward -f options with positive and negative forms; we translate
2827   // these by hand.
2828
2829   if (Args.hasArg(options::OPT_mkernel)) {
2830     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
2831       CmdArgs.push_back("-fapple-kext");
2832     if (!Args.hasArg(options::OPT_fbuiltin))
2833       CmdArgs.push_back("-fno-builtin");
2834     Args.ClaimAllArgs(options::OPT_fno_builtin);
2835   }
2836   // -fbuiltin is default.
2837   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
2838     CmdArgs.push_back("-fno-builtin");
2839
2840   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2841                     options::OPT_fno_assume_sane_operator_new))
2842     CmdArgs.push_back("-fno-assume-sane-operator-new");
2843
2844   // -fblocks=0 is default.
2845   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
2846                    getToolChain().IsBlocksDefault()) ||
2847         (Args.hasArg(options::OPT_fgnu_runtime) &&
2848          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
2849          !Args.hasArg(options::OPT_fno_blocks))) {
2850     CmdArgs.push_back("-fblocks");
2851
2852     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
2853         !getToolChain().hasBlocksRuntime())
2854       CmdArgs.push_back("-fblocks-runtime-optional");
2855   }
2856
2857   // -fmodules enables modules (off by default). However, for C++/Objective-C++,
2858   // users must also pass -fcxx-modules. The latter flag will disappear once the
2859   // modules implementation is solid for C++/Objective-C++ programs as well.
2860   bool HaveModules = false;
2861   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2862     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
2863                                      options::OPT_fno_cxx_modules, 
2864                                      false);
2865     if (AllowedInCXX || !types::isCXX(InputType)) {
2866       CmdArgs.push_back("-fmodules");
2867       HaveModules = true;
2868     }
2869   }
2870
2871   // If a module path was provided, pass it along. Otherwise, use a temporary
2872   // directory.
2873   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) {
2874     A->claim();
2875     if (HaveModules) {
2876       A->render(Args, CmdArgs);
2877     }
2878   } else if (HaveModules) {
2879     SmallString<128> DefaultModuleCache;
2880     llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
2881                                            DefaultModuleCache);
2882     llvm::sys::path::append(DefaultModuleCache, "org.llvm.clang");
2883     llvm::sys::path::append(DefaultModuleCache, "ModuleCache");
2884     const char Arg[] = "-fmodules-cache-path=";
2885     DefaultModuleCache.insert(DefaultModuleCache.begin(),
2886                               Arg, Arg + strlen(Arg));
2887     CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
2888   }
2889
2890   // Pass through all -fmodules-ignore-macro arguments.
2891   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2892   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2893   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2894
2895   // -fmodules-autolink (on by default when modules is enabled) automatically
2896   // links against libraries for imported modules.  This requires the
2897   // integrated assembler.
2898   if (HaveModules && getToolChain().useIntegratedAs() &&
2899       Args.hasFlag(options::OPT_fmodules_autolink,
2900                    options::OPT_fno_modules_autolink,
2901                    true)) {
2902     CmdArgs.push_back("-fmodules-autolink");
2903   }
2904
2905   // -faccess-control is default.
2906   if (Args.hasFlag(options::OPT_fno_access_control,
2907                    options::OPT_faccess_control,
2908                    false))
2909     CmdArgs.push_back("-fno-access-control");
2910
2911   // -felide-constructors is the default.
2912   if (Args.hasFlag(options::OPT_fno_elide_constructors,
2913                    options::OPT_felide_constructors,
2914                    false))
2915     CmdArgs.push_back("-fno-elide-constructors");
2916
2917   // -frtti is default.
2918   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
2919       KernelOrKext) {
2920     CmdArgs.push_back("-fno-rtti");
2921
2922     // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
2923     if (Sanitize.sanitizesVptr()) {
2924       std::string NoRttiArg =
2925         Args.getLastArg(options::OPT_mkernel,
2926                         options::OPT_fapple_kext,
2927                         options::OPT_fno_rtti)->getAsString(Args);
2928       D.Diag(diag::err_drv_argument_not_allowed_with)
2929         << "-fsanitize=vptr" << NoRttiArg;
2930     }
2931   }
2932
2933   // -fshort-enums=0 is default for all architectures except Hexagon.
2934   if (Args.hasFlag(options::OPT_fshort_enums,
2935                    options::OPT_fno_short_enums,
2936                    getToolChain().getTriple().getArch() ==
2937                    llvm::Triple::hexagon))
2938     CmdArgs.push_back("-fshort-enums");
2939
2940   // -fsigned-char is default.
2941   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
2942                     isSignedCharDefault(getToolChain().getTriple())))
2943     CmdArgs.push_back("-fno-signed-char");
2944
2945   // -fthreadsafe-static is default.
2946   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
2947                     options::OPT_fno_threadsafe_statics))
2948     CmdArgs.push_back("-fno-threadsafe-statics");
2949
2950   // -fuse-cxa-atexit is default.
2951   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
2952                     options::OPT_fno_use_cxa_atexit,
2953                    getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
2954                   getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
2955               getToolChain().getTriple().getArch() != llvm::Triple::hexagon) ||
2956       KernelOrKext)
2957     CmdArgs.push_back("-fno-use-cxa-atexit");
2958
2959   // -fms-extensions=0 is default.
2960   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2961                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2962     CmdArgs.push_back("-fms-extensions");
2963
2964   // -fms-compatibility=0 is default.
2965   if (Args.hasFlag(options::OPT_fms_compatibility, 
2966                    options::OPT_fno_ms_compatibility,
2967                    (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
2968                     Args.hasFlag(options::OPT_fms_extensions, 
2969                                  options::OPT_fno_ms_extensions,
2970                                  true))))
2971     CmdArgs.push_back("-fms-compatibility");
2972
2973   // -fmsc-version=1300 is default.
2974   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2975                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
2976       Args.hasArg(options::OPT_fmsc_version)) {
2977     StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
2978     if (msc_ver.empty())
2979       CmdArgs.push_back("-fmsc-version=1300");
2980     else
2981       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
2982   }
2983
2984
2985   // -fno-borland-extensions is default.
2986   if (Args.hasFlag(options::OPT_fborland_extensions,
2987                    options::OPT_fno_borland_extensions, false))
2988     CmdArgs.push_back("-fborland-extensions");
2989
2990   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
2991   // needs it.
2992   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
2993                    options::OPT_fno_delayed_template_parsing,
2994                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2995     CmdArgs.push_back("-fdelayed-template-parsing");
2996
2997   // -fgnu-keywords default varies depending on language; only pass if
2998   // specified.
2999   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3000                                options::OPT_fno_gnu_keywords))
3001     A->render(Args, CmdArgs);
3002
3003   if (Args.hasFlag(options::OPT_fgnu89_inline,
3004                    options::OPT_fno_gnu89_inline,
3005                    false))
3006     CmdArgs.push_back("-fgnu89-inline");
3007
3008   if (Args.hasArg(options::OPT_fno_inline))
3009     CmdArgs.push_back("-fno-inline");
3010
3011   if (Args.hasArg(options::OPT_fno_inline_functions))
3012     CmdArgs.push_back("-fno-inline-functions");
3013
3014   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3015
3016   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3017   // legacy is the default.
3018   if (objcRuntime.isNonFragile()) {
3019     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3020                       options::OPT_fno_objc_legacy_dispatch,
3021                       objcRuntime.isLegacyDispatchDefaultForArch(
3022                         getToolChain().getTriple().getArch()))) {
3023       if (getToolChain().UseObjCMixedDispatch())
3024         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3025       else
3026         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3027     }
3028   }
3029
3030   // -fobjc-default-synthesize-properties=1 is default. This only has an effect
3031   // if the nonfragile objc abi is used.
3032   if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
3033     CmdArgs.push_back("-fobjc-default-synthesize-properties");
3034   }
3035
3036   // -fencode-extended-block-signature=1 is default.
3037   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3038     CmdArgs.push_back("-fencode-extended-block-signature");
3039   }
3040   
3041   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3042   // NOTE: This logic is duplicated in ToolChains.cpp.
3043   bool ARC = isObjCAutoRefCount(Args);
3044   if (ARC) {
3045     getToolChain().CheckObjCARC();
3046
3047     CmdArgs.push_back("-fobjc-arc");
3048
3049     // FIXME: It seems like this entire block, and several around it should be
3050     // wrapped in isObjC, but for now we just use it here as this is where it
3051     // was being used previously.
3052     if (types::isCXX(InputType) && types::isObjC(InputType)) {
3053       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3054         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3055       else
3056         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3057     }
3058
3059     // Allow the user to enable full exceptions code emission.
3060     // We define off for Objective-CC, on for Objective-C++.
3061     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3062                      options::OPT_fno_objc_arc_exceptions,
3063                      /*default*/ types::isCXX(InputType)))
3064       CmdArgs.push_back("-fobjc-arc-exceptions");
3065   }
3066
3067   // -fobjc-infer-related-result-type is the default, except in the Objective-C
3068   // rewriter.
3069   if (rewriteKind != RK_None)
3070     CmdArgs.push_back("-fno-objc-infer-related-result-type");
3071
3072   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
3073   // takes precedence.
3074   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
3075   if (!GCArg)
3076     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
3077   if (GCArg) {
3078     if (ARC) {
3079       D.Diag(diag::err_drv_objc_gc_arr)
3080         << GCArg->getAsString(Args);
3081     } else if (getToolChain().SupportsObjCGC()) {
3082       GCArg->render(Args, CmdArgs);
3083     } else {
3084       // FIXME: We should move this to a hard error.
3085       D.Diag(diag::warn_drv_objc_gc_unsupported)
3086         << GCArg->getAsString(Args);
3087     }
3088   }
3089
3090   // Add exception args.
3091   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
3092                    KernelOrKext, objcRuntime, CmdArgs);
3093
3094   if (getToolChain().UseSjLjExceptions())
3095     CmdArgs.push_back("-fsjlj-exceptions");
3096
3097   // C++ "sane" operator new.
3098   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3099                     options::OPT_fno_assume_sane_operator_new))
3100     CmdArgs.push_back("-fno-assume-sane-operator-new");
3101
3102   // -fconstant-cfstrings is default, and may be subject to argument translation
3103   // on Darwin.
3104   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3105                     options::OPT_fno_constant_cfstrings) ||
3106       !Args.hasFlag(options::OPT_mconstant_cfstrings,
3107                     options::OPT_mno_constant_cfstrings))
3108     CmdArgs.push_back("-fno-constant-cfstrings");
3109
3110   // -fshort-wchar default varies depending on platform; only
3111   // pass if specified.
3112   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
3113     A->render(Args, CmdArgs);
3114
3115   // -fno-pascal-strings is default, only pass non-default. If the tool chain
3116   // happened to translate to -mpascal-strings, we want to back translate here.
3117   //
3118   // FIXME: This is gross; that translation should be pulled from the
3119   // tool chain.
3120   if (Args.hasFlag(options::OPT_fpascal_strings,
3121                    options::OPT_fno_pascal_strings,
3122                    false) ||
3123       Args.hasFlag(options::OPT_mpascal_strings,
3124                    options::OPT_mno_pascal_strings,
3125                    false))
3126     CmdArgs.push_back("-fpascal-strings");
3127
3128   // Honor -fpack-struct= and -fpack-struct, if given. Note that
3129   // -fno-pack-struct doesn't apply to -fpack-struct=.
3130   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3131     std::string PackStructStr = "-fpack-struct=";
3132     PackStructStr += A->getValue();
3133     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3134   } else if (Args.hasFlag(options::OPT_fpack_struct,
3135                           options::OPT_fno_pack_struct, false)) {
3136     CmdArgs.push_back("-fpack-struct=1");
3137   }
3138
3139   if (KernelOrKext) {
3140     if (!Args.hasArg(options::OPT_fcommon))
3141       CmdArgs.push_back("-fno-common");
3142     Args.ClaimAllArgs(options::OPT_fno_common);
3143   }
3144
3145   // -fcommon is default, only pass non-default.
3146   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
3147     CmdArgs.push_back("-fno-common");
3148
3149   // -fsigned-bitfields is default, and clang doesn't yet support
3150   // -funsigned-bitfields.
3151   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3152                     options::OPT_funsigned_bitfields))
3153     D.Diag(diag::warn_drv_clang_unsupported)
3154       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3155
3156   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3157   if (!Args.hasFlag(options::OPT_ffor_scope,
3158                     options::OPT_fno_for_scope))
3159     D.Diag(diag::err_drv_clang_unsupported)
3160       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3161
3162   // -fcaret-diagnostics is default.
3163   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3164                     options::OPT_fno_caret_diagnostics, true))
3165     CmdArgs.push_back("-fno-caret-diagnostics");
3166
3167   // -fdiagnostics-fixit-info is default, only pass non-default.
3168   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3169                     options::OPT_fno_diagnostics_fixit_info))
3170     CmdArgs.push_back("-fno-diagnostics-fixit-info");
3171
3172   // Enable -fdiagnostics-show-option by default.
3173   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3174                    options::OPT_fno_diagnostics_show_option))
3175     CmdArgs.push_back("-fdiagnostics-show-option");
3176
3177   if (const Arg *A =
3178         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3179     CmdArgs.push_back("-fdiagnostics-show-category");
3180     CmdArgs.push_back(A->getValue());
3181   }
3182
3183   if (const Arg *A =
3184         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3185     CmdArgs.push_back("-fdiagnostics-format");
3186     CmdArgs.push_back(A->getValue());
3187   }
3188
3189   if (Arg *A = Args.getLastArg(
3190       options::OPT_fdiagnostics_show_note_include_stack,
3191       options::OPT_fno_diagnostics_show_note_include_stack)) {
3192     if (A->getOption().matches(
3193         options::OPT_fdiagnostics_show_note_include_stack))
3194       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3195     else
3196       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3197   }
3198
3199   // Color diagnostics are the default, unless the terminal doesn't support
3200   // them.
3201   if (Args.hasFlag(options::OPT_fcolor_diagnostics,
3202                    options::OPT_fno_color_diagnostics,
3203                    llvm::sys::Process::StandardErrHasColors()))
3204     CmdArgs.push_back("-fcolor-diagnostics");
3205
3206   if (!Args.hasFlag(options::OPT_fshow_source_location,
3207                     options::OPT_fno_show_source_location))
3208     CmdArgs.push_back("-fno-show-source-location");
3209
3210   if (!Args.hasFlag(options::OPT_fshow_column,
3211                     options::OPT_fno_show_column,
3212                     true))
3213     CmdArgs.push_back("-fno-show-column");
3214
3215   if (!Args.hasFlag(options::OPT_fspell_checking,
3216                     options::OPT_fno_spell_checking))
3217     CmdArgs.push_back("-fno-spell-checking");
3218
3219
3220   // -fno-asm-blocks is default.
3221   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
3222                    false))
3223     CmdArgs.push_back("-fasm-blocks");
3224
3225   // -fvectorize is default.
3226   if (Args.hasFlag(options::OPT_fvectorize,
3227                    options::OPT_fno_vectorize, true)) {
3228     CmdArgs.push_back("-backend-option");
3229     CmdArgs.push_back("-vectorize-loops");
3230   }
3231
3232   // -fno-slp-vectorize is default.
3233   if (Args.hasFlag(options::OPT_fslp_vectorize,
3234                    options::OPT_fno_slp_vectorize, false)) {
3235     CmdArgs.push_back("-backend-option");
3236     CmdArgs.push_back("-vectorize");
3237   }
3238
3239   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
3240     A->render(Args, CmdArgs);
3241
3242   // -fdollars-in-identifiers default varies depending on platform and
3243   // language; only pass if specified.
3244   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
3245                                options::OPT_fno_dollars_in_identifiers)) {
3246     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
3247       CmdArgs.push_back("-fdollars-in-identifiers");
3248     else
3249       CmdArgs.push_back("-fno-dollars-in-identifiers");
3250   }
3251
3252   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
3253   // practical purposes.
3254   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
3255                                options::OPT_fno_unit_at_a_time)) {
3256     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
3257       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
3258   }
3259
3260   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
3261                    options::OPT_fno_apple_pragma_pack, false))
3262     CmdArgs.push_back("-fapple-pragma-pack");
3263
3264   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
3265   //
3266   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
3267 #if 0
3268   if (getToolChain().getTriple().isOSDarwin() &&
3269       (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3270        getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
3271     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3272       CmdArgs.push_back("-fno-builtin-strcat");
3273     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3274       CmdArgs.push_back("-fno-builtin-strcpy");
3275   }
3276 #endif
3277
3278   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
3279   if (Arg *A = Args.getLastArg(options::OPT_traditional,
3280                                options::OPT_traditional_cpp)) {
3281     if (isa<PreprocessJobAction>(JA))
3282       CmdArgs.push_back("-traditional-cpp");
3283     else
3284       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
3285   }
3286
3287   Args.AddLastArg(CmdArgs, options::OPT_dM);
3288   Args.AddLastArg(CmdArgs, options::OPT_dD);
3289   
3290   // Handle serialized diagnostics.
3291   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
3292     CmdArgs.push_back("-serialize-diagnostic-file");
3293     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
3294   }
3295
3296   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
3297     CmdArgs.push_back("-fretain-comments-from-system-headers");
3298
3299   // Forward -fcomment-block-commands to -cc1.
3300   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
3301
3302   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
3303   // parser.
3304   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
3305   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
3306          ie = Args.filtered_end(); it != ie; ++it) {
3307     (*it)->claim();
3308
3309     // We translate this by hand to the -cc1 argument, since nightly test uses
3310     // it and developers have been trained to spell it with -mllvm.
3311     if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
3312       CmdArgs.push_back("-disable-llvm-optzns");
3313     else
3314       (*it)->render(Args, CmdArgs);
3315   }
3316
3317   if (Output.getType() == types::TY_Dependencies) {
3318     // Handled with other dependency code.
3319   } else if (Output.isFilename()) {
3320     CmdArgs.push_back("-o");
3321     CmdArgs.push_back(Output.getFilename());
3322   } else {
3323     assert(Output.isNothing() && "Invalid output.");
3324   }
3325
3326   for (InputInfoList::const_iterator
3327          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3328     const InputInfo &II = *it;
3329     CmdArgs.push_back("-x");
3330     if (Args.hasArg(options::OPT_rewrite_objc))
3331       CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3332     else
3333       CmdArgs.push_back(types::getTypeName(II.getType()));
3334     if (II.isFilename())
3335       CmdArgs.push_back(II.getFilename());
3336     else
3337       II.getInputArg().renderAsInput(Args, CmdArgs);
3338   }
3339
3340   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3341
3342   const char *Exec = getToolChain().getDriver().getClangProgramPath();
3343
3344   // Optionally embed the -cc1 level arguments into the debug info, for build
3345   // analysis.
3346   if (getToolChain().UseDwarfDebugFlags()) {
3347     ArgStringList OriginalArgs;
3348     for (ArgList::const_iterator it = Args.begin(),
3349            ie = Args.end(); it != ie; ++it)
3350       (*it)->render(Args, OriginalArgs);
3351
3352     SmallString<256> Flags;
3353     Flags += Exec;
3354     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3355       Flags += " ";
3356       Flags += OriginalArgs[i];
3357     }
3358     CmdArgs.push_back("-dwarf-debug-flags");
3359     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3360   }
3361
3362   // Add the split debug info name to the command lines here so we
3363   // can propagate it to the backend.
3364   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
3365     (getToolChain().getTriple().getOS() == llvm::Triple::Linux) &&
3366     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
3367   const char *SplitDwarfOut;
3368   if (SplitDwarf) {
3369     CmdArgs.push_back("-split-dwarf-file");
3370     SplitDwarfOut = SplitDebugName(Args, Inputs);
3371     CmdArgs.push_back(SplitDwarfOut);
3372   }
3373
3374   // Finally add the compile command to the compilation.
3375   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3376
3377   // Handle the debug info splitting at object creation time if we're
3378   // creating an object.
3379   // TODO: Currently only works on linux with newer objcopy.
3380   if (SplitDwarf && !isa<CompileJobAction>(JA))
3381     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
3382
3383   if (Arg *A = Args.getLastArg(options::OPT_pg))
3384     if (Args.hasArg(options::OPT_fomit_frame_pointer))
3385       D.Diag(diag::err_drv_argument_not_allowed_with)
3386         << "-fomit-frame-pointer" << A->getAsString(Args);
3387
3388   // Claim some arguments which clang supports automatically.
3389
3390   // -fpch-preprocess is used with gcc to add a special marker in the output to
3391   // include the PCH file. Clang's PTH solution is completely transparent, so we
3392   // do not need to deal with it at all.
3393   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
3394
3395   // Claim some arguments which clang doesn't support, but we don't
3396   // care to warn the user about.
3397   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
3398   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
3399
3400   // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
3401   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3402   Args.ClaimAllArgs(options::OPT_emit_llvm);
3403 }
3404
3405 void ClangAs::AddARMTargetArgs(const ArgList &Args,
3406                                ArgStringList &CmdArgs) const {
3407   const Driver &D = getToolChain().getDriver();
3408   llvm::Triple Triple = getToolChain().getTriple();
3409
3410   // Set the CPU based on -march= and -mcpu=.
3411   CmdArgs.push_back("-target-cpu");
3412   CmdArgs.push_back(Args.MakeArgString(getARMTargetCPU(Args, Triple)));
3413
3414   // Honor -mfpu=.
3415   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
3416     addFPUArgs(D, A, Args, CmdArgs);
3417
3418   // Honor -mfpmath=.
3419   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
3420     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
3421 }
3422
3423 void ClangAs::AddX86TargetArgs(const ArgList &Args,
3424                                ArgStringList &CmdArgs) const {
3425   // Set the CPU based on -march=.
3426   if (const char *CPUName = getX86TargetCPU(Args, getToolChain().getTriple())) {
3427     CmdArgs.push_back("-target-cpu");
3428     CmdArgs.push_back(CPUName);
3429   }
3430 }
3431
3432 /// Add options related to the Objective-C runtime/ABI.
3433 ///
3434 /// Returns true if the runtime is non-fragile.
3435 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
3436                                       ArgStringList &cmdArgs,
3437                                       RewriteKind rewriteKind) const {
3438   // Look for the controlling runtime option.
3439   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
3440                                     options::OPT_fgnu_runtime,
3441                                     options::OPT_fobjc_runtime_EQ);
3442
3443   // Just forward -fobjc-runtime= to the frontend.  This supercedes
3444   // options about fragility.
3445   if (runtimeArg &&
3446       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
3447     ObjCRuntime runtime;
3448     StringRef value = runtimeArg->getValue();
3449     if (runtime.tryParse(value)) {
3450       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
3451         << value;
3452     }
3453
3454     runtimeArg->render(args, cmdArgs);
3455     return runtime;
3456   }
3457
3458   // Otherwise, we'll need the ABI "version".  Version numbers are
3459   // slightly confusing for historical reasons:
3460   //   1 - Traditional "fragile" ABI
3461   //   2 - Non-fragile ABI, version 1
3462   //   3 - Non-fragile ABI, version 2
3463   unsigned objcABIVersion = 1;
3464   // If -fobjc-abi-version= is present, use that to set the version.
3465   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
3466     StringRef value = abiArg->getValue();
3467     if (value == "1")
3468       objcABIVersion = 1;
3469     else if (value == "2")
3470       objcABIVersion = 2;
3471     else if (value == "3")
3472       objcABIVersion = 3;
3473     else
3474       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3475         << value;
3476   } else {
3477     // Otherwise, determine if we are using the non-fragile ABI.
3478     bool nonFragileABIIsDefault = 
3479       (rewriteKind == RK_NonFragile || 
3480        (rewriteKind == RK_None &&
3481         getToolChain().IsObjCNonFragileABIDefault()));
3482     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
3483                      options::OPT_fno_objc_nonfragile_abi,
3484                      nonFragileABIIsDefault)) {
3485       // Determine the non-fragile ABI version to use.
3486 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
3487       unsigned nonFragileABIVersion = 1;
3488 #else
3489       unsigned nonFragileABIVersion = 2;
3490 #endif
3491
3492       if (Arg *abiArg = args.getLastArg(
3493             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
3494         StringRef value = abiArg->getValue();
3495         if (value == "1")
3496           nonFragileABIVersion = 1;
3497         else if (value == "2")
3498           nonFragileABIVersion = 2;
3499         else
3500           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3501             << value;
3502       }
3503
3504       objcABIVersion = 1 + nonFragileABIVersion;
3505     } else {
3506       objcABIVersion = 1;
3507     }
3508   }
3509
3510   // We don't actually care about the ABI version other than whether
3511   // it's non-fragile.
3512   bool isNonFragile = objcABIVersion != 1;
3513
3514   // If we have no runtime argument, ask the toolchain for its default runtime.
3515   // However, the rewriter only really supports the Mac runtime, so assume that.
3516   ObjCRuntime runtime;
3517   if (!runtimeArg) {
3518     switch (rewriteKind) {
3519     case RK_None:
3520       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3521       break;
3522     case RK_Fragile:
3523       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
3524       break;
3525     case RK_NonFragile:
3526       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3527       break;
3528     }
3529
3530   // -fnext-runtime
3531   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
3532     // On Darwin, make this use the default behavior for the toolchain.
3533     if (getToolChain().getTriple().isOSDarwin()) {
3534       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3535
3536     // Otherwise, build for a generic macosx port.
3537     } else {
3538       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3539     }
3540
3541   // -fgnu-runtime
3542   } else {
3543     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
3544     // Legacy behaviour is to target the gnustep runtime if we are i
3545     // non-fragile mode or the GCC runtime in fragile mode.
3546     if (isNonFragile)
3547       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
3548     else
3549       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
3550   }
3551
3552   cmdArgs.push_back(args.MakeArgString(
3553                                  "-fobjc-runtime=" + runtime.getAsString()));
3554   return runtime;
3555 }
3556
3557 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
3558                            const InputInfo &Output,
3559                            const InputInfoList &Inputs,
3560                            const ArgList &Args,
3561                            const char *LinkingOutput) const {
3562   ArgStringList CmdArgs;
3563
3564   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
3565   const InputInfo &Input = Inputs[0];
3566
3567   // Don't warn about "clang -w -c foo.s"
3568   Args.ClaimAllArgs(options::OPT_w);
3569   // and "clang -emit-llvm -c foo.s"
3570   Args.ClaimAllArgs(options::OPT_emit_llvm);
3571   // and "clang -use-gold-plugin -c foo.s"
3572   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3573
3574   // Invoke ourselves in -cc1as mode.
3575   //
3576   // FIXME: Implement custom jobs for internal actions.
3577   CmdArgs.push_back("-cc1as");
3578
3579   // Add the "effective" target triple.
3580   CmdArgs.push_back("-triple");
3581   std::string TripleStr = 
3582     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
3583   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3584
3585   // Set the output mode, we currently only expect to be used as a real
3586   // assembler.
3587   CmdArgs.push_back("-filetype");
3588   CmdArgs.push_back("obj");
3589
3590   // Set the main file name, so that debug info works even with
3591   // -save-temps or preprocessed assembly.
3592   CmdArgs.push_back("-main-file-name");
3593   CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
3594
3595   if (UseRelaxAll(C, Args))
3596     CmdArgs.push_back("-relax-all");
3597
3598   // Add target specific cpu and features flags.
3599   switch(getToolChain().getTriple().getArch()) {
3600   default:
3601     break;
3602
3603   case llvm::Triple::arm:
3604   case llvm::Triple::thumb:
3605     AddARMTargetArgs(Args, CmdArgs);
3606     break;
3607
3608   case llvm::Triple::x86:
3609   case llvm::Triple::x86_64:
3610     AddX86TargetArgs(Args, CmdArgs);
3611     break;
3612   }
3613
3614   // Ignore explicit -force_cpusubtype_ALL option.
3615   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
3616
3617   // Determine the original source input.
3618   const Action *SourceAction = &JA;
3619   while (SourceAction->getKind() != Action::InputClass) {
3620     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
3621     SourceAction = SourceAction->getInputs()[0];
3622   }
3623
3624   // Forward -g and handle debug info related flags, assuming we are dealing
3625   // with an actual assembly file.
3626   if (SourceAction->getType() == types::TY_Asm ||
3627       SourceAction->getType() == types::TY_PP_Asm) {
3628     Args.ClaimAllArgs(options::OPT_g_Group);
3629     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
3630       if (!A->getOption().matches(options::OPT_g0))
3631         CmdArgs.push_back("-g");
3632
3633     // Add the -fdebug-compilation-dir flag if needed.
3634     addDebugCompDirArg(Args, CmdArgs);
3635
3636     // Set the AT_producer to the clang version when using the integrated
3637     // assembler on assembly source files.
3638     CmdArgs.push_back("-dwarf-debug-producer");
3639     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
3640   }
3641
3642   // Optionally embed the -cc1as level arguments into the debug info, for build
3643   // analysis.
3644   if (getToolChain().UseDwarfDebugFlags()) {
3645     ArgStringList OriginalArgs;
3646     for (ArgList::const_iterator it = Args.begin(),
3647            ie = Args.end(); it != ie; ++it)
3648       (*it)->render(Args, OriginalArgs);
3649
3650     SmallString<256> Flags;
3651     const char *Exec = getToolChain().getDriver().getClangProgramPath();
3652     Flags += Exec;
3653     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3654       Flags += " ";
3655       Flags += OriginalArgs[i];
3656     }
3657     CmdArgs.push_back("-dwarf-debug-flags");
3658     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3659   }
3660
3661   // FIXME: Add -static support, once we have it.
3662
3663   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3664                        options::OPT_Xassembler);
3665   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
3666
3667   assert(Output.isFilename() && "Unexpected lipo output.");
3668   CmdArgs.push_back("-o");
3669   CmdArgs.push_back(Output.getFilename());
3670
3671   assert(Input.isFilename() && "Invalid input.");
3672   CmdArgs.push_back(Input.getFilename());
3673
3674   const char *Exec = getToolChain().getDriver().getClangProgramPath();
3675   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3676 }
3677
3678 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
3679                                const InputInfo &Output,
3680                                const InputInfoList &Inputs,
3681                                const ArgList &Args,
3682                                const char *LinkingOutput) const {
3683   const Driver &D = getToolChain().getDriver();
3684   ArgStringList CmdArgs;
3685
3686   for (ArgList::const_iterator
3687          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3688     Arg *A = *it;
3689     if (forwardToGCC(A->getOption())) {
3690       // Don't forward any -g arguments to assembly steps.
3691       if (isa<AssembleJobAction>(JA) &&
3692           A->getOption().matches(options::OPT_g_Group))
3693         continue;
3694
3695       // It is unfortunate that we have to claim here, as this means
3696       // we will basically never report anything interesting for
3697       // platforms using a generic gcc, even if we are just using gcc
3698       // to get to the assembler.
3699       A->claim();
3700       A->render(Args, CmdArgs);
3701     }
3702   }
3703
3704   RenderExtraToolArgs(JA, CmdArgs);
3705
3706   // If using a driver driver, force the arch.
3707   llvm::Triple::ArchType Arch = getToolChain().getArch();
3708   if (getToolChain().getTriple().isOSDarwin()) {
3709     CmdArgs.push_back("-arch");
3710
3711     // FIXME: Remove these special cases.
3712     if (Arch == llvm::Triple::ppc)
3713       CmdArgs.push_back("ppc");
3714     else if (Arch == llvm::Triple::ppc64)
3715       CmdArgs.push_back("ppc64");
3716     else
3717       CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName()));
3718   }
3719
3720   // Try to force gcc to match the tool chain we want, if we recognize
3721   // the arch.
3722   //
3723   // FIXME: The triple class should directly provide the information we want
3724   // here.
3725   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
3726     CmdArgs.push_back("-m32");
3727   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64)
3728     CmdArgs.push_back("-m64");
3729
3730   if (Output.isFilename()) {
3731     CmdArgs.push_back("-o");
3732     CmdArgs.push_back(Output.getFilename());
3733   } else {
3734     assert(Output.isNothing() && "Unexpected output");
3735     CmdArgs.push_back("-fsyntax-only");
3736   }
3737
3738   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3739                        options::OPT_Xassembler);
3740
3741   // Only pass -x if gcc will understand it; otherwise hope gcc
3742   // understands the suffix correctly. The main use case this would go
3743   // wrong in is for linker inputs if they happened to have an odd
3744   // suffix; really the only way to get this to happen is a command
3745   // like '-x foobar a.c' which will treat a.c like a linker input.
3746   //
3747   // FIXME: For the linker case specifically, can we safely convert
3748   // inputs into '-Wl,' options?
3749   for (InputInfoList::const_iterator
3750          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3751     const InputInfo &II = *it;
3752
3753     // Don't try to pass LLVM or AST inputs to a generic gcc.
3754     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3755         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3756       D.Diag(diag::err_drv_no_linker_llvm_support)
3757         << getToolChain().getTripleString();
3758     else if (II.getType() == types::TY_AST)
3759       D.Diag(diag::err_drv_no_ast_support)
3760         << getToolChain().getTripleString();
3761     else if (II.getType() == types::TY_ModuleFile)
3762       D.Diag(diag::err_drv_no_module_support)
3763         << getToolChain().getTripleString();
3764
3765     if (types::canTypeBeUserSpecified(II.getType())) {
3766       CmdArgs.push_back("-x");
3767       CmdArgs.push_back(types::getTypeName(II.getType()));
3768     }
3769
3770     if (II.isFilename())
3771       CmdArgs.push_back(II.getFilename());
3772     else {
3773       const Arg &A = II.getInputArg();
3774
3775       // Reverse translate some rewritten options.
3776       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
3777         CmdArgs.push_back("-lstdc++");
3778         continue;
3779       }
3780
3781       // Don't render as input, we need gcc to do the translations.
3782       A.render(Args, CmdArgs);
3783     }
3784   }
3785
3786   const std::string customGCCName = D.getCCCGenericGCCName();
3787   const char *GCCName;
3788   if (!customGCCName.empty())
3789     GCCName = customGCCName.c_str();
3790   else if (D.CCCIsCXX) {
3791     GCCName = "g++";
3792   } else
3793     GCCName = "gcc";
3794
3795   const char *Exec =
3796     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3797   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3798 }
3799
3800 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
3801                                           ArgStringList &CmdArgs) const {
3802   CmdArgs.push_back("-E");
3803 }
3804
3805 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
3806                                           ArgStringList &CmdArgs) const {
3807   // The type is good enough.
3808 }
3809
3810 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
3811                                        ArgStringList &CmdArgs) const {
3812   const Driver &D = getToolChain().getDriver();
3813
3814   // If -flto, etc. are present then make sure not to force assembly output.
3815   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
3816       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
3817     CmdArgs.push_back("-c");
3818   else {
3819     if (JA.getType() != types::TY_PP_Asm)
3820       D.Diag(diag::err_drv_invalid_gcc_output_type)
3821         << getTypeName(JA.getType());
3822
3823     CmdArgs.push_back("-S");
3824   }
3825 }
3826
3827 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
3828                                         ArgStringList &CmdArgs) const {
3829   CmdArgs.push_back("-c");
3830 }
3831
3832 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
3833                                     ArgStringList &CmdArgs) const {
3834   // The types are (hopefully) good enough.
3835 }
3836
3837 // Hexagon tools start.
3838 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
3839                                         ArgStringList &CmdArgs) const {
3840
3841 }
3842 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3843                                const InputInfo &Output,
3844                                const InputInfoList &Inputs,
3845                                const ArgList &Args,
3846                                const char *LinkingOutput) const {
3847
3848   const Driver &D = getToolChain().getDriver();
3849   ArgStringList CmdArgs;
3850
3851   std::string MarchString = "-march=";
3852   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
3853   CmdArgs.push_back(Args.MakeArgString(MarchString));
3854
3855   RenderExtraToolArgs(JA, CmdArgs);
3856
3857   if (Output.isFilename()) {
3858     CmdArgs.push_back("-o");
3859     CmdArgs.push_back(Output.getFilename());
3860   } else {
3861     assert(Output.isNothing() && "Unexpected output");
3862     CmdArgs.push_back("-fsyntax-only");
3863   }
3864
3865   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
3866   if (!SmallDataThreshold.empty())
3867     CmdArgs.push_back(
3868       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
3869
3870   Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
3871   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3872                        options::OPT_Xassembler);
3873
3874   // Only pass -x if gcc will understand it; otherwise hope gcc
3875   // understands the suffix correctly. The main use case this would go
3876   // wrong in is for linker inputs if they happened to have an odd
3877   // suffix; really the only way to get this to happen is a command
3878   // like '-x foobar a.c' which will treat a.c like a linker input.
3879   //
3880   // FIXME: For the linker case specifically, can we safely convert
3881   // inputs into '-Wl,' options?
3882   for (InputInfoList::const_iterator
3883          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3884     const InputInfo &II = *it;
3885
3886     // Don't try to pass LLVM or AST inputs to a generic gcc.
3887     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3888         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3889       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3890         << getToolChain().getTripleString();
3891     else if (II.getType() == types::TY_AST)
3892       D.Diag(clang::diag::err_drv_no_ast_support)
3893         << getToolChain().getTripleString();
3894     else if (II.getType() == types::TY_ModuleFile)
3895       D.Diag(diag::err_drv_no_module_support)
3896       << getToolChain().getTripleString();
3897
3898     if (II.isFilename())
3899       CmdArgs.push_back(II.getFilename());
3900     else
3901       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3902       II.getInputArg().render(Args, CmdArgs);
3903   }
3904
3905   const char *GCCName = "hexagon-as";
3906   const char *Exec =
3907     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3908   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3909
3910 }
3911 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
3912                                     ArgStringList &CmdArgs) const {
3913   // The types are (hopefully) good enough.
3914 }
3915
3916 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
3917                                const InputInfo &Output,
3918                                const InputInfoList &Inputs,
3919                                const ArgList &Args,
3920                                const char *LinkingOutput) const {
3921
3922   const toolchains::Hexagon_TC& ToolChain =
3923     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
3924   const Driver &D = ToolChain.getDriver();
3925
3926   ArgStringList CmdArgs;
3927
3928   //----------------------------------------------------------------------------
3929   //
3930   //----------------------------------------------------------------------------
3931   bool hasStaticArg = Args.hasArg(options::OPT_static);
3932   bool buildingLib = Args.hasArg(options::OPT_shared);
3933   bool buildPIE = Args.hasArg(options::OPT_pie);
3934   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
3935   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
3936   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
3937   bool useShared = buildingLib && !hasStaticArg;
3938
3939   //----------------------------------------------------------------------------
3940   // Silence warnings for various options
3941   //----------------------------------------------------------------------------
3942
3943   Args.ClaimAllArgs(options::OPT_g_Group);
3944   Args.ClaimAllArgs(options::OPT_emit_llvm);
3945   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
3946                                      // handled somewhere else.
3947   Args.ClaimAllArgs(options::OPT_static_libgcc);
3948
3949   //----------------------------------------------------------------------------
3950   //
3951   //----------------------------------------------------------------------------
3952   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
3953          e = ToolChain.ExtraOpts.end();
3954        i != e; ++i)
3955     CmdArgs.push_back(i->c_str());
3956
3957   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
3958   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
3959
3960   if (buildingLib) {
3961     CmdArgs.push_back("-shared");
3962     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
3963                                        // hexagon-gcc does
3964   }
3965
3966   if (hasStaticArg)
3967     CmdArgs.push_back("-static");
3968
3969   if (buildPIE && !buildingLib)
3970     CmdArgs.push_back("-pie");
3971
3972   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
3973   if (!SmallDataThreshold.empty()) {
3974     CmdArgs.push_back(
3975       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
3976   }
3977
3978   //----------------------------------------------------------------------------
3979   //
3980   //----------------------------------------------------------------------------
3981   CmdArgs.push_back("-o");
3982   CmdArgs.push_back(Output.getFilename());
3983
3984   const std::string MarchSuffix = "/" + MarchString;
3985   const std::string G0Suffix = "/G0";
3986   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
3987   const std::string RootDir = toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir)
3988                               + "/";
3989   const std::string StartFilesDir = RootDir
3990                                     + "hexagon/lib"
3991                                     + (buildingLib
3992                                        ? MarchG0Suffix : MarchSuffix);
3993
3994   //----------------------------------------------------------------------------
3995   // moslib
3996   //----------------------------------------------------------------------------
3997   std::vector<std::string> oslibs;
3998   bool hasStandalone= false;
3999
4000   for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
4001          ie = Args.filtered_end(); it != ie; ++it) {
4002     (*it)->claim();
4003     oslibs.push_back((*it)->getValue());
4004     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
4005   }
4006   if (oslibs.empty()) {
4007     oslibs.push_back("standalone");
4008     hasStandalone = true;
4009   }
4010
4011   //----------------------------------------------------------------------------
4012   // Start Files
4013   //----------------------------------------------------------------------------
4014   if (incStdLib && incStartFiles) {
4015
4016     if (!buildingLib) {
4017       if (hasStandalone) {
4018         CmdArgs.push_back(
4019           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
4020       }
4021       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
4022     }
4023     std::string initObj = useShared ? "/initS.o" : "/init.o";
4024     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
4025   }
4026
4027   //----------------------------------------------------------------------------
4028   // Library Search Paths
4029   //----------------------------------------------------------------------------
4030   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
4031   for (ToolChain::path_list::const_iterator
4032          i = LibPaths.begin(),
4033          e = LibPaths.end();
4034        i != e;
4035        ++i)
4036     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
4037
4038   //----------------------------------------------------------------------------
4039   //
4040   //----------------------------------------------------------------------------
4041   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4042   Args.AddAllArgs(CmdArgs, options::OPT_e);
4043   Args.AddAllArgs(CmdArgs, options::OPT_s);
4044   Args.AddAllArgs(CmdArgs, options::OPT_t);
4045   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4046
4047   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
4048
4049   //----------------------------------------------------------------------------
4050   // Libraries
4051   //----------------------------------------------------------------------------
4052   if (incStdLib && incDefLibs) {
4053     if (D.CCCIsCXX) {
4054       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
4055       CmdArgs.push_back("-lm");
4056     }
4057
4058     CmdArgs.push_back("--start-group");
4059
4060     if (!buildingLib) {
4061       for(std::vector<std::string>::iterator i = oslibs.begin(),
4062             e = oslibs.end(); i != e; ++i)
4063         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
4064       CmdArgs.push_back("-lc");
4065     }
4066     CmdArgs.push_back("-lgcc");
4067
4068     CmdArgs.push_back("--end-group");
4069   }
4070
4071   //----------------------------------------------------------------------------
4072   // End files
4073   //----------------------------------------------------------------------------
4074   if (incStdLib && incStartFiles) {
4075     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
4076     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
4077   }
4078
4079   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
4080   C.addCommand(
4081     new Command(
4082       JA, *this,
4083       Args.MakeArgString(Linker), CmdArgs));
4084 }
4085 // Hexagon tools end.
4086
4087 llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Str) {
4088   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
4089   // archs which Darwin doesn't use.
4090
4091   // The matching this routine does is fairly pointless, since it is neither the
4092   // complete architecture list, nor a reasonable subset. The problem is that
4093   // historically the driver driver accepts this and also ties its -march=
4094   // handling to the architecture name, so we need to be careful before removing
4095   // support for it.
4096
4097   // This code must be kept in sync with Clang's Darwin specific argument
4098   // translation.
4099
4100   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
4101     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
4102     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
4103     .Case("ppc64", llvm::Triple::ppc64)
4104     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
4105     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
4106            llvm::Triple::x86)
4107     .Case("x86_64", llvm::Triple::x86_64)
4108     // This is derived from the driver driver.
4109     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
4110     .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm)
4111     .Cases("armv7s", "xscale", llvm::Triple::arm)
4112     .Case("r600", llvm::Triple::r600)
4113     .Case("nvptx", llvm::Triple::nvptx)
4114     .Case("nvptx64", llvm::Triple::nvptx64)
4115     .Case("amdil", llvm::Triple::amdil)
4116     .Case("spir", llvm::Triple::spir)
4117     .Default(llvm::Triple::UnknownArch);
4118 }
4119
4120 const char *Clang::getBaseInputName(const ArgList &Args,
4121                                     const InputInfoList &Inputs) {
4122   return Args.MakeArgString(
4123     llvm::sys::path::filename(Inputs[0].getBaseInput()));
4124 }
4125
4126 const char *Clang::getBaseInputStem(const ArgList &Args,
4127                                     const InputInfoList &Inputs) {
4128   const char *Str = getBaseInputName(Args, Inputs);
4129
4130   if (const char *End = strrchr(Str, '.'))
4131     return Args.MakeArgString(std::string(Str, End));
4132
4133   return Str;
4134 }
4135
4136 const char *Clang::getDependencyFileName(const ArgList &Args,
4137                                          const InputInfoList &Inputs) {
4138   // FIXME: Think about this more.
4139   std::string Res;
4140
4141   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4142     std::string Str(OutputOpt->getValue());
4143     Res = Str.substr(0, Str.rfind('.'));
4144   } else {
4145     Res = getBaseInputStem(Args, Inputs);
4146   }
4147   return Args.MakeArgString(Res + ".d");
4148 }
4149
4150 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4151                                     const InputInfo &Output,
4152                                     const InputInfoList &Inputs,
4153                                     const ArgList &Args,
4154                                     const char *LinkingOutput) const {
4155   ArgStringList CmdArgs;
4156
4157   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4158   const InputInfo &Input = Inputs[0];
4159
4160   // Determine the original source input.
4161   const Action *SourceAction = &JA;
4162   while (SourceAction->getKind() != Action::InputClass) {
4163     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4164     SourceAction = SourceAction->getInputs()[0];
4165   }
4166
4167   // Forward -g, assuming we are dealing with an actual assembly file.
4168   if (SourceAction->getType() == types::TY_Asm ||
4169       SourceAction->getType() == types::TY_PP_Asm) {
4170     if (Args.hasArg(options::OPT_gstabs))
4171       CmdArgs.push_back("--gstabs");
4172     else if (Args.hasArg(options::OPT_g_Group))
4173       CmdArgs.push_back("-g");
4174   }
4175
4176   // Derived from asm spec.
4177   AddDarwinArch(Args, CmdArgs);
4178
4179   // Use -force_cpusubtype_ALL on x86 by default.
4180   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
4181       getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
4182       Args.hasArg(options::OPT_force__cpusubtype__ALL))
4183     CmdArgs.push_back("-force_cpusubtype_ALL");
4184
4185   if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
4186       (((Args.hasArg(options::OPT_mkernel) ||
4187          Args.hasArg(options::OPT_fapple_kext)) &&
4188         (!getDarwinToolChain().isTargetIPhoneOS() ||
4189          getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) ||
4190        Args.hasArg(options::OPT_static)))
4191     CmdArgs.push_back("-static");
4192
4193   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4194                        options::OPT_Xassembler);
4195
4196   assert(Output.isFilename() && "Unexpected lipo output.");
4197   CmdArgs.push_back("-o");
4198   CmdArgs.push_back(Output.getFilename());
4199
4200   assert(Input.isFilename() && "Invalid input.");
4201   CmdArgs.push_back(Input.getFilename());
4202
4203   // asm_final spec is empty.
4204
4205   const char *Exec =
4206     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4207   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4208 }
4209
4210 void darwin::DarwinTool::anchor() {}
4211
4212 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4213                                        ArgStringList &CmdArgs) const {
4214   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4215
4216   // Derived from darwin_arch spec.
4217   CmdArgs.push_back("-arch");
4218   CmdArgs.push_back(Args.MakeArgString(ArchName));
4219
4220   // FIXME: Is this needed anymore?
4221   if (ArchName == "arm")
4222     CmdArgs.push_back("-force_cpusubtype_ALL");
4223 }
4224
4225 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
4226   // We only need to generate a temp path for LTO if we aren't compiling object
4227   // files. When compiling source files, we run 'dsymutil' after linking. We
4228   // don't run 'dsymutil' when compiling object files.
4229   for (InputInfoList::const_iterator
4230          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it)
4231     if (it->getType() != types::TY_Object)
4232       return true;
4233
4234   return false;
4235 }
4236
4237 void darwin::Link::AddLinkArgs(Compilation &C,
4238                                const ArgList &Args,
4239                                ArgStringList &CmdArgs,
4240                                const InputInfoList &Inputs) const {
4241   const Driver &D = getToolChain().getDriver();
4242   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4243
4244   unsigned Version[3] = { 0, 0, 0 };
4245   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4246     bool HadExtra;
4247     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
4248                                    Version[1], Version[2], HadExtra) ||
4249         HadExtra)
4250       D.Diag(diag::err_drv_invalid_version_number)
4251         << A->getAsString(Args);
4252   }
4253
4254   // Newer linkers support -demangle, pass it if supported and not disabled by
4255   // the user.
4256   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4257     // Don't pass -demangle to ld_classic.
4258     //
4259     // FIXME: This is a temporary workaround, ld should be handling this.
4260     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4261                           Args.hasArg(options::OPT_static));
4262     if (getToolChain().getArch() == llvm::Triple::x86) {
4263       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4264                                                  options::OPT_Wl_COMMA),
4265              ie = Args.filtered_end(); it != ie; ++it) {
4266         const Arg *A = *it;
4267         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4268           if (StringRef(A->getValue(i)) == "-kext")
4269             UsesLdClassic = true;
4270       }
4271     }
4272     if (!UsesLdClassic)
4273       CmdArgs.push_back("-demangle");
4274   }
4275
4276   // If we are using LTO, then automatically create a temporary file path for
4277   // the linker to use, so that it's lifetime will extend past a possible
4278   // dsymutil step.
4279   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
4280     const char *TmpPath = C.getArgs().MakeArgString(
4281       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4282     C.addTempFile(TmpPath);
4283     CmdArgs.push_back("-object_path_lto");
4284     CmdArgs.push_back(TmpPath);
4285   }
4286
4287   // Derived from the "link" spec.
4288   Args.AddAllArgs(CmdArgs, options::OPT_static);
4289   if (!Args.hasArg(options::OPT_static))
4290     CmdArgs.push_back("-dynamic");
4291   if (Args.hasArg(options::OPT_fgnu_runtime)) {
4292     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4293     // here. How do we wish to handle such things?
4294   }
4295
4296   if (!Args.hasArg(options::OPT_dynamiclib)) {
4297     AddDarwinArch(Args, CmdArgs);
4298     // FIXME: Why do this only on this path?
4299     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4300
4301     Args.AddLastArg(CmdArgs, options::OPT_bundle);
4302     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4303     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4304
4305     Arg *A;
4306     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4307         (A = Args.getLastArg(options::OPT_current__version)) ||
4308         (A = Args.getLastArg(options::OPT_install__name)))
4309       D.Diag(diag::err_drv_argument_only_allowed_with)
4310         << A->getAsString(Args) << "-dynamiclib";
4311
4312     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4313     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4314     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4315   } else {
4316     CmdArgs.push_back("-dylib");
4317
4318     Arg *A;
4319     if ((A = Args.getLastArg(options::OPT_bundle)) ||
4320         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4321         (A = Args.getLastArg(options::OPT_client__name)) ||
4322         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4323         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4324         (A = Args.getLastArg(options::OPT_private__bundle)))
4325       D.Diag(diag::err_drv_argument_not_allowed_with)
4326         << A->getAsString(Args) << "-dynamiclib";
4327
4328     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4329                               "-dylib_compatibility_version");
4330     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4331                               "-dylib_current_version");
4332
4333     AddDarwinArch(Args, CmdArgs);
4334
4335     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4336                               "-dylib_install_name");
4337   }
4338
4339   Args.AddLastArg(CmdArgs, options::OPT_all__load);
4340   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4341   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4342   if (DarwinTC.isTargetIPhoneOS())
4343     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4344   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4345   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4346   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4347   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4348   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4349   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4350   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4351   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4352   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4353   Args.AddAllArgs(CmdArgs, options::OPT_init);
4354
4355   // Add the deployment target.
4356   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4357
4358   // If we had an explicit -mios-simulator-version-min argument, honor that,
4359   // otherwise use the traditional deployment targets. We can't just check the
4360   // is-sim attribute because existing code follows this path, and the linker
4361   // may not handle the argument.
4362   //
4363   // FIXME: We may be able to remove this, once we can verify no one depends on
4364   // it.
4365   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4366     CmdArgs.push_back("-ios_simulator_version_min");
4367   else if (DarwinTC.isTargetIPhoneOS())
4368     CmdArgs.push_back("-iphoneos_version_min");
4369   else
4370     CmdArgs.push_back("-macosx_version_min");
4371   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4372
4373   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4374   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4375   Args.AddLastArg(CmdArgs, options::OPT_single__module);
4376   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4377   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4378
4379   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4380                                      options::OPT_fno_pie,
4381                                      options::OPT_fno_PIE)) {
4382     if (A->getOption().matches(options::OPT_fpie) ||
4383         A->getOption().matches(options::OPT_fPIE))
4384       CmdArgs.push_back("-pie");
4385     else
4386       CmdArgs.push_back("-no_pie");
4387   }
4388
4389   Args.AddLastArg(CmdArgs, options::OPT_prebind);
4390   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4391   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4392   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4393   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4394   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4395   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4396   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4397   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4398   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4399   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4400   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4401   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4402   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4403   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4404   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4405
4406   // Give --sysroot= preference, over the Apple specific behavior to also use
4407   // --isysroot as the syslibroot.
4408   StringRef sysroot = C.getSysRoot();
4409   if (sysroot != "") {
4410     CmdArgs.push_back("-syslibroot");
4411     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4412   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4413     CmdArgs.push_back("-syslibroot");
4414     CmdArgs.push_back(A->getValue());
4415   }
4416
4417   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4418   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4419   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4420   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4421   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4422   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4423   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4424   Args.AddAllArgs(CmdArgs, options::OPT_y);
4425   Args.AddLastArg(CmdArgs, options::OPT_w);
4426   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4427   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4428   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4429   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4430   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4431   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4432   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4433   Args.AddLastArg(CmdArgs, options::OPT_whyload);
4434   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4435   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4436   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4437   Args.AddLastArg(CmdArgs, options::OPT_Mach);
4438 }
4439
4440 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4441                                 const InputInfo &Output,
4442                                 const InputInfoList &Inputs,
4443                                 const ArgList &Args,
4444                                 const char *LinkingOutput) const {
4445   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4446
4447   // The logic here is derived from gcc's behavior; most of which
4448   // comes from specs (starting with link_command). Consult gcc for
4449   // more information.
4450   ArgStringList CmdArgs;
4451
4452   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4453   if (Args.hasArg(options::OPT_ccc_arcmt_check,
4454                   options::OPT_ccc_arcmt_migrate)) {
4455     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4456       (*I)->claim();
4457     const char *Exec =
4458       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4459     CmdArgs.push_back(Output.getFilename());
4460     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4461     return;
4462   }
4463
4464   // I'm not sure why this particular decomposition exists in gcc, but
4465   // we follow suite for ease of comparison.
4466   AddLinkArgs(C, Args, CmdArgs, Inputs);
4467
4468   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4469   Args.AddAllArgs(CmdArgs, options::OPT_s);
4470   Args.AddAllArgs(CmdArgs, options::OPT_t);
4471   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4472   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4473   Args.AddLastArg(CmdArgs, options::OPT_e);
4474   Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
4475   Args.AddAllArgs(CmdArgs, options::OPT_r);
4476
4477   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4478   // members of static archive libraries which implement Objective-C classes or
4479   // categories.
4480   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4481     CmdArgs.push_back("-ObjC");
4482
4483   if (Args.hasArg(options::OPT_rdynamic))
4484     CmdArgs.push_back("-export_dynamic");
4485
4486   CmdArgs.push_back("-o");
4487   CmdArgs.push_back(Output.getFilename());
4488
4489   if (!Args.hasArg(options::OPT_nostdlib) &&
4490       !Args.hasArg(options::OPT_nostartfiles)) {
4491     // Derived from startfile spec.
4492     if (Args.hasArg(options::OPT_dynamiclib)) {
4493       // Derived from darwin_dylib1 spec.
4494       if (getDarwinToolChain().isTargetIOSSimulator()) {
4495         // The simulator doesn't have a versioned crt1 file.
4496         CmdArgs.push_back("-ldylib1.o");
4497       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4498         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4499           CmdArgs.push_back("-ldylib1.o");
4500       } else {
4501         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4502           CmdArgs.push_back("-ldylib1.o");
4503         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4504           CmdArgs.push_back("-ldylib1.10.5.o");
4505       }
4506     } else {
4507       if (Args.hasArg(options::OPT_bundle)) {
4508         if (!Args.hasArg(options::OPT_static)) {
4509           // Derived from darwin_bundle1 spec.
4510           if (getDarwinToolChain().isTargetIOSSimulator()) {
4511             // The simulator doesn't have a versioned crt1 file.
4512             CmdArgs.push_back("-lbundle1.o");
4513           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4514             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4515               CmdArgs.push_back("-lbundle1.o");
4516           } else {
4517             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4518               CmdArgs.push_back("-lbundle1.o");
4519           }
4520         }
4521       } else {
4522         if (Args.hasArg(options::OPT_pg) &&
4523             getToolChain().SupportsProfiling()) {
4524           if (Args.hasArg(options::OPT_static) ||
4525               Args.hasArg(options::OPT_object) ||
4526               Args.hasArg(options::OPT_preload)) {
4527             CmdArgs.push_back("-lgcrt0.o");
4528           } else {
4529             CmdArgs.push_back("-lgcrt1.o");
4530
4531             // darwin_crt2 spec is empty.
4532           }
4533           // By default on OS X 10.8 and later, we don't link with a crt1.o
4534           // file and the linker knows to use _main as the entry point.  But,
4535           // when compiling with -pg, we need to link with the gcrt1.o file,
4536           // so pass the -no_new_main option to tell the linker to use the
4537           // "start" symbol as the entry point.
4538           if (getDarwinToolChain().isTargetMacOS() &&
4539               !getDarwinToolChain().isMacosxVersionLT(10, 8))
4540             CmdArgs.push_back("-no_new_main");
4541         } else {
4542           if (Args.hasArg(options::OPT_static) ||
4543               Args.hasArg(options::OPT_object) ||
4544               Args.hasArg(options::OPT_preload)) {
4545             CmdArgs.push_back("-lcrt0.o");
4546           } else {
4547             // Derived from darwin_crt1 spec.
4548             if (getDarwinToolChain().isTargetIOSSimulator()) {
4549               // The simulator doesn't have a versioned crt1 file.
4550               CmdArgs.push_back("-lcrt1.o");
4551             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4552               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4553                 CmdArgs.push_back("-lcrt1.o");
4554               else if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0))
4555                 CmdArgs.push_back("-lcrt1.3.1.o");
4556             } else {
4557               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4558                 CmdArgs.push_back("-lcrt1.o");
4559               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4560                 CmdArgs.push_back("-lcrt1.10.5.o");
4561               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
4562                 CmdArgs.push_back("-lcrt1.10.6.o");
4563
4564               // darwin_crt2 spec is empty.
4565             }
4566           }
4567         }
4568       }
4569     }
4570
4571     if (!getDarwinToolChain().isTargetIPhoneOS() &&
4572         Args.hasArg(options::OPT_shared_libgcc) &&
4573         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
4574       const char *Str =
4575         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
4576       CmdArgs.push_back(Str);
4577     }
4578   }
4579
4580   Args.AddAllArgs(CmdArgs, options::OPT_L);
4581
4582   SanitizerArgs Sanitize(getToolChain().getDriver(), Args);
4583   // If we're building a dynamic lib with -fsanitize=address,
4584   // unresolved symbols may appear. Mark all
4585   // of them as dynamic_lookup. Linking executables is handled in
4586   // lib/Driver/ToolChains.cpp.
4587   if (Sanitize.needsAsanRt()) {
4588     if (Args.hasArg(options::OPT_dynamiclib) ||
4589         Args.hasArg(options::OPT_bundle)) {
4590       CmdArgs.push_back("-undefined");
4591       CmdArgs.push_back("dynamic_lookup");
4592     }
4593   }
4594
4595   if (Args.hasArg(options::OPT_fopenmp))
4596     // This is more complicated in gcc...
4597     CmdArgs.push_back("-lgomp");
4598
4599   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4600   
4601   if (isObjCRuntimeLinked(Args) &&
4602       !Args.hasArg(options::OPT_nostdlib) &&
4603       !Args.hasArg(options::OPT_nodefaultlibs)) {
4604     // Avoid linking compatibility stubs on i386 mac.
4605     if (!getDarwinToolChain().isTargetMacOS() ||
4606         getDarwinToolChain().getArch() != llvm::Triple::x86) {
4607       // If we don't have ARC or subscripting runtime support, link in the
4608       // runtime stubs.  We have to do this *before* adding any of the normal
4609       // linker inputs so that its initializer gets run first.
4610       ObjCRuntime runtime =
4611         getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
4612       // We use arclite library for both ARC and subscripting support.
4613       if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) ||
4614           !runtime.hasSubscripting())
4615         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
4616     }
4617     CmdArgs.push_back("-framework");
4618     CmdArgs.push_back("Foundation");
4619     // Link libobj.
4620     CmdArgs.push_back("-lobjc");
4621   }
4622
4623   if (LinkingOutput) {
4624     CmdArgs.push_back("-arch_multiple");
4625     CmdArgs.push_back("-final_output");
4626     CmdArgs.push_back(LinkingOutput);
4627   }
4628
4629   if (Args.hasArg(options::OPT_fnested_functions))
4630     CmdArgs.push_back("-allow_stack_execute");
4631
4632   if (!Args.hasArg(options::OPT_nostdlib) &&
4633       !Args.hasArg(options::OPT_nodefaultlibs)) {
4634     if (getToolChain().getDriver().CCCIsCXX)
4635       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4636
4637     // link_ssp spec is empty.
4638
4639     // Let the tool chain choose which runtime library to link.
4640     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
4641   }
4642
4643   if (!Args.hasArg(options::OPT_nostdlib) &&
4644       !Args.hasArg(options::OPT_nostartfiles)) {
4645     // endfile_spec is empty.
4646   }
4647
4648   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4649   Args.AddAllArgs(CmdArgs, options::OPT_F);
4650
4651   const char *Exec =
4652     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4653   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4654 }
4655
4656 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
4657                                 const InputInfo &Output,
4658                                 const InputInfoList &Inputs,
4659                                 const ArgList &Args,
4660                                 const char *LinkingOutput) const {
4661   ArgStringList CmdArgs;
4662
4663   CmdArgs.push_back("-create");
4664   assert(Output.isFilename() && "Unexpected lipo output.");
4665
4666   CmdArgs.push_back("-output");
4667   CmdArgs.push_back(Output.getFilename());
4668
4669   for (InputInfoList::const_iterator
4670          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4671     const InputInfo &II = *it;
4672     assert(II.isFilename() && "Unexpected lipo input.");
4673     CmdArgs.push_back(II.getFilename());
4674   }
4675   const char *Exec =
4676     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
4677   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4678 }
4679
4680 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
4681                                     const InputInfo &Output,
4682                                     const InputInfoList &Inputs,
4683                                     const ArgList &Args,
4684                                     const char *LinkingOutput) const {
4685   ArgStringList CmdArgs;
4686
4687   CmdArgs.push_back("-o");
4688   CmdArgs.push_back(Output.getFilename());
4689
4690   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4691   const InputInfo &Input = Inputs[0];
4692   assert(Input.isFilename() && "Unexpected dsymutil input.");
4693   CmdArgs.push_back(Input.getFilename());
4694
4695   const char *Exec =
4696     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
4697   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4698 }
4699
4700 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
4701                                        const InputInfo &Output,
4702                                        const InputInfoList &Inputs,
4703                                        const ArgList &Args,
4704                                        const char *LinkingOutput) const {
4705   ArgStringList CmdArgs;
4706   CmdArgs.push_back("--verify");
4707   CmdArgs.push_back("--debug-info");
4708   CmdArgs.push_back("--eh-frame");
4709   CmdArgs.push_back("--quiet");
4710
4711   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4712   const InputInfo &Input = Inputs[0];
4713   assert(Input.isFilename() && "Unexpected verify input");
4714
4715   // Grabbing the output of the earlier dsymutil run.
4716   CmdArgs.push_back(Input.getFilename());
4717
4718   const char *Exec =
4719     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
4720   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4721 }
4722
4723 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4724                                       const InputInfo &Output,
4725                                       const InputInfoList &Inputs,
4726                                       const ArgList &Args,
4727                                       const char *LinkingOutput) const {
4728   ArgStringList CmdArgs;
4729
4730   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4731                        options::OPT_Xassembler);
4732
4733   CmdArgs.push_back("-o");
4734   CmdArgs.push_back(Output.getFilename());
4735
4736   for (InputInfoList::const_iterator
4737          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4738     const InputInfo &II = *it;
4739     CmdArgs.push_back(II.getFilename());
4740   }
4741
4742   const char *Exec =
4743     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4744   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4745 }
4746
4747
4748 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
4749                                   const InputInfo &Output,
4750                                   const InputInfoList &Inputs,
4751                                   const ArgList &Args,
4752                                   const char *LinkingOutput) const {
4753   // FIXME: Find a real GCC, don't hard-code versions here
4754   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
4755   const llvm::Triple &T = getToolChain().getTriple();
4756   std::string LibPath = "/usr/lib/";
4757   llvm::Triple::ArchType Arch = T.getArch();
4758   switch (Arch) {
4759         case llvm::Triple::x86:
4760           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4761               T.getOSName()).str() + "/4.5.2/";
4762           break;
4763         case llvm::Triple::x86_64:
4764           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4765               T.getOSName()).str();
4766           GCCLibPath += "/4.5.2/amd64/";
4767           LibPath += "amd64/";
4768           break;
4769         default:
4770           assert(0 && "Unsupported architecture");
4771   }
4772
4773   ArgStringList CmdArgs;
4774
4775   // Demangle C++ names in errors
4776   CmdArgs.push_back("-C");
4777
4778   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4779       (!Args.hasArg(options::OPT_shared))) {
4780     CmdArgs.push_back("-e");
4781     CmdArgs.push_back("_start");
4782   }
4783
4784   if (Args.hasArg(options::OPT_static)) {
4785     CmdArgs.push_back("-Bstatic");
4786     CmdArgs.push_back("-dn");
4787   } else {
4788     CmdArgs.push_back("-Bdynamic");
4789     if (Args.hasArg(options::OPT_shared)) {
4790       CmdArgs.push_back("-shared");
4791     } else {
4792       CmdArgs.push_back("--dynamic-linker");
4793       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
4794     }
4795   }
4796
4797   if (Output.isFilename()) {
4798     CmdArgs.push_back("-o");
4799     CmdArgs.push_back(Output.getFilename());
4800   } else {
4801     assert(Output.isNothing() && "Invalid output.");
4802   }
4803
4804   if (!Args.hasArg(options::OPT_nostdlib) &&
4805       !Args.hasArg(options::OPT_nostartfiles)) {
4806     if (!Args.hasArg(options::OPT_shared)) {
4807       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
4808       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4809       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4810       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4811     } else {
4812       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4813       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4814       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4815     }
4816     if (getToolChain().getDriver().CCCIsCXX)
4817       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
4818   }
4819
4820   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
4821
4822   Args.AddAllArgs(CmdArgs, options::OPT_L);
4823   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4824   Args.AddAllArgs(CmdArgs, options::OPT_e);
4825   Args.AddAllArgs(CmdArgs, options::OPT_r);
4826
4827   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4828
4829   if (!Args.hasArg(options::OPT_nostdlib) &&
4830       !Args.hasArg(options::OPT_nodefaultlibs)) {
4831     if (getToolChain().getDriver().CCCIsCXX)
4832       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4833     CmdArgs.push_back("-lgcc_s");
4834     if (!Args.hasArg(options::OPT_shared)) {
4835       CmdArgs.push_back("-lgcc");
4836       CmdArgs.push_back("-lc");
4837       CmdArgs.push_back("-lm");
4838     }
4839   }
4840
4841   if (!Args.hasArg(options::OPT_nostdlib) &&
4842       !Args.hasArg(options::OPT_nostartfiles)) {
4843     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
4844   }
4845   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
4846
4847   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4848
4849   const char *Exec =
4850     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4851   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4852 }
4853
4854 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4855                                       const InputInfo &Output,
4856                                       const InputInfoList &Inputs,
4857                                       const ArgList &Args,
4858                                       const char *LinkingOutput) const {
4859   ArgStringList CmdArgs;
4860
4861   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4862                        options::OPT_Xassembler);
4863
4864   CmdArgs.push_back("-o");
4865   CmdArgs.push_back(Output.getFilename());
4866
4867   for (InputInfoList::const_iterator
4868          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4869     const InputInfo &II = *it;
4870     CmdArgs.push_back(II.getFilename());
4871   }
4872
4873   const char *Exec =
4874     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
4875   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4876 }
4877
4878 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
4879                                   const InputInfo &Output,
4880                                   const InputInfoList &Inputs,
4881                                   const ArgList &Args,
4882                                   const char *LinkingOutput) const {
4883   ArgStringList CmdArgs;
4884
4885   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4886       (!Args.hasArg(options::OPT_shared))) {
4887     CmdArgs.push_back("-e");
4888     CmdArgs.push_back("_start");
4889   }
4890
4891   if (Args.hasArg(options::OPT_static)) {
4892     CmdArgs.push_back("-Bstatic");
4893     CmdArgs.push_back("-dn");
4894   } else {
4895 //    CmdArgs.push_back("--eh-frame-hdr");
4896     CmdArgs.push_back("-Bdynamic");
4897     if (Args.hasArg(options::OPT_shared)) {
4898       CmdArgs.push_back("-shared");
4899     } else {
4900       CmdArgs.push_back("--dynamic-linker");
4901       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
4902     }
4903   }
4904
4905   if (Output.isFilename()) {
4906     CmdArgs.push_back("-o");
4907     CmdArgs.push_back(Output.getFilename());
4908   } else {
4909     assert(Output.isNothing() && "Invalid output.");
4910   }
4911
4912   if (!Args.hasArg(options::OPT_nostdlib) &&
4913       !Args.hasArg(options::OPT_nostartfiles)) {
4914     if (!Args.hasArg(options::OPT_shared)) {
4915       CmdArgs.push_back(Args.MakeArgString(
4916                                 getToolChain().GetFilePath("crt1.o")));
4917       CmdArgs.push_back(Args.MakeArgString(
4918                                 getToolChain().GetFilePath("crti.o")));
4919       CmdArgs.push_back(Args.MakeArgString(
4920                                 getToolChain().GetFilePath("crtbegin.o")));
4921     } else {
4922       CmdArgs.push_back(Args.MakeArgString(
4923                                 getToolChain().GetFilePath("crti.o")));
4924     }
4925     CmdArgs.push_back(Args.MakeArgString(
4926                                 getToolChain().GetFilePath("crtn.o")));
4927   }
4928
4929   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
4930                                        + getToolChain().getTripleString()
4931                                        + "/4.2.4"));
4932
4933   Args.AddAllArgs(CmdArgs, options::OPT_L);
4934   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4935   Args.AddAllArgs(CmdArgs, options::OPT_e);
4936
4937   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4938
4939   if (!Args.hasArg(options::OPT_nostdlib) &&
4940       !Args.hasArg(options::OPT_nodefaultlibs)) {
4941     // FIXME: For some reason GCC passes -lgcc before adding
4942     // the default system libraries. Just mimic this for now.
4943     CmdArgs.push_back("-lgcc");
4944
4945     if (Args.hasArg(options::OPT_pthread))
4946       CmdArgs.push_back("-pthread");
4947     if (!Args.hasArg(options::OPT_shared))
4948       CmdArgs.push_back("-lc");
4949     CmdArgs.push_back("-lgcc");
4950   }
4951
4952   if (!Args.hasArg(options::OPT_nostdlib) &&
4953       !Args.hasArg(options::OPT_nostartfiles)) {
4954     if (!Args.hasArg(options::OPT_shared))
4955       CmdArgs.push_back(Args.MakeArgString(
4956                                 getToolChain().GetFilePath("crtend.o")));
4957   }
4958
4959   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4960
4961   const char *Exec =
4962     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4963   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4964 }
4965
4966 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4967                                      const InputInfo &Output,
4968                                      const InputInfoList &Inputs,
4969                                      const ArgList &Args,
4970                                      const char *LinkingOutput) const {
4971   ArgStringList CmdArgs;
4972
4973   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4974                        options::OPT_Xassembler);
4975
4976   CmdArgs.push_back("-o");
4977   CmdArgs.push_back(Output.getFilename());
4978
4979   for (InputInfoList::const_iterator
4980          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4981     const InputInfo &II = *it;
4982     CmdArgs.push_back(II.getFilename());
4983   }
4984
4985   const char *Exec =
4986     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4987   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4988 }
4989
4990 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
4991                                  const InputInfo &Output,
4992                                  const InputInfoList &Inputs,
4993                                  const ArgList &Args,
4994                                  const char *LinkingOutput) const {
4995   const Driver &D = getToolChain().getDriver();
4996   ArgStringList CmdArgs;
4997
4998   // Silence warning for "clang -g foo.o -o foo"
4999   Args.ClaimAllArgs(options::OPT_g_Group);
5000   // and "clang -emit-llvm foo.o -o foo"
5001   Args.ClaimAllArgs(options::OPT_emit_llvm);
5002   // and for "clang -w foo.o -o foo". Other warning options are already
5003   // handled somewhere else.
5004   Args.ClaimAllArgs(options::OPT_w);
5005
5006   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5007       (!Args.hasArg(options::OPT_shared))) {
5008     CmdArgs.push_back("-e");
5009     CmdArgs.push_back("__start");
5010   }
5011
5012   if (Args.hasArg(options::OPT_static)) {
5013     CmdArgs.push_back("-Bstatic");
5014   } else {
5015     if (Args.hasArg(options::OPT_rdynamic))
5016       CmdArgs.push_back("-export-dynamic");
5017     CmdArgs.push_back("--eh-frame-hdr");
5018     CmdArgs.push_back("-Bdynamic");
5019     if (Args.hasArg(options::OPT_shared)) {
5020       CmdArgs.push_back("-shared");
5021     } else {
5022       CmdArgs.push_back("-dynamic-linker");
5023       CmdArgs.push_back("/usr/libexec/ld.so");
5024     }
5025   }
5026
5027   if (Output.isFilename()) {
5028     CmdArgs.push_back("-o");
5029     CmdArgs.push_back(Output.getFilename());
5030   } else {
5031     assert(Output.isNothing() && "Invalid output.");
5032   }
5033
5034   if (!Args.hasArg(options::OPT_nostdlib) &&
5035       !Args.hasArg(options::OPT_nostartfiles)) {
5036     if (!Args.hasArg(options::OPT_shared)) {
5037       if (Args.hasArg(options::OPT_pg))  
5038         CmdArgs.push_back(Args.MakeArgString(
5039                                 getToolChain().GetFilePath("gcrt0.o")));
5040       else
5041         CmdArgs.push_back(Args.MakeArgString(
5042                                 getToolChain().GetFilePath("crt0.o")));
5043       CmdArgs.push_back(Args.MakeArgString(
5044                               getToolChain().GetFilePath("crtbegin.o")));
5045     } else {
5046       CmdArgs.push_back(Args.MakeArgString(
5047                               getToolChain().GetFilePath("crtbeginS.o")));
5048     }
5049   }
5050
5051   std::string Triple = getToolChain().getTripleString();
5052   if (Triple.substr(0, 6) == "x86_64")
5053     Triple.replace(0, 6, "amd64");
5054   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
5055                                        "/4.2.1"));
5056
5057   Args.AddAllArgs(CmdArgs, options::OPT_L);
5058   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5059   Args.AddAllArgs(CmdArgs, options::OPT_e);
5060   Args.AddAllArgs(CmdArgs, options::OPT_s);
5061   Args.AddAllArgs(CmdArgs, options::OPT_t);
5062   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5063   Args.AddAllArgs(CmdArgs, options::OPT_r);
5064
5065   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5066
5067   if (!Args.hasArg(options::OPT_nostdlib) &&
5068       !Args.hasArg(options::OPT_nodefaultlibs)) {
5069     if (D.CCCIsCXX) {
5070       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5071       if (Args.hasArg(options::OPT_pg)) 
5072         CmdArgs.push_back("-lm_p");
5073       else
5074         CmdArgs.push_back("-lm");
5075     }
5076
5077     // FIXME: For some reason GCC passes -lgcc before adding
5078     // the default system libraries. Just mimic this for now.
5079     CmdArgs.push_back("-lgcc");
5080
5081     if (Args.hasArg(options::OPT_pthread)) {
5082       if (!Args.hasArg(options::OPT_shared) &&
5083           Args.hasArg(options::OPT_pg))
5084          CmdArgs.push_back("-lpthread_p");
5085       else
5086          CmdArgs.push_back("-lpthread");
5087     }
5088
5089     if (!Args.hasArg(options::OPT_shared)) {
5090       if (Args.hasArg(options::OPT_pg))
5091          CmdArgs.push_back("-lc_p");
5092       else
5093          CmdArgs.push_back("-lc");
5094     }
5095
5096     CmdArgs.push_back("-lgcc");
5097   }
5098
5099   if (!Args.hasArg(options::OPT_nostdlib) &&
5100       !Args.hasArg(options::OPT_nostartfiles)) {
5101     if (!Args.hasArg(options::OPT_shared))
5102       CmdArgs.push_back(Args.MakeArgString(
5103                               getToolChain().GetFilePath("crtend.o")));
5104     else
5105       CmdArgs.push_back(Args.MakeArgString(
5106                               getToolChain().GetFilePath("crtendS.o")));
5107   }
5108
5109   const char *Exec =
5110     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5111   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5112 }
5113
5114 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5115                                     const InputInfo &Output,
5116                                     const InputInfoList &Inputs,
5117                                     const ArgList &Args,
5118                                     const char *LinkingOutput) const {
5119   ArgStringList CmdArgs;
5120
5121   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5122                        options::OPT_Xassembler);
5123
5124   CmdArgs.push_back("-o");
5125   CmdArgs.push_back(Output.getFilename());
5126
5127   for (InputInfoList::const_iterator
5128          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5129     const InputInfo &II = *it;
5130     CmdArgs.push_back(II.getFilename());
5131   }
5132
5133   const char *Exec =
5134     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5135   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5136 }
5137
5138 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
5139                                 const InputInfo &Output,
5140                                 const InputInfoList &Inputs,
5141                                 const ArgList &Args,
5142                                 const char *LinkingOutput) const {
5143   const Driver &D = getToolChain().getDriver();
5144   ArgStringList CmdArgs;
5145
5146   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5147       (!Args.hasArg(options::OPT_shared))) {
5148     CmdArgs.push_back("-e");
5149     CmdArgs.push_back("__start");
5150   }
5151
5152   if (Args.hasArg(options::OPT_static)) {
5153     CmdArgs.push_back("-Bstatic");
5154   } else {
5155     if (Args.hasArg(options::OPT_rdynamic))
5156       CmdArgs.push_back("-export-dynamic");
5157     CmdArgs.push_back("--eh-frame-hdr");
5158     CmdArgs.push_back("-Bdynamic");
5159     if (Args.hasArg(options::OPT_shared)) {
5160       CmdArgs.push_back("-shared");
5161     } else {
5162       CmdArgs.push_back("-dynamic-linker");
5163       CmdArgs.push_back("/usr/libexec/ld.so");
5164     }
5165   }
5166
5167   if (Output.isFilename()) {
5168     CmdArgs.push_back("-o");
5169     CmdArgs.push_back(Output.getFilename());
5170   } else {
5171     assert(Output.isNothing() && "Invalid output.");
5172   }
5173
5174   if (!Args.hasArg(options::OPT_nostdlib) &&
5175       !Args.hasArg(options::OPT_nostartfiles)) {
5176     if (!Args.hasArg(options::OPT_shared)) {
5177       if (Args.hasArg(options::OPT_pg))
5178         CmdArgs.push_back(Args.MakeArgString(
5179                                 getToolChain().GetFilePath("gcrt0.o")));
5180       else
5181         CmdArgs.push_back(Args.MakeArgString(
5182                                 getToolChain().GetFilePath("crt0.o")));
5183       CmdArgs.push_back(Args.MakeArgString(
5184                               getToolChain().GetFilePath("crtbegin.o")));
5185     } else {
5186       CmdArgs.push_back(Args.MakeArgString(
5187                               getToolChain().GetFilePath("crtbeginS.o")));
5188     }
5189   }
5190
5191   Args.AddAllArgs(CmdArgs, options::OPT_L);
5192   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5193   Args.AddAllArgs(CmdArgs, options::OPT_e);
5194
5195   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5196
5197   if (!Args.hasArg(options::OPT_nostdlib) &&
5198       !Args.hasArg(options::OPT_nodefaultlibs)) {
5199     if (D.CCCIsCXX) {
5200       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5201       if (Args.hasArg(options::OPT_pg))
5202         CmdArgs.push_back("-lm_p");
5203       else
5204         CmdArgs.push_back("-lm");
5205     }
5206
5207     if (Args.hasArg(options::OPT_pthread)) {
5208       if (!Args.hasArg(options::OPT_shared) &&
5209           Args.hasArg(options::OPT_pg))
5210         CmdArgs.push_back("-lpthread_p");
5211       else
5212         CmdArgs.push_back("-lpthread");
5213     }
5214
5215     if (!Args.hasArg(options::OPT_shared)) {
5216       if (Args.hasArg(options::OPT_pg))
5217         CmdArgs.push_back("-lc_p");
5218       else
5219         CmdArgs.push_back("-lc");
5220     }
5221
5222     std::string myarch = "-lclang_rt.";
5223     const llvm::Triple &T = getToolChain().getTriple();
5224     llvm::Triple::ArchType Arch = T.getArch();
5225     switch (Arch) {
5226           case llvm::Triple::arm:
5227             myarch += ("arm");
5228             break;
5229           case llvm::Triple::x86:
5230             myarch += ("i386");
5231             break;
5232           case llvm::Triple::x86_64:
5233             myarch += ("amd64");
5234             break;
5235           default:
5236             assert(0 && "Unsupported architecture");
5237      }
5238      CmdArgs.push_back(Args.MakeArgString(myarch));
5239   }
5240
5241   if (!Args.hasArg(options::OPT_nostdlib) &&
5242       !Args.hasArg(options::OPT_nostartfiles)) {
5243     if (!Args.hasArg(options::OPT_shared))
5244       CmdArgs.push_back(Args.MakeArgString(
5245                               getToolChain().GetFilePath("crtend.o")));
5246     else
5247       CmdArgs.push_back(Args.MakeArgString(
5248                               getToolChain().GetFilePath("crtendS.o")));
5249   }
5250
5251   const char *Exec =
5252     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5253   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5254 }
5255
5256 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5257                                      const InputInfo &Output,
5258                                      const InputInfoList &Inputs,
5259                                      const ArgList &Args,
5260                                      const char *LinkingOutput) const {
5261   ArgStringList CmdArgs;
5262
5263   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5264   // instruct as in the base system to assemble 32-bit code.
5265   if (getToolChain().getArch() == llvm::Triple::x86)
5266     CmdArgs.push_back("--32");
5267   else if (getToolChain().getArch() == llvm::Triple::ppc)
5268     CmdArgs.push_back("-a32");
5269   else if (getToolChain().getArch() == llvm::Triple::mips ||
5270            getToolChain().getArch() == llvm::Triple::mipsel ||
5271            getToolChain().getArch() == llvm::Triple::mips64 ||
5272            getToolChain().getArch() == llvm::Triple::mips64el) {
5273     StringRef CPUName;
5274     StringRef ABIName;
5275     getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5276
5277     CmdArgs.push_back("-march");
5278     CmdArgs.push_back(CPUName.data());
5279
5280     CmdArgs.push_back("-mabi");
5281     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5282
5283     if (getToolChain().getArch() == llvm::Triple::mips ||
5284         getToolChain().getArch() == llvm::Triple::mips64)
5285       CmdArgs.push_back("-EB");
5286     else
5287       CmdArgs.push_back("-EL");
5288
5289     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5290                                       options::OPT_fpic, options::OPT_fno_pic,
5291                                       options::OPT_fPIE, options::OPT_fno_PIE,
5292                                       options::OPT_fpie, options::OPT_fno_pie);
5293     if (LastPICArg &&
5294         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5295          LastPICArg->getOption().matches(options::OPT_fpic) ||
5296          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5297          LastPICArg->getOption().matches(options::OPT_fpie))) {
5298       CmdArgs.push_back("-KPIC");
5299     }
5300   } else if (getToolChain().getArch() == llvm::Triple::arm ||
5301              getToolChain().getArch() == llvm::Triple::thumb) {
5302     CmdArgs.push_back("-mfpu=softvfp");
5303     switch(getToolChain().getTriple().getEnvironment()) {
5304     case llvm::Triple::GNUEABI:
5305     case llvm::Triple::EABI:
5306       CmdArgs.push_back("-meabi=5");
5307       break;
5308
5309     default:
5310       CmdArgs.push_back("-matpcs");
5311     }
5312   }
5313
5314   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5315                        options::OPT_Xassembler);
5316
5317   CmdArgs.push_back("-o");
5318   CmdArgs.push_back(Output.getFilename());
5319
5320   for (InputInfoList::const_iterator
5321          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5322     const InputInfo &II = *it;
5323     CmdArgs.push_back(II.getFilename());
5324   }
5325
5326   const char *Exec =
5327     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5328   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5329 }
5330
5331 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5332                                  const InputInfo &Output,
5333                                  const InputInfoList &Inputs,
5334                                  const ArgList &Args,
5335                                  const char *LinkingOutput) const {
5336   const toolchains::FreeBSD& ToolChain = 
5337     static_cast<const toolchains::FreeBSD&>(getToolChain());
5338   const Driver &D = ToolChain.getDriver();
5339   ArgStringList CmdArgs;
5340
5341   // Silence warning for "clang -g foo.o -o foo"
5342   Args.ClaimAllArgs(options::OPT_g_Group);
5343   // and "clang -emit-llvm foo.o -o foo"
5344   Args.ClaimAllArgs(options::OPT_emit_llvm);
5345   // and for "clang -w foo.o -o foo". Other warning options are already
5346   // handled somewhere else.
5347   Args.ClaimAllArgs(options::OPT_w);
5348
5349   if (!D.SysRoot.empty())
5350     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5351
5352   if (Args.hasArg(options::OPT_pie))
5353     CmdArgs.push_back("-pie");
5354
5355   if (Args.hasArg(options::OPT_static)) {
5356     CmdArgs.push_back("-Bstatic");
5357   } else {
5358     if (Args.hasArg(options::OPT_rdynamic))
5359       CmdArgs.push_back("-export-dynamic");
5360     CmdArgs.push_back("--eh-frame-hdr");
5361     if (Args.hasArg(options::OPT_shared)) {
5362       CmdArgs.push_back("-Bshareable");
5363     } else {
5364       CmdArgs.push_back("-dynamic-linker");
5365       CmdArgs.push_back("/libexec/ld-elf.so.1");
5366     }
5367     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
5368       llvm::Triple::ArchType Arch = ToolChain.getArch();
5369       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5370           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5371         CmdArgs.push_back("--hash-style=both");
5372       }
5373     }
5374     CmdArgs.push_back("--enable-new-dtags");
5375   }
5376
5377   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5378   // instruct ld in the base system to link 32-bit code.
5379   if (ToolChain.getArch() == llvm::Triple::x86) {
5380     CmdArgs.push_back("-m");
5381     CmdArgs.push_back("elf_i386_fbsd");
5382   }
5383
5384   if (ToolChain.getArch() == llvm::Triple::ppc) {
5385     CmdArgs.push_back("-m");
5386     CmdArgs.push_back("elf32ppc_fbsd");
5387   }
5388
5389   if (Output.isFilename()) {
5390     CmdArgs.push_back("-o");
5391     CmdArgs.push_back(Output.getFilename());
5392   } else {
5393     assert(Output.isNothing() && "Invalid output.");
5394   }
5395
5396   if (!Args.hasArg(options::OPT_nostdlib) &&
5397       !Args.hasArg(options::OPT_nostartfiles)) {
5398     const char *crt1 = NULL;
5399     if (!Args.hasArg(options::OPT_shared)) {
5400       if (Args.hasArg(options::OPT_pg))
5401         crt1 = "gcrt1.o";
5402       else if (Args.hasArg(options::OPT_pie))
5403         crt1 = "Scrt1.o";
5404       else
5405         crt1 = "crt1.o";
5406     }
5407     if (crt1)
5408       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5409
5410     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5411
5412     const char *crtbegin = NULL;
5413     if (Args.hasArg(options::OPT_static))
5414       crtbegin = "crtbeginT.o";
5415     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5416       crtbegin = "crtbeginS.o";
5417     else
5418       crtbegin = "crtbegin.o";
5419
5420     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5421   }
5422
5423   Args.AddAllArgs(CmdArgs, options::OPT_L);
5424   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5425   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5426        i != e; ++i)
5427     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5428   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5429   Args.AddAllArgs(CmdArgs, options::OPT_e);
5430   Args.AddAllArgs(CmdArgs, options::OPT_s);
5431   Args.AddAllArgs(CmdArgs, options::OPT_t);
5432   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5433   Args.AddAllArgs(CmdArgs, options::OPT_r);
5434
5435   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5436
5437   if (!Args.hasArg(options::OPT_nostdlib) &&
5438       !Args.hasArg(options::OPT_nodefaultlibs)) {
5439     if (D.CCCIsCXX) {
5440       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5441       if (Args.hasArg(options::OPT_pg))
5442         CmdArgs.push_back("-lm_p");
5443       else
5444         CmdArgs.push_back("-lm");
5445     }
5446     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5447     // the default system libraries. Just mimic this for now.
5448     if (Args.hasArg(options::OPT_pg))
5449       CmdArgs.push_back("-lgcc_p");
5450     else
5451       CmdArgs.push_back("-lgcc");
5452     if (Args.hasArg(options::OPT_static)) {
5453       CmdArgs.push_back("-lgcc_eh");
5454     } else if (Args.hasArg(options::OPT_pg)) {
5455       CmdArgs.push_back("-lgcc_eh_p");
5456     } else {
5457       CmdArgs.push_back("--as-needed");
5458       CmdArgs.push_back("-lgcc_s");
5459       CmdArgs.push_back("--no-as-needed");
5460     }
5461
5462     if (Args.hasArg(options::OPT_pthread)) {
5463       if (Args.hasArg(options::OPT_pg))
5464         CmdArgs.push_back("-lpthread_p");
5465       else
5466         CmdArgs.push_back("-lpthread");
5467     }
5468
5469     if (Args.hasArg(options::OPT_pg)) {
5470       if (Args.hasArg(options::OPT_shared))
5471         CmdArgs.push_back("-lc");
5472       else
5473         CmdArgs.push_back("-lc_p");
5474       CmdArgs.push_back("-lgcc_p");
5475     } else {
5476       CmdArgs.push_back("-lc");
5477       CmdArgs.push_back("-lgcc");
5478     }
5479
5480     if (Args.hasArg(options::OPT_static)) {
5481       CmdArgs.push_back("-lgcc_eh");
5482     } else if (Args.hasArg(options::OPT_pg)) {
5483       CmdArgs.push_back("-lgcc_eh_p");
5484     } else {
5485       CmdArgs.push_back("--as-needed");
5486       CmdArgs.push_back("-lgcc_s");
5487       CmdArgs.push_back("--no-as-needed");
5488     }
5489   }
5490
5491   if (!Args.hasArg(options::OPT_nostdlib) &&
5492       !Args.hasArg(options::OPT_nostartfiles)) {
5493     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5494       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
5495     else
5496       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
5497     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
5498   }
5499
5500   addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple());
5501
5502   const char *Exec =
5503     Args.MakeArgString(ToolChain.GetProgramPath("ld"));
5504   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5505 }
5506
5507 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5508                                      const InputInfo &Output,
5509                                      const InputInfoList &Inputs,
5510                                      const ArgList &Args,
5511                                      const char *LinkingOutput) const {
5512   ArgStringList CmdArgs;
5513
5514   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5515   // instruct as in the base system to assemble 32-bit code.
5516   if (getToolChain().getArch() == llvm::Triple::x86)
5517     CmdArgs.push_back("--32");
5518
5519   // Set byte order explicitly
5520   if (getToolChain().getArch() == llvm::Triple::mips)
5521     CmdArgs.push_back("-EB");
5522   else if (getToolChain().getArch() == llvm::Triple::mipsel)
5523     CmdArgs.push_back("-EL");
5524
5525   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5526                        options::OPT_Xassembler);
5527
5528   CmdArgs.push_back("-o");
5529   CmdArgs.push_back(Output.getFilename());
5530
5531   for (InputInfoList::const_iterator
5532          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5533     const InputInfo &II = *it;
5534     CmdArgs.push_back(II.getFilename());
5535   }
5536
5537   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
5538   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5539 }
5540
5541 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5542                                  const InputInfo &Output,
5543                                  const InputInfoList &Inputs,
5544                                  const ArgList &Args,
5545                                  const char *LinkingOutput) const {
5546   const Driver &D = getToolChain().getDriver();
5547   ArgStringList CmdArgs;
5548
5549   if (!D.SysRoot.empty())
5550     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5551
5552   if (Args.hasArg(options::OPT_static)) {
5553     CmdArgs.push_back("-Bstatic");
5554   } else {
5555     if (Args.hasArg(options::OPT_rdynamic))
5556       CmdArgs.push_back("-export-dynamic");
5557     CmdArgs.push_back("--eh-frame-hdr");
5558     if (Args.hasArg(options::OPT_shared)) {
5559       CmdArgs.push_back("-Bshareable");
5560     } else {
5561       CmdArgs.push_back("-dynamic-linker");
5562       CmdArgs.push_back("/libexec/ld.elf_so");
5563     }
5564   }
5565
5566   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5567   // instruct ld in the base system to link 32-bit code.
5568   if (getToolChain().getArch() == llvm::Triple::x86) {
5569     CmdArgs.push_back("-m");
5570     CmdArgs.push_back("elf_i386");
5571   }
5572
5573   if (Output.isFilename()) {
5574     CmdArgs.push_back("-o");
5575     CmdArgs.push_back(Output.getFilename());
5576   } else {
5577     assert(Output.isNothing() && "Invalid output.");
5578   }
5579
5580   if (!Args.hasArg(options::OPT_nostdlib) &&
5581       !Args.hasArg(options::OPT_nostartfiles)) {
5582     if (!Args.hasArg(options::OPT_shared)) {
5583       CmdArgs.push_back(Args.MakeArgString(
5584                               getToolChain().GetFilePath("crt0.o")));
5585       CmdArgs.push_back(Args.MakeArgString(
5586                               getToolChain().GetFilePath("crti.o")));
5587       CmdArgs.push_back(Args.MakeArgString(
5588                               getToolChain().GetFilePath("crtbegin.o")));
5589     } else {
5590       CmdArgs.push_back(Args.MakeArgString(
5591                               getToolChain().GetFilePath("crti.o")));
5592       CmdArgs.push_back(Args.MakeArgString(
5593                               getToolChain().GetFilePath("crtbeginS.o")));
5594     }
5595   }
5596
5597   Args.AddAllArgs(CmdArgs, options::OPT_L);
5598   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5599   Args.AddAllArgs(CmdArgs, options::OPT_e);
5600   Args.AddAllArgs(CmdArgs, options::OPT_s);
5601   Args.AddAllArgs(CmdArgs, options::OPT_t);
5602   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5603   Args.AddAllArgs(CmdArgs, options::OPT_r);
5604
5605   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5606
5607   if (!Args.hasArg(options::OPT_nostdlib) &&
5608       !Args.hasArg(options::OPT_nodefaultlibs)) {
5609     if (D.CCCIsCXX) {
5610       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5611       CmdArgs.push_back("-lm");
5612     }
5613     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5614     // the default system libraries. Just mimic this for now.
5615     if (Args.hasArg(options::OPT_static)) {
5616       CmdArgs.push_back("-lgcc_eh");
5617     } else {
5618       CmdArgs.push_back("--as-needed");
5619       CmdArgs.push_back("-lgcc_s");
5620       CmdArgs.push_back("--no-as-needed");
5621     }
5622     CmdArgs.push_back("-lgcc");
5623
5624     if (Args.hasArg(options::OPT_pthread))
5625       CmdArgs.push_back("-lpthread");
5626     CmdArgs.push_back("-lc");
5627
5628     CmdArgs.push_back("-lgcc");
5629     if (Args.hasArg(options::OPT_static)) {
5630       CmdArgs.push_back("-lgcc_eh");
5631     } else {
5632       CmdArgs.push_back("--as-needed");
5633       CmdArgs.push_back("-lgcc_s");
5634       CmdArgs.push_back("--no-as-needed");
5635     }
5636   }
5637
5638   if (!Args.hasArg(options::OPT_nostdlib) &&
5639       !Args.hasArg(options::OPT_nostartfiles)) {
5640     if (!Args.hasArg(options::OPT_shared))
5641       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5642                                                                   "crtend.o")));
5643     else
5644       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5645                                                                  "crtendS.o")));
5646     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5647                                                                     "crtn.o")));
5648   }
5649
5650   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5651
5652   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5653   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5654 }
5655
5656 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5657                                       const InputInfo &Output,
5658                                       const InputInfoList &Inputs,
5659                                       const ArgList &Args,
5660                                       const char *LinkingOutput) const {
5661   ArgStringList CmdArgs;
5662
5663   // Add --32/--64 to make sure we get the format we want.
5664   // This is incomplete
5665   if (getToolChain().getArch() == llvm::Triple::x86) {
5666     CmdArgs.push_back("--32");
5667   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
5668     CmdArgs.push_back("--64");
5669   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
5670     CmdArgs.push_back("-a32");
5671     CmdArgs.push_back("-mppc");
5672     CmdArgs.push_back("-many");
5673   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
5674     CmdArgs.push_back("-a64");
5675     CmdArgs.push_back("-mppc64");
5676     CmdArgs.push_back("-many");
5677   } else if (getToolChain().getArch() == llvm::Triple::arm) {
5678     StringRef MArch = getToolChain().getArchName();
5679     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
5680       CmdArgs.push_back("-mfpu=neon");
5681
5682     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
5683                                            getToolChain().getTriple());
5684     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
5685
5686     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
5687     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
5688     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
5689   } else if (getToolChain().getArch() == llvm::Triple::mips ||
5690              getToolChain().getArch() == llvm::Triple::mipsel ||
5691              getToolChain().getArch() == llvm::Triple::mips64 ||
5692              getToolChain().getArch() == llvm::Triple::mips64el) {
5693     StringRef CPUName;
5694     StringRef ABIName;
5695     getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5696
5697     CmdArgs.push_back("-march");
5698     CmdArgs.push_back(CPUName.data());
5699
5700     CmdArgs.push_back("-mabi");
5701     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5702
5703     if (getToolChain().getArch() == llvm::Triple::mips ||
5704         getToolChain().getArch() == llvm::Triple::mips64)
5705       CmdArgs.push_back("-EB");
5706     else
5707       CmdArgs.push_back("-EL");
5708
5709     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5710                                       options::OPT_fpic, options::OPT_fno_pic,
5711                                       options::OPT_fPIE, options::OPT_fno_PIE,
5712                                       options::OPT_fpie, options::OPT_fno_pie);
5713     if (LastPICArg &&
5714         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5715          LastPICArg->getOption().matches(options::OPT_fpic) ||
5716          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5717          LastPICArg->getOption().matches(options::OPT_fpie))) {
5718       CmdArgs.push_back("-KPIC");
5719     }
5720   }
5721
5722   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5723                        options::OPT_Xassembler);
5724
5725   CmdArgs.push_back("-o");
5726   CmdArgs.push_back(Output.getFilename());
5727
5728   for (InputInfoList::const_iterator
5729          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5730     const InputInfo &II = *it;
5731     CmdArgs.push_back(II.getFilename());
5732   }
5733
5734   const char *Exec =
5735     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5736   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5737 }
5738
5739 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
5740                       ArgStringList &CmdArgs, const ArgList &Args) {
5741   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
5742   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
5743                       Args.hasArg(options::OPT_static);
5744   if (!D.CCCIsCXX)
5745     CmdArgs.push_back("-lgcc");
5746
5747   if (StaticLibgcc || isAndroid) {
5748     if (D.CCCIsCXX)
5749       CmdArgs.push_back("-lgcc");
5750   } else {
5751     if (!D.CCCIsCXX)
5752       CmdArgs.push_back("--as-needed");
5753     CmdArgs.push_back("-lgcc_s");
5754     if (!D.CCCIsCXX)
5755       CmdArgs.push_back("--no-as-needed");
5756   }
5757
5758   if (StaticLibgcc && !isAndroid)
5759     CmdArgs.push_back("-lgcc_eh");
5760   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
5761     CmdArgs.push_back("-lgcc");
5762
5763   // According to Android ABI, we have to link with libdl if we are
5764   // linking with non-static libgcc.
5765   //
5766   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
5767   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
5768   if (isAndroid && !StaticLibgcc)
5769     CmdArgs.push_back("-ldl");
5770 }
5771
5772 static bool hasMipsN32ABIArg(const ArgList &Args) {
5773   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5774   return A && (A->getValue() == StringRef("n32"));
5775 }
5776
5777 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
5778                                   const InputInfo &Output,
5779                                   const InputInfoList &Inputs,
5780                                   const ArgList &Args,
5781                                   const char *LinkingOutput) const {
5782   const toolchains::Linux& ToolChain =
5783     static_cast<const toolchains::Linux&>(getToolChain());
5784   const Driver &D = ToolChain.getDriver();
5785   const bool isAndroid =
5786     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
5787
5788   ArgStringList CmdArgs;
5789
5790   // Silence warning for "clang -g foo.o -o foo"
5791   Args.ClaimAllArgs(options::OPT_g_Group);
5792   // and "clang -emit-llvm foo.o -o foo"
5793   Args.ClaimAllArgs(options::OPT_emit_llvm);
5794   // and for "clang -w foo.o -o foo". Other warning options are already
5795   // handled somewhere else.
5796   Args.ClaimAllArgs(options::OPT_w);
5797
5798   if (!D.SysRoot.empty())
5799     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5800
5801   if (Args.hasArg(options::OPT_pie) && !Args.hasArg(options::OPT_shared))
5802     CmdArgs.push_back("-pie");
5803
5804   if (Args.hasArg(options::OPT_rdynamic))
5805     CmdArgs.push_back("-export-dynamic");
5806
5807   if (Args.hasArg(options::OPT_s))
5808     CmdArgs.push_back("-s");
5809
5810   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
5811          e = ToolChain.ExtraOpts.end();
5812        i != e; ++i)
5813     CmdArgs.push_back(i->c_str());
5814
5815   if (!Args.hasArg(options::OPT_static)) {
5816     CmdArgs.push_back("--eh-frame-hdr");
5817   }
5818
5819   CmdArgs.push_back("-m");
5820   if (ToolChain.getArch() == llvm::Triple::x86)
5821     CmdArgs.push_back("elf_i386");
5822   else if (ToolChain.getArch() == llvm::Triple::aarch64)
5823     CmdArgs.push_back("aarch64linux");
5824   else if (ToolChain.getArch() == llvm::Triple::arm
5825            ||  ToolChain.getArch() == llvm::Triple::thumb)
5826     CmdArgs.push_back("armelf_linux_eabi");
5827   else if (ToolChain.getArch() == llvm::Triple::ppc)
5828     CmdArgs.push_back("elf32ppclinux");
5829   else if (ToolChain.getArch() == llvm::Triple::ppc64)
5830     CmdArgs.push_back("elf64ppc");
5831   else if (ToolChain.getArch() == llvm::Triple::mips)
5832     CmdArgs.push_back("elf32btsmip");
5833   else if (ToolChain.getArch() == llvm::Triple::mipsel)
5834     CmdArgs.push_back("elf32ltsmip");
5835   else if (ToolChain.getArch() == llvm::Triple::mips64) {
5836     if (hasMipsN32ABIArg(Args))
5837       CmdArgs.push_back("elf32btsmipn32");
5838     else
5839       CmdArgs.push_back("elf64btsmip");
5840   }
5841   else if (ToolChain.getArch() == llvm::Triple::mips64el) {
5842     if (hasMipsN32ABIArg(Args))
5843       CmdArgs.push_back("elf32ltsmipn32");
5844     else
5845       CmdArgs.push_back("elf64ltsmip");
5846   }
5847   else
5848     CmdArgs.push_back("elf_x86_64");
5849
5850   if (Args.hasArg(options::OPT_static)) {
5851     if (ToolChain.getArch() == llvm::Triple::arm
5852         || ToolChain.getArch() == llvm::Triple::thumb)
5853       CmdArgs.push_back("-Bstatic");
5854     else
5855       CmdArgs.push_back("-static");
5856   } else if (Args.hasArg(options::OPT_shared)) {
5857     CmdArgs.push_back("-shared");
5858     if (isAndroid) {
5859       CmdArgs.push_back("-Bsymbolic");
5860     }
5861   }
5862
5863   if (ToolChain.getArch() == llvm::Triple::arm ||
5864       ToolChain.getArch() == llvm::Triple::thumb ||
5865       (!Args.hasArg(options::OPT_static) &&
5866        !Args.hasArg(options::OPT_shared))) {
5867     CmdArgs.push_back("-dynamic-linker");
5868     if (isAndroid)
5869       CmdArgs.push_back("/system/bin/linker");
5870     else if (ToolChain.getArch() == llvm::Triple::x86)
5871       CmdArgs.push_back("/lib/ld-linux.so.2");
5872     else if (ToolChain.getArch() == llvm::Triple::aarch64)
5873       CmdArgs.push_back("/lib/ld-linux-aarch64.so.1");
5874     else if (ToolChain.getArch() == llvm::Triple::arm ||
5875              ToolChain.getArch() == llvm::Triple::thumb) {
5876       if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
5877         CmdArgs.push_back("/lib/ld-linux-armhf.so.3");
5878       else
5879         CmdArgs.push_back("/lib/ld-linux.so.3");
5880     }
5881     else if (ToolChain.getArch() == llvm::Triple::mips ||
5882              ToolChain.getArch() == llvm::Triple::mipsel)
5883       CmdArgs.push_back("/lib/ld.so.1");
5884     else if (ToolChain.getArch() == llvm::Triple::mips64 ||
5885              ToolChain.getArch() == llvm::Triple::mips64el) {
5886       if (hasMipsN32ABIArg(Args))
5887         CmdArgs.push_back("/lib32/ld.so.1");
5888       else
5889         CmdArgs.push_back("/lib64/ld.so.1");
5890     }
5891     else if (ToolChain.getArch() == llvm::Triple::ppc)
5892       CmdArgs.push_back("/lib/ld.so.1");
5893     else if (ToolChain.getArch() == llvm::Triple::ppc64)
5894       CmdArgs.push_back("/lib64/ld64.so.1");
5895     else
5896       CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
5897   }
5898
5899   CmdArgs.push_back("-o");
5900   CmdArgs.push_back(Output.getFilename());
5901
5902   if (!Args.hasArg(options::OPT_nostdlib) &&
5903       !Args.hasArg(options::OPT_nostartfiles)) {
5904     if (!isAndroid) {
5905       const char *crt1 = NULL;
5906       if (!Args.hasArg(options::OPT_shared)){
5907         if (Args.hasArg(options::OPT_pie))
5908           crt1 = "Scrt1.o";
5909         else
5910           crt1 = "crt1.o";
5911       }
5912       if (crt1)
5913         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5914
5915       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5916     }
5917
5918     const char *crtbegin;
5919     if (Args.hasArg(options::OPT_static))
5920       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
5921     else if (Args.hasArg(options::OPT_shared))
5922       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
5923     else if (Args.hasArg(options::OPT_pie))
5924       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
5925     else
5926       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
5927     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5928
5929     // Add crtfastmath.o if available and fast math is enabled.
5930     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
5931   }
5932
5933   Args.AddAllArgs(CmdArgs, options::OPT_L);
5934
5935   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5936
5937   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5938        i != e; ++i)
5939     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5940
5941   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5942   // as gold requires -plugin to come before any -plugin-opt that -Wl might
5943   // forward.
5944   if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
5945     CmdArgs.push_back("-plugin");
5946     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5947     CmdArgs.push_back(Args.MakeArgString(Plugin));
5948
5949     // Try to pass driver level flags relevant to LTO code generation down to
5950     // the plugin.
5951
5952     // Handle architecture-specific flags for selecting CPU variants.
5953     if (ToolChain.getArch() == llvm::Triple::x86 ||
5954         ToolChain.getArch() == llvm::Triple::x86_64)
5955       CmdArgs.push_back(
5956           Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
5957                              getX86TargetCPU(Args, ToolChain.getTriple())));
5958     else if (ToolChain.getArch() == llvm::Triple::arm ||
5959              ToolChain.getArch() == llvm::Triple::thumb)
5960       CmdArgs.push_back(
5961           Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
5962                              getARMTargetCPU(Args, ToolChain.getTriple())));
5963
5964     // FIXME: Factor out logic for MIPS, PPC, and other targets to support this
5965     // as well.
5966   }
5967
5968
5969   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
5970     CmdArgs.push_back("--no-demangle");
5971
5972   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5973
5974   SanitizerArgs Sanitize(D, Args);
5975
5976   // Call these before we add the C++ ABI library.
5977   if (Sanitize.needsUbsanRt())
5978     addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX,
5979                     Sanitize.needsAsanRt() || Sanitize.needsTsanRt() ||
5980                     Sanitize.needsMsanRt());
5981   if (Sanitize.needsAsanRt())
5982     addAsanRTLinux(getToolChain(), Args, CmdArgs);
5983   if (Sanitize.needsTsanRt())
5984     addTsanRTLinux(getToolChain(), Args, CmdArgs);
5985   if (Sanitize.needsMsanRt())
5986     addMsanRTLinux(getToolChain(), Args, CmdArgs);
5987
5988   if (D.CCCIsCXX &&
5989       !Args.hasArg(options::OPT_nostdlib) &&
5990       !Args.hasArg(options::OPT_nodefaultlibs)) {
5991     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
5992       !Args.hasArg(options::OPT_static);
5993     if (OnlyLibstdcxxStatic)
5994       CmdArgs.push_back("-Bstatic");
5995     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5996     if (OnlyLibstdcxxStatic)
5997       CmdArgs.push_back("-Bdynamic");
5998     CmdArgs.push_back("-lm");
5999   }
6000
6001   if (!Args.hasArg(options::OPT_nostdlib)) {
6002     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
6003       if (Args.hasArg(options::OPT_static))
6004         CmdArgs.push_back("--start-group");
6005
6006       bool OpenMP = Args.hasArg(options::OPT_fopenmp);
6007       if (OpenMP) {
6008         CmdArgs.push_back("-lgomp");
6009
6010         // FIXME: Exclude this for platforms whith libgomp that doesn't require
6011         // librt. Most modern Linux platfroms require it, but some may not.
6012         CmdArgs.push_back("-lrt");
6013       }
6014
6015       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6016
6017       if (Args.hasArg(options::OPT_pthread) ||
6018           Args.hasArg(options::OPT_pthreads) || OpenMP)
6019         CmdArgs.push_back("-lpthread");
6020
6021       CmdArgs.push_back("-lc");
6022
6023       if (Args.hasArg(options::OPT_static))
6024         CmdArgs.push_back("--end-group");
6025       else
6026         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6027     }
6028
6029     if (!Args.hasArg(options::OPT_nostartfiles)) {
6030       const char *crtend;
6031       if (Args.hasArg(options::OPT_shared))
6032         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
6033       else if (Args.hasArg(options::OPT_pie))
6034         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
6035       else
6036         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
6037
6038       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
6039       if (!isAndroid)
6040         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6041     }
6042   }
6043
6044   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6045
6046   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
6047 }
6048
6049 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6050                                    const InputInfo &Output,
6051                                    const InputInfoList &Inputs,
6052                                    const ArgList &Args,
6053                                    const char *LinkingOutput) const {
6054   ArgStringList CmdArgs;
6055
6056   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6057                        options::OPT_Xassembler);
6058
6059   CmdArgs.push_back("-o");
6060   CmdArgs.push_back(Output.getFilename());
6061
6062   for (InputInfoList::const_iterator
6063          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6064     const InputInfo &II = *it;
6065     CmdArgs.push_back(II.getFilename());
6066   }
6067
6068   const char *Exec =
6069     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6070   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6071 }
6072
6073 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
6074                                const InputInfo &Output,
6075                                const InputInfoList &Inputs,
6076                                const ArgList &Args,
6077                                const char *LinkingOutput) const {
6078   const Driver &D = getToolChain().getDriver();
6079   ArgStringList CmdArgs;
6080
6081   if (Output.isFilename()) {
6082     CmdArgs.push_back("-o");
6083     CmdArgs.push_back(Output.getFilename());
6084   } else {
6085     assert(Output.isNothing() && "Invalid output.");
6086   }
6087
6088   if (!Args.hasArg(options::OPT_nostdlib) &&
6089       !Args.hasArg(options::OPT_nostartfiles)) {
6090       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6091       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6092       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6093       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
6094   }
6095
6096   Args.AddAllArgs(CmdArgs, options::OPT_L);
6097   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6098   Args.AddAllArgs(CmdArgs, options::OPT_e);
6099
6100   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6101
6102   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6103
6104   if (!Args.hasArg(options::OPT_nostdlib) &&
6105       !Args.hasArg(options::OPT_nodefaultlibs)) {
6106     if (D.CCCIsCXX) {
6107       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6108       CmdArgs.push_back("-lm");
6109     }
6110   }
6111
6112   if (!Args.hasArg(options::OPT_nostdlib) &&
6113       !Args.hasArg(options::OPT_nostartfiles)) {
6114     if (Args.hasArg(options::OPT_pthread))
6115       CmdArgs.push_back("-lpthread");
6116     CmdArgs.push_back("-lc");
6117     CmdArgs.push_back("-lCompilerRT-Generic");
6118     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
6119     CmdArgs.push_back(
6120          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6121   }
6122
6123   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6124   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6125 }
6126
6127 /// DragonFly Tools
6128
6129 // For now, DragonFly Assemble does just about the same as for
6130 // FreeBSD, but this may change soon.
6131 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6132                                        const InputInfo &Output,
6133                                        const InputInfoList &Inputs,
6134                                        const ArgList &Args,
6135                                        const char *LinkingOutput) const {
6136   ArgStringList CmdArgs;
6137
6138   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6139   // instruct as in the base system to assemble 32-bit code.
6140   if (getToolChain().getArch() == llvm::Triple::x86)
6141     CmdArgs.push_back("--32");
6142
6143   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6144                        options::OPT_Xassembler);
6145
6146   CmdArgs.push_back("-o");
6147   CmdArgs.push_back(Output.getFilename());
6148
6149   for (InputInfoList::const_iterator
6150          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6151     const InputInfo &II = *it;
6152     CmdArgs.push_back(II.getFilename());
6153   }
6154
6155   const char *Exec =
6156     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6157   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6158 }
6159
6160 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
6161                                    const InputInfo &Output,
6162                                    const InputInfoList &Inputs,
6163                                    const ArgList &Args,
6164                                    const char *LinkingOutput) const {
6165   const Driver &D = getToolChain().getDriver();
6166   ArgStringList CmdArgs;
6167
6168   if (!D.SysRoot.empty())
6169     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6170
6171   if (Args.hasArg(options::OPT_static)) {
6172     CmdArgs.push_back("-Bstatic");
6173   } else {
6174     if (Args.hasArg(options::OPT_shared))
6175       CmdArgs.push_back("-Bshareable");
6176     else {
6177       CmdArgs.push_back("-dynamic-linker");
6178       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
6179     }
6180   }
6181
6182   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6183   // instruct ld in the base system to link 32-bit code.
6184   if (getToolChain().getArch() == llvm::Triple::x86) {
6185     CmdArgs.push_back("-m");
6186     CmdArgs.push_back("elf_i386");
6187   }
6188
6189   if (Output.isFilename()) {
6190     CmdArgs.push_back("-o");
6191     CmdArgs.push_back(Output.getFilename());
6192   } else {
6193     assert(Output.isNothing() && "Invalid output.");
6194   }
6195
6196   if (!Args.hasArg(options::OPT_nostdlib) &&
6197       !Args.hasArg(options::OPT_nostartfiles)) {
6198     if (!Args.hasArg(options::OPT_shared)) {
6199       CmdArgs.push_back(
6200             Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6201       CmdArgs.push_back(
6202             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6203       CmdArgs.push_back(
6204             Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6205     } else {
6206       CmdArgs.push_back(
6207             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6208       CmdArgs.push_back(
6209             Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6210     }
6211   }
6212
6213   Args.AddAllArgs(CmdArgs, options::OPT_L);
6214   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6215   Args.AddAllArgs(CmdArgs, options::OPT_e);
6216
6217   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6218
6219   if (!Args.hasArg(options::OPT_nostdlib) &&
6220       !Args.hasArg(options::OPT_nodefaultlibs)) {
6221     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
6222     //         rpaths
6223     CmdArgs.push_back("-L/usr/lib/gcc41");
6224
6225     if (!Args.hasArg(options::OPT_static)) {
6226       CmdArgs.push_back("-rpath");
6227       CmdArgs.push_back("/usr/lib/gcc41");
6228
6229       CmdArgs.push_back("-rpath-link");
6230       CmdArgs.push_back("/usr/lib/gcc41");
6231
6232       CmdArgs.push_back("-rpath");
6233       CmdArgs.push_back("/usr/lib");
6234
6235       CmdArgs.push_back("-rpath-link");
6236       CmdArgs.push_back("/usr/lib");
6237     }
6238
6239     if (D.CCCIsCXX) {
6240       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6241       CmdArgs.push_back("-lm");
6242     }
6243
6244     if (Args.hasArg(options::OPT_shared)) {
6245       CmdArgs.push_back("-lgcc_pic");
6246     } else {
6247       CmdArgs.push_back("-lgcc");
6248     }
6249
6250
6251     if (Args.hasArg(options::OPT_pthread))
6252       CmdArgs.push_back("-lpthread");
6253
6254     if (!Args.hasArg(options::OPT_nolibc)) {
6255       CmdArgs.push_back("-lc");
6256     }
6257
6258     if (Args.hasArg(options::OPT_shared)) {
6259       CmdArgs.push_back("-lgcc_pic");
6260     } else {
6261       CmdArgs.push_back("-lgcc");
6262     }
6263   }
6264
6265   if (!Args.hasArg(options::OPT_nostdlib) &&
6266       !Args.hasArg(options::OPT_nostartfiles)) {
6267     if (!Args.hasArg(options::OPT_shared))
6268       CmdArgs.push_back(Args.MakeArgString(
6269                               getToolChain().GetFilePath("crtend.o")));
6270     else
6271       CmdArgs.push_back(Args.MakeArgString(
6272                               getToolChain().GetFilePath("crtendS.o")));
6273     CmdArgs.push_back(Args.MakeArgString(
6274                               getToolChain().GetFilePath("crtn.o")));
6275   }
6276
6277   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6278
6279   const char *Exec =
6280     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6281   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6282 }
6283
6284 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6285                                       const InputInfo &Output,
6286                                       const InputInfoList &Inputs,
6287                                       const ArgList &Args,
6288                                       const char *LinkingOutput) const {
6289   ArgStringList CmdArgs;
6290
6291   if (Output.isFilename()) {
6292     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6293                                          Output.getFilename()));
6294   } else {
6295     assert(Output.isNothing() && "Invalid output.");
6296   }
6297
6298   if (!Args.hasArg(options::OPT_nostdlib) &&
6299     !Args.hasArg(options::OPT_nostartfiles)) {
6300     CmdArgs.push_back("-defaultlib:libcmt");
6301   }
6302
6303   CmdArgs.push_back("-nologo");
6304
6305   Args.AddAllArgValues(CmdArgs, options::OPT_l);
6306
6307   // Add filenames immediately.
6308   for (InputInfoList::const_iterator
6309        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6310     if (it->isFilename())
6311       CmdArgs.push_back(it->getFilename());
6312   }
6313
6314   const char *Exec =
6315     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
6316   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6317 }