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