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