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