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