]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge ^/head r277719 through 277776.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Basic/ObjCRuntime.h"
15 #include "clang/Basic/Version.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Job.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Driver/SanitizerArgs.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "clang/Driver/Util.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/Program.h"
40 #include "llvm/Support/raw_ostream.h"
41
42 using namespace clang::driver;
43 using namespace clang::driver::tools;
44 using namespace clang;
45 using namespace llvm::opt;
46
47 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
48   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
49                                     options::OPT_fpic, options::OPT_fno_pic,
50                                     options::OPT_fPIE, options::OPT_fno_PIE,
51                                     options::OPT_fpie, options::OPT_fno_pie);
52   if (!LastPICArg)
53     return;
54   if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
55       LastPICArg->getOption().matches(options::OPT_fpic) ||
56       LastPICArg->getOption().matches(options::OPT_fPIE) ||
57       LastPICArg->getOption().matches(options::OPT_fpie)) {
58     CmdArgs.push_back("-KPIC");
59   }
60 }
61
62 /// CheckPreprocessingOptions - Perform some validation of preprocessing
63 /// arguments that is shared with gcc.
64 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
65   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
66     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
67         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
68       D.Diag(diag::err_drv_argument_only_allowed_with)
69           << A->getBaseArg().getAsString(Args)
70           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
71     }
72   }
73 }
74
75 /// CheckCodeGenerationOptions - Perform some validation of code generation
76 /// arguments that is shared with gcc.
77 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
78   // In gcc, only ARM checks this, but it seems reasonable to check universally.
79   if (Args.hasArg(options::OPT_static))
80     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
81                                        options::OPT_mdynamic_no_pic))
82       D.Diag(diag::err_drv_argument_not_allowed_with)
83         << A->getAsString(Args) << "-static";
84 }
85
86 // Add backslashes to escape spaces and other backslashes.
87 // This is used for the space-separated argument list specified with
88 // the -dwarf-debug-flags option.
89 static void EscapeSpacesAndBackslashes(const char *Arg,
90                                        SmallVectorImpl<char> &Res) {
91   for ( ; *Arg; ++Arg) {
92     switch (*Arg) {
93     default: break;
94     case ' ':
95     case '\\':
96       Res.push_back('\\');
97       break;
98     }
99     Res.push_back(*Arg);
100   }
101 }
102
103 // Quote target names for inclusion in GNU Make dependency files.
104 // Only the characters '$', '#', ' ', '\t' are quoted.
105 static void QuoteTarget(StringRef Target,
106                         SmallVectorImpl<char> &Res) {
107   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
108     switch (Target[i]) {
109     case ' ':
110     case '\t':
111       // Escape the preceding backslashes
112       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
113         Res.push_back('\\');
114
115       // Escape the space/tab
116       Res.push_back('\\');
117       break;
118     case '$':
119       Res.push_back('$');
120       break;
121     case '#':
122       Res.push_back('\\');
123       break;
124     default:
125       break;
126     }
127
128     Res.push_back(Target[i]);
129   }
130 }
131
132 static void addDirectoryList(const ArgList &Args,
133                              ArgStringList &CmdArgs,
134                              const char *ArgName,
135                              const char *EnvVar) {
136   const char *DirList = ::getenv(EnvVar);
137   bool CombinedArg = false;
138
139   if (!DirList)
140     return; // Nothing to do.
141
142   StringRef Name(ArgName);
143   if (Name.equals("-I") || Name.equals("-L"))
144     CombinedArg = true;
145
146   StringRef Dirs(DirList);
147   if (Dirs.empty()) // Empty string should not add '.'.
148     return;
149
150   StringRef::size_type Delim;
151   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
152     if (Delim == 0) { // Leading colon.
153       if (CombinedArg) {
154         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
155       } else {
156         CmdArgs.push_back(ArgName);
157         CmdArgs.push_back(".");
158       }
159     } else {
160       if (CombinedArg) {
161         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
162       } else {
163         CmdArgs.push_back(ArgName);
164         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
165       }
166     }
167     Dirs = Dirs.substr(Delim + 1);
168   }
169
170   if (Dirs.empty()) { // Trailing colon.
171     if (CombinedArg) {
172       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
173     } else {
174       CmdArgs.push_back(ArgName);
175       CmdArgs.push_back(".");
176     }
177   } else { // Add the last path.
178     if (CombinedArg) {
179       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
180     } else {
181       CmdArgs.push_back(ArgName);
182       CmdArgs.push_back(Args.MakeArgString(Dirs));
183     }
184   }
185 }
186
187 static void AddLinkerInputs(const ToolChain &TC,
188                             const InputInfoList &Inputs, const ArgList &Args,
189                             ArgStringList &CmdArgs) {
190   const Driver &D = TC.getDriver();
191
192   // Add extra linker input arguments which are not treated as inputs
193   // (constructed via -Xarch_).
194   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
195
196   for (const auto &II : Inputs) {
197     if (!TC.HasNativeLLVMSupport()) {
198       // Don't try to pass LLVM inputs unless we have native support.
199       if (II.getType() == types::TY_LLVM_IR ||
200           II.getType() == types::TY_LTO_IR ||
201           II.getType() == types::TY_LLVM_BC ||
202           II.getType() == types::TY_LTO_BC)
203         D.Diag(diag::err_drv_no_linker_llvm_support)
204           << TC.getTripleString();
205     }
206
207     // Add filenames immediately.
208     if (II.isFilename()) {
209       CmdArgs.push_back(II.getFilename());
210       continue;
211     }
212
213     // Otherwise, this is a linker input argument.
214     const Arg &A = II.getInputArg();
215
216     // Handle reserved library options.
217     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
218       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
219     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
220       TC.AddCCKextLibArgs(Args, CmdArgs);
221     else if (A.getOption().matches(options::OPT_z)) {
222       // Pass -z prefix for gcc linker compatibility.
223       A.claim();
224       A.render(Args, CmdArgs);
225     } else {
226        A.renderAsInput(Args, CmdArgs);
227     }
228   }
229
230   // LIBRARY_PATH - included following the user specified library paths.
231   //                and only supported on native toolchains.
232   if (!TC.isCrossCompiling())
233     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
234 }
235
236 /// \brief Determine whether Objective-C automated reference counting is
237 /// enabled.
238 static bool isObjCAutoRefCount(const ArgList &Args) {
239   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
240 }
241
242 /// \brief Determine whether we are linking the ObjC runtime.
243 static bool isObjCRuntimeLinked(const ArgList &Args) {
244   if (isObjCAutoRefCount(Args)) {
245     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
246     return true;
247   }
248   return Args.hasArg(options::OPT_fobjc_link_runtime);
249 }
250
251 static bool forwardToGCC(const Option &O) {
252   // Don't forward inputs from the original command line.  They are added from
253   // InputInfoList.
254   return O.getKind() != Option::InputClass &&
255          !O.hasFlag(options::DriverOption) &&
256          !O.hasFlag(options::LinkerInput);
257 }
258
259 void Clang::AddPreprocessingOptions(Compilation &C,
260                                     const JobAction &JA,
261                                     const Driver &D,
262                                     const ArgList &Args,
263                                     ArgStringList &CmdArgs,
264                                     const InputInfo &Output,
265                                     const InputInfoList &Inputs) const {
266   Arg *A;
267
268   CheckPreprocessingOptions(D, Args);
269
270   Args.AddLastArg(CmdArgs, options::OPT_C);
271   Args.AddLastArg(CmdArgs, options::OPT_CC);
272
273   // Handle dependency file generation.
274   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
275       (A = Args.getLastArg(options::OPT_MD)) ||
276       (A = Args.getLastArg(options::OPT_MMD))) {
277     // Determine the output location.
278     const char *DepFile;
279     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
280       DepFile = MF->getValue();
281       C.addFailureResultFile(DepFile, &JA);
282     } else if (Output.getType() == types::TY_Dependencies) {
283       DepFile = Output.getFilename();
284     } else if (A->getOption().matches(options::OPT_M) ||
285                A->getOption().matches(options::OPT_MM)) {
286       DepFile = "-";
287     } else {
288       DepFile = getDependencyFileName(Args, Inputs);
289       C.addFailureResultFile(DepFile, &JA);
290     }
291     CmdArgs.push_back("-dependency-file");
292     CmdArgs.push_back(DepFile);
293
294     // Add a default target if one wasn't specified.
295     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
296       const char *DepTarget;
297
298       // If user provided -o, that is the dependency target, except
299       // when we are only generating a dependency file.
300       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
301       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
302         DepTarget = OutputOpt->getValue();
303       } else {
304         // Otherwise derive from the base input.
305         //
306         // FIXME: This should use the computed output file location.
307         SmallString<128> P(Inputs[0].getBaseInput());
308         llvm::sys::path::replace_extension(P, "o");
309         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
310       }
311
312       CmdArgs.push_back("-MT");
313       SmallString<128> Quoted;
314       QuoteTarget(DepTarget, Quoted);
315       CmdArgs.push_back(Args.MakeArgString(Quoted));
316     }
317
318     if (A->getOption().matches(options::OPT_M) ||
319         A->getOption().matches(options::OPT_MD))
320       CmdArgs.push_back("-sys-header-deps");
321
322     if (isa<PrecompileJobAction>(JA))
323       CmdArgs.push_back("-module-file-deps");
324   }
325
326   if (Args.hasArg(options::OPT_MG)) {
327     if (!A || A->getOption().matches(options::OPT_MD) ||
328               A->getOption().matches(options::OPT_MMD))
329       D.Diag(diag::err_drv_mg_requires_m_or_mm);
330     CmdArgs.push_back("-MG");
331   }
332
333   Args.AddLastArg(CmdArgs, options::OPT_MP);
334
335   // Convert all -MQ <target> args to -MT <quoted target>
336   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
337                                              options::OPT_MQ),
338          ie = Args.filtered_end(); it != ie; ++it) {
339     const Arg *A = *it;
340     A->claim();
341
342     if (A->getOption().matches(options::OPT_MQ)) {
343       CmdArgs.push_back("-MT");
344       SmallString<128> Quoted;
345       QuoteTarget(A->getValue(), Quoted);
346       CmdArgs.push_back(Args.MakeArgString(Quoted));
347
348     // -MT flag - no change
349     } else {
350       A->render(Args, CmdArgs);
351     }
352   }
353
354   // Add -i* options, and automatically translate to
355   // -include-pch/-include-pth for transparent PCH support. It's
356   // wonky, but we include looking for .gch so we can support seamless
357   // replacement into a build system already set up to be generating
358   // .gch files.
359   bool RenderedImplicitInclude = false;
360   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
361          ie = Args.filtered_end(); it != ie; ++it) {
362     const Arg *A = it;
363
364     if (A->getOption().matches(options::OPT_include)) {
365       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
366       RenderedImplicitInclude = true;
367
368       // Use PCH if the user requested it.
369       bool UsePCH = D.CCCUsePCH;
370
371       bool FoundPTH = false;
372       bool FoundPCH = false;
373       SmallString<128> P(A->getValue());
374       // We want the files to have a name like foo.h.pch. Add a dummy extension
375       // so that replace_extension does the right thing.
376       P += ".dummy";
377       if (UsePCH) {
378         llvm::sys::path::replace_extension(P, "pch");
379         if (llvm::sys::fs::exists(P.str()))
380           FoundPCH = true;
381       }
382
383       if (!FoundPCH) {
384         llvm::sys::path::replace_extension(P, "pth");
385         if (llvm::sys::fs::exists(P.str()))
386           FoundPTH = true;
387       }
388
389       if (!FoundPCH && !FoundPTH) {
390         llvm::sys::path::replace_extension(P, "gch");
391         if (llvm::sys::fs::exists(P.str())) {
392           FoundPCH = UsePCH;
393           FoundPTH = !UsePCH;
394         }
395       }
396
397       if (FoundPCH || FoundPTH) {
398         if (IsFirstImplicitInclude) {
399           A->claim();
400           if (UsePCH)
401             CmdArgs.push_back("-include-pch");
402           else
403             CmdArgs.push_back("-include-pth");
404           CmdArgs.push_back(Args.MakeArgString(P.str()));
405           continue;
406         } else {
407           // Ignore the PCH if not first on command line and emit warning.
408           D.Diag(diag::warn_drv_pch_not_first_include)
409               << P.str() << A->getAsString(Args);
410         }
411       }
412     }
413
414     // Not translated, render as usual.
415     A->claim();
416     A->render(Args, CmdArgs);
417   }
418
419   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
420   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
421                   options::OPT_index_header_map);
422
423   // Add -Wp, and -Xassembler if using the preprocessor.
424
425   // FIXME: There is a very unfortunate problem here, some troubled
426   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
427   // really support that we would have to parse and then translate
428   // those options. :(
429   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
430                        options::OPT_Xpreprocessor);
431
432   // -I- is a deprecated GCC feature, reject it.
433   if (Arg *A = Args.getLastArg(options::OPT_I_))
434     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
435
436   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
437   // -isysroot to the CC1 invocation.
438   StringRef sysroot = C.getSysRoot();
439   if (sysroot != "") {
440     if (!Args.hasArg(options::OPT_isysroot)) {
441       CmdArgs.push_back("-isysroot");
442       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
443     }
444   }
445
446   // Parse additional include paths from environment variables.
447   // FIXME: We should probably sink the logic for handling these from the
448   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
449   // CPATH - included following the user specified includes (but prior to
450   // builtin and standard includes).
451   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
452   // C_INCLUDE_PATH - system includes enabled when compiling C.
453   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
454   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
455   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
456   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
457   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
458   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
459   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
460
461   // Add C++ include arguments, if needed.
462   if (types::isCXX(Inputs[0].getType()))
463     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
464
465   // Add system include arguments.
466   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
467 }
468
469 // FIXME: Move to target hook.
470 static bool isSignedCharDefault(const llvm::Triple &Triple) {
471   switch (Triple.getArch()) {
472   default:
473     return true;
474
475   case llvm::Triple::aarch64:
476   case llvm::Triple::aarch64_be:
477   case llvm::Triple::arm:
478   case llvm::Triple::armeb:
479   case llvm::Triple::thumb:
480   case llvm::Triple::thumbeb:
481     if (Triple.isOSDarwin() || Triple.isOSWindows())
482       return true;
483     return false;
484
485   case llvm::Triple::ppc:
486   case llvm::Triple::ppc64:
487     if (Triple.isOSDarwin())
488       return true;
489     return false;
490
491   case llvm::Triple::ppc64le:
492   case llvm::Triple::systemz:
493   case llvm::Triple::xcore:
494     return false;
495   }
496 }
497
498 static bool isNoCommonDefault(const llvm::Triple &Triple) {
499   switch (Triple.getArch()) {
500   default:
501     return false;
502
503   case llvm::Triple::xcore:
504     return true;
505   }
506 }
507
508 // Handle -mhwdiv=.
509 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
510                               const ArgList &Args,
511                               std::vector<const char *> &Features) {
512   StringRef HWDiv = A->getValue();
513   if (HWDiv == "arm") {
514     Features.push_back("+hwdiv-arm");
515     Features.push_back("-hwdiv");
516   } else if (HWDiv == "thumb") {
517     Features.push_back("-hwdiv-arm");
518     Features.push_back("+hwdiv");
519   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
520     Features.push_back("+hwdiv-arm");
521     Features.push_back("+hwdiv");
522   } else if (HWDiv == "none") {
523     Features.push_back("-hwdiv-arm");
524     Features.push_back("-hwdiv");
525   } else
526     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
527 }
528
529 // Handle -mfpu=.
530 //
531 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
532 // frontend target.
533 static void getARMFPUFeatures(const Driver &D, const Arg *A,
534                               const ArgList &Args,
535                               std::vector<const char *> &Features) {
536   StringRef FPU = A->getValue();
537
538   // Set the target features based on the FPU.
539   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
540     // Disable any default FPU support.
541     Features.push_back("-vfp2");
542     Features.push_back("-vfp3");
543     Features.push_back("-neon");
544   } else if (FPU == "vfp") {
545     Features.push_back("+vfp2");
546     Features.push_back("-neon");
547   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
548     Features.push_back("+vfp3");
549     Features.push_back("+d16");
550     Features.push_back("-neon");
551   } else if (FPU == "vfp3" || FPU == "vfpv3") {
552     Features.push_back("+vfp3");
553     Features.push_back("-neon");
554   } else if (FPU == "vfp4-d16" || FPU == "vfpv4-d16") {
555     Features.push_back("+vfp4");
556     Features.push_back("+d16");
557     Features.push_back("-neon");
558   } else if (FPU == "vfp4" || FPU == "vfpv4") {
559     Features.push_back("+vfp4");
560     Features.push_back("-neon");
561   } else if (FPU == "fp4-sp-d16" || FPU == "fpv4-sp-d16") {
562     Features.push_back("+vfp4");
563     Features.push_back("+d16");
564     Features.push_back("+fp-only-sp");
565     Features.push_back("-neon");
566   } else if (FPU == "fp5-sp-d16" || FPU == "fpv5-sp-d16") {
567     Features.push_back("+fp-armv8");
568     Features.push_back("+fp-only-sp");
569     Features.push_back("+d16");
570     Features.push_back("-neon");
571     Features.push_back("-crypto");
572   } else if (FPU == "fp5-dp-d16" || FPU == "fpv5-dp-d16" ||
573              FPU == "fp5-d16" || FPU == "fpv5-d16") {
574     Features.push_back("+fp-armv8");
575     Features.push_back("+d16");
576     Features.push_back("-neon");
577     Features.push_back("-crypto");
578   } else if (FPU == "fp-armv8") {
579     Features.push_back("+fp-armv8");
580     Features.push_back("-neon");
581     Features.push_back("-crypto");
582   } else if (FPU == "neon-fp-armv8") {
583     Features.push_back("+fp-armv8");
584     Features.push_back("+neon");
585     Features.push_back("-crypto");
586   } else if (FPU == "crypto-neon-fp-armv8") {
587     Features.push_back("+fp-armv8");
588     Features.push_back("+neon");
589     Features.push_back("+crypto");
590   } else if (FPU == "neon") {
591     Features.push_back("+neon");
592   } else if (FPU == "neon-vfpv3") {
593     Features.push_back("+vfp3");
594     Features.push_back("+neon");
595   } else if (FPU == "neon-vfpv4") {
596     Features.push_back("+neon");
597     Features.push_back("+vfp4");
598   } else if (FPU == "none") {
599     Features.push_back("-vfp2");
600     Features.push_back("-vfp3");
601     Features.push_back("-vfp4");
602     Features.push_back("-fp-armv8");
603     Features.push_back("-crypto");
604     Features.push_back("-neon");
605   } else
606     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
607 }
608
609 // Select the float ABI as determined by -msoft-float, -mhard-float, and
610 // -mfloat-abi=.
611 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
612                                      const llvm::Triple &Triple) {
613   StringRef FloatABI;
614   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
615                                options::OPT_mhard_float,
616                                options::OPT_mfloat_abi_EQ)) {
617     if (A->getOption().matches(options::OPT_msoft_float))
618       FloatABI = "soft";
619     else if (A->getOption().matches(options::OPT_mhard_float))
620       FloatABI = "hard";
621     else {
622       FloatABI = A->getValue();
623       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
624         D.Diag(diag::err_drv_invalid_mfloat_abi)
625           << A->getAsString(Args);
626         FloatABI = "soft";
627       }
628     }
629   }
630
631   // If unspecified, choose the default based on the platform.
632   if (FloatABI.empty()) {
633     switch (Triple.getOS()) {
634     case llvm::Triple::Darwin:
635     case llvm::Triple::MacOSX:
636     case llvm::Triple::IOS: {
637       // Darwin defaults to "softfp" for v6 and v7.
638       //
639       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
640       std::string ArchName =
641         arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
642       if (StringRef(ArchName).startswith("v6") ||
643           StringRef(ArchName).startswith("v7"))
644         FloatABI = "softfp";
645       else
646         FloatABI = "soft";
647       break;
648     }
649
650     // FIXME: this is invalid for WindowsCE
651     case llvm::Triple::Win32:
652       FloatABI = "hard";
653       break;
654
655     case llvm::Triple::FreeBSD:
656       switch(Triple.getEnvironment()) {
657       case llvm::Triple::GNUEABIHF:
658         FloatABI = "hard";
659         break;
660       default:
661         // FreeBSD defaults to soft float
662         FloatABI = "soft";
663         break;
664       }
665       break;
666
667     default:
668       switch(Triple.getEnvironment()) {
669       case llvm::Triple::GNUEABIHF:
670         FloatABI = "hard";
671         break;
672       case llvm::Triple::GNUEABI:
673         FloatABI = "softfp";
674         break;
675       case llvm::Triple::EABIHF:
676         FloatABI = "hard";
677         break;
678       case llvm::Triple::EABI:
679         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
680         FloatABI = "softfp";
681         break;
682       case llvm::Triple::Android: {
683         std::string ArchName =
684           arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
685         if (StringRef(ArchName).startswith("v7"))
686           FloatABI = "softfp";
687         else
688           FloatABI = "soft";
689         break;
690       }
691       default:
692         // Assume "soft", but warn the user we are guessing.
693         FloatABI = "soft";
694         if (Triple.getOS() != llvm::Triple::UnknownOS ||
695             !Triple.isOSBinFormatMachO())
696           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
697         break;
698       }
699     }
700   }
701
702   return FloatABI;
703 }
704
705 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
706                                  const ArgList &Args,
707                                  std::vector<const char *> &Features,
708                                  bool ForAS) {
709   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
710   if (!ForAS) {
711     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
712     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
713     // stripped out by the ARM target. We should probably pass this a new
714     // -target-option, which is handled by the -cc1/-cc1as invocation.
715     //
716     // FIXME2:  For consistency, it would be ideal if we set up the target
717     // machine state the same when using the frontend or the assembler. We don't
718     // currently do that for the assembler, we pass the options directly to the
719     // backend and never even instantiate the frontend TargetInfo. If we did,
720     // and used its handleTargetFeatures hook, then we could ensure the
721     // assembler and the frontend behave the same.
722
723     // Use software floating point operations?
724     if (FloatABI == "soft")
725       Features.push_back("+soft-float");
726
727     // Use software floating point argument passing?
728     if (FloatABI != "hard")
729       Features.push_back("+soft-float-abi");
730   }
731
732   // Honor -mfpu=.
733   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
734     getARMFPUFeatures(D, A, Args, Features);
735   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
736     getARMHWDivFeatures(D, A, Args, Features);
737
738   // Setting -msoft-float effectively disables NEON because of the GCC
739   // implementation, although the same isn't true of VFP or VFP3.
740   if (FloatABI == "soft") {
741     Features.push_back("-neon");
742     // Also need to explicitly disable features which imply NEON.
743     Features.push_back("-crypto");
744   }
745
746   // En/disable crc
747   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
748                                options::OPT_mnocrc)) {
749     if (A->getOption().matches(options::OPT_mcrc))
750       Features.push_back("+crc");
751     else
752       Features.push_back("-crc");
753   }
754 }
755
756 void Clang::AddARMTargetArgs(const ArgList &Args,
757                              ArgStringList &CmdArgs,
758                              bool KernelOrKext) const {
759   const Driver &D = getToolChain().getDriver();
760   // Get the effective triple, which takes into account the deployment target.
761   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
762   llvm::Triple Triple(TripleStr);
763   std::string CPUName = arm::getARMTargetCPU(Args, Triple);
764
765   // Select the ABI to use.
766   //
767   // FIXME: Support -meabi.
768   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
769   const char *ABIName = nullptr;
770   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
771     ABIName = A->getValue();
772   } else if (Triple.isOSBinFormatMachO()) {
773     // The backend is hardwired to assume AAPCS for M-class processors, ensure
774     // the frontend matches that.
775     if (Triple.getEnvironment() == llvm::Triple::EABI ||
776         Triple.getOS() == llvm::Triple::UnknownOS ||
777         StringRef(CPUName).startswith("cortex-m")) {
778       ABIName = "aapcs";
779     } else {
780       ABIName = "apcs-gnu";
781     }
782   } else if (Triple.isOSWindows()) {
783     // FIXME: this is invalid for WindowsCE
784     ABIName = "aapcs";
785   } else {
786     // Select the default based on the platform.
787     switch(Triple.getEnvironment()) {
788     case llvm::Triple::Android:
789     case llvm::Triple::GNUEABI:
790     case llvm::Triple::GNUEABIHF:
791       ABIName = "aapcs-linux";
792       break;
793     case llvm::Triple::EABIHF:
794     case llvm::Triple::EABI:
795       ABIName = "aapcs";
796       break;
797     default:
798       if (Triple.getOS() == llvm::Triple::NetBSD)
799         ABIName = "apcs-gnu";
800       else
801         ABIName = "aapcs";
802       break;
803     }
804   }
805   CmdArgs.push_back("-target-abi");
806   CmdArgs.push_back(ABIName);
807
808   // Determine floating point ABI from the options & target defaults.
809   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
810   if (FloatABI == "soft") {
811     // Floating point operations and argument passing are soft.
812     //
813     // FIXME: This changes CPP defines, we need -target-soft-float.
814     CmdArgs.push_back("-msoft-float");
815     CmdArgs.push_back("-mfloat-abi");
816     CmdArgs.push_back("soft");
817   } else if (FloatABI == "softfp") {
818     // Floating point operations are hard, but argument passing is soft.
819     CmdArgs.push_back("-mfloat-abi");
820     CmdArgs.push_back("soft");
821   } else {
822     // Floating point operations and argument passing are hard.
823     assert(FloatABI == "hard" && "Invalid float abi!");
824     CmdArgs.push_back("-mfloat-abi");
825     CmdArgs.push_back("hard");
826   }
827
828   // Kernel code has more strict alignment requirements.
829   if (KernelOrKext) {
830     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
831       CmdArgs.push_back("-backend-option");
832       CmdArgs.push_back("-arm-long-calls");
833     }
834
835     CmdArgs.push_back("-backend-option");
836     CmdArgs.push_back("-arm-strict-align");
837
838     // The kext linker doesn't know how to deal with movw/movt.
839     CmdArgs.push_back("-backend-option");
840     CmdArgs.push_back("-arm-use-movt=0");
841   }
842
843   // -mkernel implies -mstrict-align; don't add the redundant option.
844   if (!KernelOrKext) {
845     if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
846                                  options::OPT_munaligned_access)) {
847       CmdArgs.push_back("-backend-option");
848       if (A->getOption().matches(options::OPT_mno_unaligned_access))
849         CmdArgs.push_back("-arm-strict-align");
850       else {
851         if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
852           D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
853         CmdArgs.push_back("-arm-no-strict-align");
854       }
855     }
856   }
857
858   // Setting -mno-global-merge disables the codegen global merge pass. Setting 
859   // -mglobal-merge has no effect as the pass is enabled by default.
860   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
861                                options::OPT_mno_global_merge)) {
862     if (A->getOption().matches(options::OPT_mno_global_merge))
863       CmdArgs.push_back("-mno-global-merge");
864   }
865
866   if (!Args.hasFlag(options::OPT_mimplicit_float,
867                     options::OPT_mno_implicit_float,
868                     true))
869     CmdArgs.push_back("-no-implicit-float");
870
871   // llvm does not support reserving registers in general. There is support
872   // for reserving r9 on ARM though (defined as a platform-specific register
873   // in ARM EABI).
874   if (Args.hasArg(options::OPT_ffixed_r9)) {
875     CmdArgs.push_back("-backend-option");
876     CmdArgs.push_back("-arm-reserve-r9");
877   }
878 }
879
880 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
881 /// targeting.
882 static std::string getAArch64TargetCPU(const ArgList &Args) {
883   Arg *A;
884   std::string CPU;
885   // If we have -mtune or -mcpu, use that.
886   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
887     CPU = A->getValue();
888   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
889     StringRef Mcpu = A->getValue();
890     CPU = Mcpu.split("+").first;
891   }
892
893   // Handle CPU name is 'native'.
894   if (CPU == "native")
895     return llvm::sys::getHostCPUName();
896   else if (CPU.size())
897     return CPU;
898
899   // Make sure we pick "cyclone" if -arch is used.
900   // FIXME: Should this be picked by checking the target triple instead?
901   if (Args.getLastArg(options::OPT_arch))
902     return "cyclone";
903
904   return "generic";
905 }
906
907 void Clang::AddAArch64TargetArgs(const ArgList &Args,
908                                  ArgStringList &CmdArgs) const {
909   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
910   llvm::Triple Triple(TripleStr);
911
912   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
913       Args.hasArg(options::OPT_mkernel) ||
914       Args.hasArg(options::OPT_fapple_kext))
915     CmdArgs.push_back("-disable-red-zone");
916
917   if (!Args.hasFlag(options::OPT_mimplicit_float,
918                     options::OPT_mno_implicit_float, true))
919     CmdArgs.push_back("-no-implicit-float");
920
921   const char *ABIName = nullptr;
922   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
923     ABIName = A->getValue();
924   else if (Triple.isOSDarwin())
925     ABIName = "darwinpcs";
926   else
927     ABIName = "aapcs";
928
929   CmdArgs.push_back("-target-abi");
930   CmdArgs.push_back(ABIName);
931
932   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
933                                options::OPT_munaligned_access)) {
934     CmdArgs.push_back("-backend-option");
935     if (A->getOption().matches(options::OPT_mno_unaligned_access))
936       CmdArgs.push_back("-aarch64-strict-align");
937     else
938       CmdArgs.push_back("-aarch64-no-strict-align");
939   }
940
941   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
942                                options::OPT_mno_fix_cortex_a53_835769)) {
943     CmdArgs.push_back("-backend-option");
944     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
945       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
946     else
947       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
948   } else if (Triple.getEnvironment() == llvm::Triple::Android) {
949     // Enabled A53 errata (835769) workaround by default on android
950     CmdArgs.push_back("-backend-option");
951     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
952   }
953
954   // Setting -mno-global-merge disables the codegen global merge pass. Setting
955   // -mglobal-merge has no effect as the pass is enabled by default.
956   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
957                                options::OPT_mno_global_merge)) {
958     if (A->getOption().matches(options::OPT_mno_global_merge))
959       CmdArgs.push_back("-mno-global-merge");
960   }
961
962   if (Args.hasArg(options::OPT_ffixed_x18)) {
963     CmdArgs.push_back("-backend-option");
964     CmdArgs.push_back("-aarch64-reserve-x18");
965   }
966 }
967
968 // Get CPU and ABI names. They are not independent
969 // so we have to calculate them together.
970 void mips::getMipsCPUAndABI(const ArgList &Args,
971                             const llvm::Triple &Triple,
972                             StringRef &CPUName,
973                             StringRef &ABIName) {
974   const char *DefMips32CPU = "mips32r2";
975   const char *DefMips64CPU = "mips64r2";
976
977   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
978   // default for mips64(el)?-img-linux-gnu.
979   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
980       Triple.getEnvironment() == llvm::Triple::GNU) {
981     DefMips32CPU = "mips32r6";
982     DefMips64CPU = "mips64r6";
983   }
984
985   // MIPS3 is the default for mips64*-unknown-openbsd.
986   if (Triple.getOS() == llvm::Triple::OpenBSD)
987     DefMips64CPU = "mips3";
988
989   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
990                                options::OPT_mcpu_EQ))
991     CPUName = A->getValue();
992
993   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
994     ABIName = A->getValue();
995     // Convert a GNU style Mips ABI name to the name
996     // accepted by LLVM Mips backend.
997     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
998       .Case("32", "o32")
999       .Case("64", "n64")
1000       .Default(ABIName);
1001   }
1002
1003   // Setup default CPU and ABI names.
1004   if (CPUName.empty() && ABIName.empty()) {
1005     switch (Triple.getArch()) {
1006     default:
1007       llvm_unreachable("Unexpected triple arch name");
1008     case llvm::Triple::mips:
1009     case llvm::Triple::mipsel:
1010       CPUName = DefMips32CPU;
1011       break;
1012     case llvm::Triple::mips64:
1013     case llvm::Triple::mips64el:
1014       CPUName = DefMips64CPU;
1015       break;
1016     }
1017   }
1018
1019   if (ABIName.empty()) {
1020     // Deduce ABI name from the target triple.
1021     if (Triple.getArch() == llvm::Triple::mips ||
1022         Triple.getArch() == llvm::Triple::mipsel)
1023       ABIName = "o32";
1024     else
1025       ABIName = "n64";
1026   }
1027
1028   if (CPUName.empty()) {
1029     // Deduce CPU name from ABI name.
1030     CPUName = llvm::StringSwitch<const char *>(ABIName)
1031       .Cases("o32", "eabi", DefMips32CPU)
1032       .Cases("n32", "n64", DefMips64CPU)
1033       .Default("");
1034   }
1035
1036   // FIXME: Warn on inconsistent use of -march and -mabi.
1037 }
1038
1039 // Convert ABI name to the GNU tools acceptable variant.
1040 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1041   return llvm::StringSwitch<llvm::StringRef>(ABI)
1042     .Case("o32", "32")
1043     .Case("n64", "64")
1044     .Default(ABI);
1045 }
1046
1047 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1048 // and -mfloat-abi=.
1049 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1050   StringRef FloatABI;
1051   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1052                                options::OPT_mhard_float,
1053                                options::OPT_mfloat_abi_EQ)) {
1054     if (A->getOption().matches(options::OPT_msoft_float))
1055       FloatABI = "soft";
1056     else if (A->getOption().matches(options::OPT_mhard_float))
1057       FloatABI = "hard";
1058     else {
1059       FloatABI = A->getValue();
1060       if (FloatABI != "soft" && FloatABI != "hard") {
1061         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1062         FloatABI = "hard";
1063       }
1064     }
1065   }
1066
1067   // If unspecified, choose the default based on the platform.
1068   if (FloatABI.empty()) {
1069     // Assume "hard", because it's a default value used by gcc.
1070     // When we start to recognize specific target MIPS processors,
1071     // we will be able to select the default more correctly.
1072     FloatABI = "hard";
1073   }
1074
1075   return FloatABI;
1076 }
1077
1078 static void AddTargetFeature(const ArgList &Args,
1079                              std::vector<const char *> &Features,
1080                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1081                              StringRef FeatureName) {
1082   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1083     if (A->getOption().matches(OnOpt))
1084       Features.push_back(Args.MakeArgString("+" + FeatureName));
1085     else
1086       Features.push_back(Args.MakeArgString("-" + FeatureName));
1087   }
1088 }
1089
1090 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1091                                   const ArgList &Args,
1092                                   std::vector<const char *> &Features) {
1093   StringRef CPUName;
1094   StringRef ABIName;
1095   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1096   ABIName = getGnuCompatibleMipsABIName(ABIName);
1097
1098   // Always override the backend's default ABI.
1099   std::string ABIFeature = llvm::StringSwitch<StringRef>(ABIName)
1100                                .Case("32", "+o32")
1101                                .Case("n32", "+n32")
1102                                .Case("64", "+n64")
1103                                .Case("eabi", "+eabi")
1104                                .Default(("+" + ABIName).str());
1105   Features.push_back("-o32");
1106   Features.push_back("-n64");
1107   Features.push_back(Args.MakeArgString(ABIFeature));
1108
1109   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1110                    options::OPT_mabicalls, "noabicalls");
1111
1112   StringRef FloatABI = getMipsFloatABI(D, Args);
1113   if (FloatABI == "soft") {
1114     // FIXME: Note, this is a hack. We need to pass the selected float
1115     // mode to the MipsTargetInfoBase to define appropriate macros there.
1116     // Now it is the only method.
1117     Features.push_back("+soft-float");
1118   }
1119
1120   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1121     StringRef Val = StringRef(A->getValue());
1122     if (Val == "2008")
1123       Features.push_back("+nan2008");
1124     else if (Val == "legacy")
1125       Features.push_back("-nan2008");
1126     else
1127       D.Diag(diag::err_drv_unsupported_option_argument)
1128           << A->getOption().getName() << Val;
1129   }
1130
1131   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1132                    options::OPT_mdouble_float, "single-float");
1133   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1134                    "mips16");
1135   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1136                    options::OPT_mno_micromips, "micromips");
1137   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1138                    "dsp");
1139   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1140                    "dspr2");
1141   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1142                    "msa");
1143
1144   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1145   // pass -mfpxx
1146   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1147                                options::OPT_mfp64)) {
1148     if (A->getOption().matches(options::OPT_mfp32))
1149       Features.push_back(Args.MakeArgString("-fp64"));
1150     else if (A->getOption().matches(options::OPT_mfpxx)) {
1151       Features.push_back(Args.MakeArgString("+fpxx"));
1152       Features.push_back(Args.MakeArgString("+nooddspreg"));
1153     } else
1154       Features.push_back(Args.MakeArgString("+fp64"));
1155   } else if (mips::isFPXXDefault(Triple, CPUName, ABIName)) {
1156     Features.push_back(Args.MakeArgString("+fpxx"));
1157     Features.push_back(Args.MakeArgString("+nooddspreg"));
1158   }
1159
1160   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1161                    options::OPT_modd_spreg, "nooddspreg");
1162 }
1163
1164 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1165                               ArgStringList &CmdArgs) const {
1166   const Driver &D = getToolChain().getDriver();
1167   StringRef CPUName;
1168   StringRef ABIName;
1169   const llvm::Triple &Triple = getToolChain().getTriple();
1170   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1171
1172   CmdArgs.push_back("-target-abi");
1173   CmdArgs.push_back(ABIName.data());
1174
1175   StringRef FloatABI = getMipsFloatABI(D, Args);
1176
1177   if (FloatABI == "soft") {
1178     // Floating point operations and argument passing are soft.
1179     CmdArgs.push_back("-msoft-float");
1180     CmdArgs.push_back("-mfloat-abi");
1181     CmdArgs.push_back("soft");
1182   }
1183   else {
1184     // Floating point operations and argument passing are hard.
1185     assert(FloatABI == "hard" && "Invalid float abi!");
1186     CmdArgs.push_back("-mfloat-abi");
1187     CmdArgs.push_back("hard");
1188   }
1189
1190   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1191     if (A->getOption().matches(options::OPT_mxgot)) {
1192       CmdArgs.push_back("-mllvm");
1193       CmdArgs.push_back("-mxgot");
1194     }
1195   }
1196
1197   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1198                                options::OPT_mno_ldc1_sdc1)) {
1199     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1200       CmdArgs.push_back("-mllvm");
1201       CmdArgs.push_back("-mno-ldc1-sdc1");
1202     }
1203   }
1204
1205   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1206                                options::OPT_mno_check_zero_division)) {
1207     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1208       CmdArgs.push_back("-mllvm");
1209       CmdArgs.push_back("-mno-check-zero-division");
1210     }
1211   }
1212
1213   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1214     StringRef v = A->getValue();
1215     CmdArgs.push_back("-mllvm");
1216     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1217     A->claim();
1218   }
1219 }
1220
1221 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1222 static std::string getPPCTargetCPU(const ArgList &Args) {
1223   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1224     StringRef CPUName = A->getValue();
1225
1226     if (CPUName == "native") {
1227       std::string CPU = llvm::sys::getHostCPUName();
1228       if (!CPU.empty() && CPU != "generic")
1229         return CPU;
1230       else
1231         return "";
1232     }
1233
1234     return llvm::StringSwitch<const char *>(CPUName)
1235       .Case("common", "generic")
1236       .Case("440", "440")
1237       .Case("440fp", "440")
1238       .Case("450", "450")
1239       .Case("601", "601")
1240       .Case("602", "602")
1241       .Case("603", "603")
1242       .Case("603e", "603e")
1243       .Case("603ev", "603ev")
1244       .Case("604", "604")
1245       .Case("604e", "604e")
1246       .Case("620", "620")
1247       .Case("630", "pwr3")
1248       .Case("G3", "g3")
1249       .Case("7400", "7400")
1250       .Case("G4", "g4")
1251       .Case("7450", "7450")
1252       .Case("G4+", "g4+")
1253       .Case("750", "750")
1254       .Case("970", "970")
1255       .Case("G5", "g5")
1256       .Case("a2", "a2")
1257       .Case("a2q", "a2q")
1258       .Case("e500mc", "e500mc")
1259       .Case("e5500", "e5500")
1260       .Case("power3", "pwr3")
1261       .Case("power4", "pwr4")
1262       .Case("power5", "pwr5")
1263       .Case("power5x", "pwr5x")
1264       .Case("power6", "pwr6")
1265       .Case("power6x", "pwr6x")
1266       .Case("power7", "pwr7")
1267       .Case("power8", "pwr8")
1268       .Case("pwr3", "pwr3")
1269       .Case("pwr4", "pwr4")
1270       .Case("pwr5", "pwr5")
1271       .Case("pwr5x", "pwr5x")
1272       .Case("pwr6", "pwr6")
1273       .Case("pwr6x", "pwr6x")
1274       .Case("pwr7", "pwr7")
1275       .Case("pwr8", "pwr8")
1276       .Case("powerpc", "ppc")
1277       .Case("powerpc64", "ppc64")
1278       .Case("powerpc64le", "ppc64le")
1279       .Default("");
1280   }
1281
1282   return "";
1283 }
1284
1285 static void getPPCTargetFeatures(const ArgList &Args,
1286                                  std::vector<const char *> &Features) {
1287   for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
1288                     ie = Args.filtered_end();
1289        it != ie; ++it) {
1290     StringRef Name = (*it)->getOption().getName();
1291     (*it)->claim();
1292
1293     // Skip over "-m".
1294     assert(Name.startswith("m") && "Invalid feature name.");
1295     Name = Name.substr(1);
1296
1297     bool IsNegative = Name.startswith("no-");
1298     if (IsNegative)
1299       Name = Name.substr(3);
1300
1301     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1302     // pass the correct option to the backend while calling the frontend
1303     // option the same.
1304     // TODO: Change the LLVM backend option maybe?
1305     if (Name == "mfcrf")
1306       Name = "mfocrf";
1307
1308     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1309   }
1310
1311   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1312   AddTargetFeature(Args, Features, options::OPT_faltivec,
1313                    options::OPT_fno_altivec, "altivec");
1314 }
1315
1316 void Clang::AddPPCTargetArgs(const ArgList &Args,
1317                              ArgStringList &CmdArgs) const {
1318   // Select the ABI to use.
1319   const char *ABIName = nullptr;
1320   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1321     ABIName = A->getValue();
1322   } else if (getToolChain().getTriple().isOSLinux())
1323     switch(getToolChain().getArch()) {
1324     case llvm::Triple::ppc64:
1325       ABIName = "elfv1";
1326       break;
1327     case llvm::Triple::ppc64le:
1328       ABIName = "elfv2";
1329       break;
1330     default:
1331       break;
1332   }
1333
1334   if (ABIName) {
1335     CmdArgs.push_back("-target-abi");
1336     CmdArgs.push_back(ABIName);
1337   }
1338 }
1339
1340 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1341   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1342   return A && (A->getValue() == StringRef(Value));
1343 }
1344
1345 /// Get the (LLVM) name of the R600 gpu we are targeting.
1346 static std::string getR600TargetGPU(const ArgList &Args) {
1347   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1348     const char *GPUName = A->getValue();
1349     return llvm::StringSwitch<const char *>(GPUName)
1350       .Cases("rv630", "rv635", "r600")
1351       .Cases("rv610", "rv620", "rs780", "rs880")
1352       .Case("rv740", "rv770")
1353       .Case("palm", "cedar")
1354       .Cases("sumo", "sumo2", "sumo")
1355       .Case("hemlock", "cypress")
1356       .Case("aruba", "cayman")
1357       .Default(GPUName);
1358   }
1359   return "";
1360 }
1361
1362 static void getSparcTargetFeatures(const ArgList &Args,
1363                                    std::vector<const char *> &Features) {
1364   bool SoftFloatABI = true;
1365   if (Arg *A =
1366           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1367     if (A->getOption().matches(options::OPT_mhard_float))
1368       SoftFloatABI = false;
1369   }
1370   if (SoftFloatABI)
1371     Features.push_back("+soft-float");
1372 }
1373
1374 void Clang::AddSparcTargetArgs(const ArgList &Args,
1375                              ArgStringList &CmdArgs) const {
1376   const Driver &D = getToolChain().getDriver();
1377
1378   // Select the float ABI as determined by -msoft-float and -mhard-float.
1379   StringRef FloatABI;
1380   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1381                                options::OPT_mhard_float)) {
1382     if (A->getOption().matches(options::OPT_msoft_float))
1383       FloatABI = "soft";
1384     else if (A->getOption().matches(options::OPT_mhard_float))
1385       FloatABI = "hard";
1386   }
1387
1388   // If unspecified, choose the default based on the platform.
1389   if (FloatABI.empty()) {
1390     // Assume "soft", but warn the user we are guessing.
1391     FloatABI = "soft";
1392     D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1393   }
1394
1395   if (FloatABI == "soft") {
1396     // Floating point operations and argument passing are soft.
1397     //
1398     // FIXME: This changes CPP defines, we need -target-soft-float.
1399     CmdArgs.push_back("-msoft-float");
1400   } else {
1401     assert(FloatABI == "hard" && "Invalid float abi!");
1402     CmdArgs.push_back("-mhard-float");
1403   }
1404 }
1405
1406 static const char *getSystemZTargetCPU(const ArgList &Args) {
1407   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1408     return A->getValue();
1409   return "z10";
1410 }
1411
1412 static const char *getX86TargetCPU(const ArgList &Args,
1413                                    const llvm::Triple &Triple) {
1414   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1415     if (StringRef(A->getValue()) != "native") {
1416       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1417         return "core-avx2";
1418
1419       return A->getValue();
1420     }
1421
1422     // FIXME: Reject attempts to use -march=native unless the target matches
1423     // the host.
1424     //
1425     // FIXME: We should also incorporate the detected target features for use
1426     // with -native.
1427     std::string CPU = llvm::sys::getHostCPUName();
1428     if (!CPU.empty() && CPU != "generic")
1429       return Args.MakeArgString(CPU);
1430   }
1431
1432   // Select the default CPU if none was given (or detection failed).
1433
1434   if (Triple.getArch() != llvm::Triple::x86_64 &&
1435       Triple.getArch() != llvm::Triple::x86)
1436     return nullptr; // This routine is only handling x86 targets.
1437
1438   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1439
1440   // FIXME: Need target hooks.
1441   if (Triple.isOSDarwin()) {
1442     if (Triple.getArchName() == "x86_64h")
1443       return "core-avx2";
1444     return Is64Bit ? "core2" : "yonah";
1445   }
1446
1447   // On Android use targets compatible with gcc
1448   if (Triple.getEnvironment() == llvm::Triple::Android)
1449     return Is64Bit ? "x86-64" : "i686";
1450
1451   // Everything else goes to x86-64 in 64-bit mode.
1452   if (Is64Bit)
1453     return "x86-64";
1454
1455   switch (Triple.getOS()) {
1456   case llvm::Triple::FreeBSD:
1457   case llvm::Triple::NetBSD:
1458   case llvm::Triple::OpenBSD:
1459     return "i486";
1460   case llvm::Triple::Haiku:
1461     return "i586";
1462   case llvm::Triple::Bitrig:
1463     return "i686";
1464   default:
1465     // Fallback to p4.
1466     return "pentium4";
1467   }
1468 }
1469
1470 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1471   switch(T.getArch()) {
1472   default:
1473     return "";
1474
1475   case llvm::Triple::aarch64:
1476   case llvm::Triple::aarch64_be:
1477     return getAArch64TargetCPU(Args);
1478
1479   case llvm::Triple::arm:
1480   case llvm::Triple::armeb:
1481   case llvm::Triple::thumb:
1482   case llvm::Triple::thumbeb:
1483     return arm::getARMTargetCPU(Args, T);
1484
1485   case llvm::Triple::mips:
1486   case llvm::Triple::mipsel:
1487   case llvm::Triple::mips64:
1488   case llvm::Triple::mips64el: {
1489     StringRef CPUName;
1490     StringRef ABIName;
1491     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1492     return CPUName;
1493   }
1494
1495   case llvm::Triple::ppc:
1496   case llvm::Triple::ppc64:
1497   case llvm::Triple::ppc64le: {
1498     std::string TargetCPUName = getPPCTargetCPU(Args);
1499     // LLVM may default to generating code for the native CPU,
1500     // but, like gcc, we default to a more generic option for
1501     // each architecture. (except on Darwin)
1502     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1503       if (T.getArch() == llvm::Triple::ppc64)
1504         TargetCPUName = "ppc64";
1505       else if (T.getArch() == llvm::Triple::ppc64le)
1506         TargetCPUName = "ppc64le";
1507       else
1508         TargetCPUName = "ppc";
1509     }
1510     return TargetCPUName;
1511   }
1512
1513   case llvm::Triple::sparc:
1514   case llvm::Triple::sparcv9:
1515     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1516       return A->getValue();
1517     return "";
1518
1519   case llvm::Triple::x86:
1520   case llvm::Triple::x86_64:
1521     return getX86TargetCPU(Args, T);
1522
1523   case llvm::Triple::hexagon:
1524     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1525
1526   case llvm::Triple::systemz:
1527     return getSystemZTargetCPU(Args);
1528
1529   case llvm::Triple::r600:
1530   case llvm::Triple::amdgcn:
1531     return getR600TargetGPU(Args);
1532   }
1533 }
1534
1535 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1536                           ArgStringList &CmdArgs) {
1537   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1538   // as gold requires -plugin to come before any -plugin-opt that -Wl might
1539   // forward.
1540   CmdArgs.push_back("-plugin");
1541   std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
1542   CmdArgs.push_back(Args.MakeArgString(Plugin));
1543
1544   // Try to pass driver level flags relevant to LTO code generation down to
1545   // the plugin.
1546
1547   // Handle flags for selecting CPU variants.
1548   std::string CPU = getCPUName(Args, ToolChain.getTriple());
1549   if (!CPU.empty())
1550     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1551 }
1552
1553 static void getX86TargetFeatures(const Driver & D,
1554                                  const llvm::Triple &Triple,
1555                                  const ArgList &Args,
1556                                  std::vector<const char *> &Features) {
1557   if (Triple.getArchName() == "x86_64h") {
1558     // x86_64h implies quite a few of the more modern subtarget features
1559     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1560     Features.push_back("-rdrnd");
1561     Features.push_back("-aes");
1562     Features.push_back("-pclmul");
1563     Features.push_back("-rtm");
1564     Features.push_back("-hle");
1565     Features.push_back("-fsgsbase");
1566   }
1567
1568   // Add features to comply with gcc on Android
1569   if (Triple.getEnvironment() == llvm::Triple::Android) {
1570     if (Triple.getArch() == llvm::Triple::x86_64) {
1571       Features.push_back("+sse4.2");
1572       Features.push_back("+popcnt");
1573     } else
1574       Features.push_back("+ssse3");
1575   }
1576
1577   // Set features according to the -arch flag on MSVC
1578   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1579     StringRef Arch = A->getValue();
1580     bool ArchUsed = false;
1581     // First, look for flags that are shared in x86 and x86-64.
1582     if (Triple.getArch() == llvm::Triple::x86_64 ||
1583         Triple.getArch() == llvm::Triple::x86) {
1584       if (Arch == "AVX" || Arch == "AVX2") {
1585         ArchUsed = true;
1586         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1587       }
1588     }
1589     // Then, look for x86-specific flags.
1590     if (Triple.getArch() == llvm::Triple::x86) {
1591       if (Arch == "IA32") {
1592         ArchUsed = true;
1593       } else if (Arch == "SSE" || Arch == "SSE2") {
1594         ArchUsed = true;
1595         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1596       }
1597     }
1598     if (!ArchUsed)
1599       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1600   }
1601
1602   // Now add any that the user explicitly requested on the command line,
1603   // which may override the defaults.
1604   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1605                     ie = Args.filtered_end();
1606        it != ie; ++it) {
1607     StringRef Name = (*it)->getOption().getName();
1608     (*it)->claim();
1609
1610     // Skip over "-m".
1611     assert(Name.startswith("m") && "Invalid feature name.");
1612     Name = Name.substr(1);
1613
1614     bool IsNegative = Name.startswith("no-");
1615     if (IsNegative)
1616       Name = Name.substr(3);
1617
1618     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1619   }
1620 }
1621
1622 void Clang::AddX86TargetArgs(const ArgList &Args,
1623                              ArgStringList &CmdArgs) const {
1624   if (!Args.hasFlag(options::OPT_mred_zone,
1625                     options::OPT_mno_red_zone,
1626                     true) ||
1627       Args.hasArg(options::OPT_mkernel) ||
1628       Args.hasArg(options::OPT_fapple_kext))
1629     CmdArgs.push_back("-disable-red-zone");
1630
1631   // Default to avoid implicit floating-point for kernel/kext code, but allow
1632   // that to be overridden with -mno-soft-float.
1633   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1634                           Args.hasArg(options::OPT_fapple_kext));
1635   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1636                                options::OPT_mno_soft_float,
1637                                options::OPT_mimplicit_float,
1638                                options::OPT_mno_implicit_float)) {
1639     const Option &O = A->getOption();
1640     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1641                        O.matches(options::OPT_msoft_float));
1642   }
1643   if (NoImplicitFloat)
1644     CmdArgs.push_back("-no-implicit-float");
1645
1646   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1647     StringRef Value = A->getValue();
1648     if (Value == "intel" || Value == "att") {
1649       CmdArgs.push_back("-mllvm");
1650       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1651     } else {
1652       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1653           << A->getOption().getName() << Value;
1654     }
1655   }
1656 }
1657
1658 static inline bool HasPICArg(const ArgList &Args) {
1659   return Args.hasArg(options::OPT_fPIC)
1660     || Args.hasArg(options::OPT_fpic);
1661 }
1662
1663 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
1664   return Args.getLastArg(options::OPT_G,
1665                          options::OPT_G_EQ,
1666                          options::OPT_msmall_data_threshold_EQ);
1667 }
1668
1669 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
1670   std::string value;
1671   if (HasPICArg(Args))
1672     value = "0";
1673   else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
1674     value = A->getValue();
1675     A->claim();
1676   }
1677   return value;
1678 }
1679
1680 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1681                                  ArgStringList &CmdArgs) const {
1682   CmdArgs.push_back("-fno-signed-char");
1683   CmdArgs.push_back("-mqdsp6-compat");
1684   CmdArgs.push_back("-Wreturn-type");
1685
1686   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
1687   if (!SmallDataThreshold.empty()) {
1688     CmdArgs.push_back ("-mllvm");
1689     CmdArgs.push_back(Args.MakeArgString(
1690                         "-hexagon-small-data-threshold=" + SmallDataThreshold));
1691   }
1692
1693   if (!Args.hasArg(options::OPT_fno_short_enums))
1694     CmdArgs.push_back("-fshort-enums");
1695   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1696     CmdArgs.push_back ("-mllvm");
1697     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1698   }
1699   CmdArgs.push_back ("-mllvm");
1700   CmdArgs.push_back ("-machine-sink-split=0");
1701 }
1702
1703 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1704 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1705                                   std::vector<const char *> &Features) {
1706   SmallVector<StringRef, 8> Split;
1707   text.split(Split, StringRef("+"), -1, false);
1708
1709   for (unsigned I = 0, E = Split.size(); I != E; ++I) {
1710     const char *result = llvm::StringSwitch<const char *>(Split[I])
1711                              .Case("fp", "+fp-armv8")
1712                              .Case("simd", "+neon")
1713                              .Case("crc", "+crc")
1714                              .Case("crypto", "+crypto")
1715                              .Case("nofp", "-fp-armv8")
1716                              .Case("nosimd", "-neon")
1717                              .Case("nocrc", "-crc")
1718                              .Case("nocrypto", "-crypto")
1719                              .Default(nullptr);
1720     if (result)
1721       Features.push_back(result);
1722     else if (Split[I] == "neon" || Split[I] == "noneon")
1723       D.Diag(diag::err_drv_no_neon_modifier);
1724     else
1725       return false;
1726   }
1727   return true;
1728 }
1729
1730 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1731 // decode CPU and feature.
1732 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1733                               std::vector<const char *> &Features) {
1734   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1735   CPU = Split.first;
1736   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57") {
1737     Features.push_back("+neon");
1738     Features.push_back("+crc");
1739     Features.push_back("+crypto");
1740   } else if (CPU == "generic") {
1741     Features.push_back("+neon");
1742   } else {
1743     return false;
1744   }
1745
1746   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1747     return false;
1748
1749   return true;
1750 }
1751
1752 static bool
1753 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1754                                 const ArgList &Args,
1755                                 std::vector<const char *> &Features) {
1756   std::pair<StringRef, StringRef> Split = March.split("+");
1757   if (Split.first != "armv8-a")
1758     return false;
1759
1760   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1761     return false;
1762
1763   return true;
1764 }
1765
1766 static bool
1767 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1768                                const ArgList &Args,
1769                                std::vector<const char *> &Features) {
1770   StringRef CPU;
1771   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, Features))
1772     return false;
1773
1774   return true;
1775 }
1776
1777 static bool
1778 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
1779                                      const ArgList &Args,
1780                                      std::vector<const char *> &Features) {
1781   // Handle CPU name is 'native'.
1782   if (Mtune == "native")
1783     Mtune = llvm::sys::getHostCPUName();
1784   if (Mtune == "cyclone") {
1785     Features.push_back("+zcm");
1786     Features.push_back("+zcz");
1787   }
1788   return true;
1789 }
1790
1791 static bool
1792 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1793                                     const ArgList &Args,
1794                                     std::vector<const char *> &Features) {
1795   StringRef CPU;
1796   std::vector<const char *> DecodedFeature;
1797   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, DecodedFeature))
1798     return false;
1799
1800   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
1801 }
1802
1803 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1804                                      std::vector<const char *> &Features) {
1805   Arg *A;
1806   bool success = true;
1807   // Enable NEON by default.
1808   Features.push_back("+neon");
1809   if ((A = Args.getLastArg(options::OPT_march_EQ)))
1810     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
1811   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
1812     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1813   else if (Args.hasArg(options::OPT_arch))
1814     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
1815                                              Features);
1816
1817   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
1818     success =
1819         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
1820   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
1821     success =
1822         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1823   else if (Args.hasArg(options::OPT_arch))
1824     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
1825                                                   Args, Features);
1826
1827   if (!success)
1828     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
1829
1830   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
1831     Features.push_back("-fp-armv8");
1832     Features.push_back("-crypto");
1833     Features.push_back("-neon");
1834   }
1835
1836   // En/disable crc
1837   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
1838                                options::OPT_mnocrc)) {
1839     if (A->getOption().matches(options::OPT_mcrc))
1840       Features.push_back("+crc");
1841     else
1842       Features.push_back("-crc");
1843   }
1844 }
1845
1846 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1847                               const ArgList &Args, ArgStringList &CmdArgs,
1848                               bool ForAS) {
1849   std::vector<const char *> Features;
1850   switch (Triple.getArch()) {
1851   default:
1852     break;
1853   case llvm::Triple::mips:
1854   case llvm::Triple::mipsel:
1855   case llvm::Triple::mips64:
1856   case llvm::Triple::mips64el:
1857     getMIPSTargetFeatures(D, Triple, Args, Features);
1858     break;
1859
1860   case llvm::Triple::arm:
1861   case llvm::Triple::armeb:
1862   case llvm::Triple::thumb:
1863   case llvm::Triple::thumbeb:
1864     getARMTargetFeatures(D, Triple, Args, Features, ForAS);
1865     break;
1866
1867   case llvm::Triple::ppc:
1868   case llvm::Triple::ppc64:
1869   case llvm::Triple::ppc64le:
1870     getPPCTargetFeatures(Args, Features);
1871     break;
1872   case llvm::Triple::sparc:
1873   case llvm::Triple::sparcv9:
1874     getSparcTargetFeatures(Args, Features);
1875     break;
1876   case llvm::Triple::aarch64:
1877   case llvm::Triple::aarch64_be:
1878     getAArch64TargetFeatures(D, Args, Features);
1879     break;
1880   case llvm::Triple::x86:
1881   case llvm::Triple::x86_64:
1882     getX86TargetFeatures(D, Triple, Args, Features);
1883     break;
1884   }
1885
1886   // Find the last of each feature.
1887   llvm::StringMap<unsigned> LastOpt;
1888   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1889     const char *Name = Features[I];
1890     assert(Name[0] == '-' || Name[0] == '+');
1891     LastOpt[Name + 1] = I;
1892   }
1893
1894   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1895     // If this feature was overridden, ignore it.
1896     const char *Name = Features[I];
1897     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
1898     assert(LastI != LastOpt.end());
1899     unsigned Last = LastI->second;
1900     if (Last != I)
1901       continue;
1902
1903     CmdArgs.push_back("-target-feature");
1904     CmdArgs.push_back(Name);
1905   }
1906 }
1907
1908 static bool
1909 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1910                                           const llvm::Triple &Triple) {
1911   // We use the zero-cost exception tables for Objective-C if the non-fragile
1912   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1913   // later.
1914   if (runtime.isNonFragile())
1915     return true;
1916
1917   if (!Triple.isMacOSX())
1918     return false;
1919
1920   return (!Triple.isMacOSXVersionLT(10,5) &&
1921           (Triple.getArch() == llvm::Triple::x86_64 ||
1922            Triple.getArch() == llvm::Triple::arm));
1923 }
1924
1925 // exceptionSettings() exists to share the logic between -cc1 and linker
1926 // invocations.
1927 static bool exceptionSettings(const ArgList &Args, const llvm::Triple &Triple) {
1928   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1929                                options::OPT_fno_exceptions))
1930     if (A->getOption().matches(options::OPT_fexceptions))
1931       return true;
1932
1933   return false;
1934 }
1935
1936 /// addExceptionArgs - Adds exception related arguments to the driver command
1937 /// arguments. There's a master flag, -fexceptions and also language specific
1938 /// flags to enable/disable C++ and Objective-C exceptions.
1939 /// This makes it possible to for example disable C++ exceptions but enable
1940 /// Objective-C exceptions.
1941 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1942                              const llvm::Triple &Triple,
1943                              bool KernelOrKext,
1944                              const ObjCRuntime &objcRuntime,
1945                              ArgStringList &CmdArgs) {
1946   if (KernelOrKext) {
1947     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1948     // arguments now to avoid warnings about unused arguments.
1949     Args.ClaimAllArgs(options::OPT_fexceptions);
1950     Args.ClaimAllArgs(options::OPT_fno_exceptions);
1951     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1952     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1953     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1954     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1955     return;
1956   }
1957
1958   // Gather the exception settings from the command line arguments.
1959   bool EH = exceptionSettings(Args, Triple);
1960
1961   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1962   // is not necessarily sensible, but follows GCC.
1963   if (types::isObjC(InputType) &&
1964       Args.hasFlag(options::OPT_fobjc_exceptions,
1965                    options::OPT_fno_objc_exceptions,
1966                    true)) {
1967     CmdArgs.push_back("-fobjc-exceptions");
1968
1969     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1970   }
1971
1972   if (types::isCXX(InputType)) {
1973     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore;
1974     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1975                                  options::OPT_fno_cxx_exceptions,
1976                                  options::OPT_fexceptions,
1977                                  options::OPT_fno_exceptions))
1978       CXXExceptionsEnabled =
1979           A->getOption().matches(options::OPT_fcxx_exceptions) ||
1980           A->getOption().matches(options::OPT_fexceptions);
1981
1982     if (CXXExceptionsEnabled) {
1983       CmdArgs.push_back("-fcxx-exceptions");
1984
1985       EH = true;
1986     }
1987   }
1988
1989   if (EH)
1990     CmdArgs.push_back("-fexceptions");
1991 }
1992
1993 static bool ShouldDisableAutolink(const ArgList &Args,
1994                              const ToolChain &TC) {
1995   bool Default = true;
1996   if (TC.getTriple().isOSDarwin()) {
1997     // The native darwin assembler doesn't support the linker_option directives,
1998     // so we disable them if we think the .s file will be passed to it.
1999     Default = TC.useIntegratedAs();
2000   }
2001   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2002                        Default);
2003 }
2004
2005 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2006                                         const ToolChain &TC) {
2007   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
2008                                         options::OPT_fno_dwarf_directory_asm,
2009                                         TC.useIntegratedAs());
2010   return !UseDwarfDirectory;
2011 }
2012
2013 /// \brief Check whether the given input tree contains any compilation actions.
2014 static bool ContainsCompileAction(const Action *A) {
2015   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2016     return true;
2017
2018   for (const auto &Act : *A)
2019     if (ContainsCompileAction(Act))
2020       return true;
2021
2022   return false;
2023 }
2024
2025 /// \brief Check if -relax-all should be passed to the internal assembler.
2026 /// This is done by default when compiling non-assembler source with -O0.
2027 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2028   bool RelaxDefault = true;
2029
2030   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2031     RelaxDefault = A->getOption().matches(options::OPT_O0);
2032
2033   if (RelaxDefault) {
2034     RelaxDefault = false;
2035     for (const auto &Act : C.getActions()) {
2036       if (ContainsCompileAction(Act)) {
2037         RelaxDefault = true;
2038         break;
2039       }
2040     }
2041   }
2042
2043   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2044     RelaxDefault);
2045 }
2046
2047 static void CollectArgsForIntegratedAssembler(Compilation &C,
2048                                               const ArgList &Args,
2049                                               ArgStringList &CmdArgs,
2050                                               const Driver &D) {
2051     if (UseRelaxAll(C, Args))
2052       CmdArgs.push_back("-mrelax-all");
2053
2054     // When passing -I arguments to the assembler we sometimes need to
2055     // unconditionally take the next argument.  For example, when parsing
2056     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2057     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2058     // arg after parsing the '-I' arg.
2059     bool TakeNextArg = false;
2060
2061     // When using an integrated assembler, translate -Wa, and -Xassembler
2062     // options.
2063     bool CompressDebugSections = false;
2064     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
2065                                                options::OPT_Xassembler),
2066            ie = Args.filtered_end(); it != ie; ++it) {
2067       const Arg *A = *it;
2068       A->claim();
2069
2070       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
2071         StringRef Value = A->getValue(i);
2072         if (TakeNextArg) {
2073           CmdArgs.push_back(Value.data());
2074           TakeNextArg = false;
2075           continue;
2076         }
2077
2078         if (Value == "-force_cpusubtype_ALL") {
2079           // Do nothing, this is the default and we don't support anything else.
2080         } else if (Value == "-L") {
2081           CmdArgs.push_back("-msave-temp-labels");
2082         } else if (Value == "--fatal-warnings") {
2083           CmdArgs.push_back("-massembler-fatal-warnings");
2084         } else if (Value == "--noexecstack") {
2085           CmdArgs.push_back("-mnoexecstack");
2086         } else if (Value == "-compress-debug-sections" ||
2087                    Value == "--compress-debug-sections") {
2088           CompressDebugSections = true;
2089         } else if (Value == "-nocompress-debug-sections" ||
2090                    Value == "--nocompress-debug-sections") {
2091           CompressDebugSections = false;
2092         } else if (Value.startswith("-I")) {
2093           CmdArgs.push_back(Value.data());
2094           // We need to consume the next argument if the current arg is a plain
2095           // -I. The next arg will be the include directory.
2096           if (Value == "-I")
2097             TakeNextArg = true;
2098         } else if (Value.startswith("-gdwarf-")) {
2099           CmdArgs.push_back(Value.data());
2100         } else {
2101           D.Diag(diag::err_drv_unsupported_option_argument)
2102             << A->getOption().getName() << Value;
2103         }
2104       }
2105     }
2106     if (CompressDebugSections) {
2107       if (llvm::zlib::isAvailable())
2108         CmdArgs.push_back("-compress-debug-sections");
2109       else
2110         D.Diag(diag::warn_debug_compression_unavailable);
2111     }
2112 }
2113
2114 // Until ARM libraries are build separately, we have them all in one library
2115 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2116   // FIXME: handle 64-bit
2117   if (TC.getTriple().isOSWindows() &&
2118       !TC.getTriple().isWindowsItaniumEnvironment())
2119     return "i386";
2120   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2121     return "arm";
2122   return TC.getArchName();
2123 }
2124
2125 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2126   // The runtimes are located in the OS-specific resource directory.
2127   SmallString<128> Res(TC.getDriver().ResourceDir);
2128   const llvm::Triple &Triple = TC.getTriple();
2129   // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2130   StringRef OSLibName =
2131       (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2132   llvm::sys::path::append(Res, "lib", OSLibName);
2133   return Res;
2134 }
2135
2136 static SmallString<128> getCompilerRT(const ToolChain &TC, StringRef Component,
2137                                       bool Shared = false,
2138                                       const char *Env = "") {
2139   bool IsOSWindows = TC.getTriple().isOSWindows();
2140   StringRef Arch = getArchNameForCompilerRTLib(TC);
2141   const char *Prefix = IsOSWindows ? "" : "lib";
2142   const char *Suffix =
2143       Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
2144
2145   SmallString<128> Path = getCompilerRTLibDir(TC);
2146   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2147                                     Arch + Env + Suffix);
2148
2149   return Path;
2150 }
2151
2152 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2153 // FIXME: Make sure we can also emit shared objects if they're requested
2154 // and available, check for possible errors, etc.
2155 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2156                        ArgStringList &CmdArgs) {
2157   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2158
2159   if (!TC.getTriple().isOSWindows()) {
2160     // FIXME: why do we link against gcc when we are using compiler-rt?
2161     CmdArgs.push_back("-lgcc_s");
2162     if (TC.getDriver().CCCIsCXX())
2163       CmdArgs.push_back("-lgcc_eh");
2164   }
2165 }
2166
2167 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2168                          ArgStringList &CmdArgs) {
2169   if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2170                      false) ||
2171         Args.hasArg(options::OPT_fprofile_generate) ||
2172         Args.hasArg(options::OPT_fprofile_instr_generate) ||
2173         Args.hasArg(options::OPT_fcreate_profile) ||
2174         Args.hasArg(options::OPT_coverage)))
2175     return;
2176
2177   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2178 }
2179
2180 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2181                                 ArgStringList &CmdArgs, StringRef Sanitizer,
2182                                 bool IsShared) {
2183   const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2184                         ? "-android"
2185                         : "";
2186
2187   // Static runtimes must be forced into executable, so we wrap them in
2188   // whole-archive.
2189   if (!IsShared)
2190     CmdArgs.push_back("-whole-archive");
2191   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared,
2192                                                      Env)));
2193   if (!IsShared)
2194     CmdArgs.push_back("-no-whole-archive");
2195 }
2196
2197 // Tries to use a file with the list of dynamic symbols that need to be exported
2198 // from the runtime library. Returns true if the file was found.
2199 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2200                                     ArgStringList &CmdArgs,
2201                                     StringRef Sanitizer) {
2202   SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2203   if (llvm::sys::fs::exists(SanRT + ".syms")) {
2204     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2205     return true;
2206   }
2207   return false;
2208 }
2209
2210 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2211                                      ArgStringList &CmdArgs) {
2212   // Force linking against the system libraries sanitizers depends on
2213   // (see PR15823 why this is necessary).
2214   CmdArgs.push_back("--no-as-needed");
2215   CmdArgs.push_back("-lpthread");
2216   CmdArgs.push_back("-lrt");
2217   CmdArgs.push_back("-lm");
2218   // There's no libdl on FreeBSD.
2219   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2220     CmdArgs.push_back("-ldl");
2221 }
2222
2223 static void
2224 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2225                          SmallVectorImpl<StringRef> &SharedRuntimes,
2226                          SmallVectorImpl<StringRef> &StaticRuntimes,
2227                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2228   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2229   // Collect shared runtimes.
2230   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2231     SharedRuntimes.push_back("asan");
2232   }
2233
2234   // Collect static runtimes.
2235   if (Args.hasArg(options::OPT_shared) ||
2236       (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2237     // Don't link static runtimes into DSOs or if compiling for Android.
2238     return;
2239   }
2240   if (SanArgs.needsAsanRt()) {
2241     if (SanArgs.needsSharedAsanRt()) {
2242       HelperStaticRuntimes.push_back("asan-preinit");
2243     } else {
2244       StaticRuntimes.push_back("asan");
2245       if (SanArgs.linkCXXRuntimes())
2246         StaticRuntimes.push_back("asan_cxx");
2247     }
2248   }
2249   if (SanArgs.needsDfsanRt())
2250     StaticRuntimes.push_back("dfsan");
2251   if (SanArgs.needsLsanRt())
2252     StaticRuntimes.push_back("lsan");
2253   if (SanArgs.needsMsanRt())
2254     StaticRuntimes.push_back("msan");
2255   if (SanArgs.needsTsanRt())
2256     StaticRuntimes.push_back("tsan");
2257   // WARNING: UBSan should always go last.
2258   if (SanArgs.needsUbsanRt()) {
2259     // If UBSan is not combined with another sanitizer, we need to pull in
2260     // sanitizer_common explicitly.
2261     if (StaticRuntimes.empty())
2262       HelperStaticRuntimes.push_back("san");
2263     StaticRuntimes.push_back("ubsan");
2264     if (SanArgs.linkCXXRuntimes())
2265       StaticRuntimes.push_back("ubsan_cxx");
2266   }
2267 }
2268
2269 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2270 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2271 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2272                                  ArgStringList &CmdArgs) {
2273   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2274       HelperStaticRuntimes;
2275   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2276                            HelperStaticRuntimes);
2277   for (auto RT : SharedRuntimes)
2278     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2279   for (auto RT : HelperStaticRuntimes)
2280     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2281   bool AddExportDynamic = false;
2282   for (auto RT : StaticRuntimes) {
2283     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2284     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2285   }
2286   // If there is a static runtime with no dynamic list, force all the symbols
2287   // to be dynamic to be sure we export sanitizer interface functions.
2288   if (AddExportDynamic)
2289     CmdArgs.push_back("-export-dynamic");
2290   return !StaticRuntimes.empty();
2291 }
2292
2293 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2294                                            const llvm::Triple &Triple) {
2295   switch (Triple.getArch()) {
2296   // Don't use a frame pointer on linux if optimizing for certain targets.
2297   case llvm::Triple::mips64:
2298   case llvm::Triple::mips64el:
2299   case llvm::Triple::mips:
2300   case llvm::Triple::mipsel:
2301   case llvm::Triple::systemz:
2302   case llvm::Triple::x86:
2303   case llvm::Triple::x86_64:
2304     if (Triple.isOSLinux())
2305       if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2306         if (!A->getOption().matches(options::OPT_O0))
2307           return false;
2308     return true;
2309   case llvm::Triple::xcore:
2310     return false;
2311   default:
2312     return true;
2313   }
2314 }
2315
2316 static bool shouldUseFramePointer(const ArgList &Args,
2317                                   const llvm::Triple &Triple) {
2318   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2319                                options::OPT_fomit_frame_pointer))
2320     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2321
2322   return shouldUseFramePointerForTarget(Args, Triple);
2323 }
2324
2325 static bool shouldUseLeafFramePointer(const ArgList &Args,
2326                                       const llvm::Triple &Triple) {
2327   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2328                                options::OPT_momit_leaf_frame_pointer))
2329     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2330
2331   return shouldUseFramePointerForTarget(Args, Triple);
2332 }
2333
2334 /// Add a CC1 option to specify the debug compilation directory.
2335 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2336   SmallString<128> cwd;
2337   if (!llvm::sys::fs::current_path(cwd)) {
2338     CmdArgs.push_back("-fdebug-compilation-dir");
2339     CmdArgs.push_back(Args.MakeArgString(cwd));
2340   }
2341 }
2342
2343 static const char *SplitDebugName(const ArgList &Args,
2344                                   const InputInfoList &Inputs) {
2345   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2346   if (FinalOutput && Args.hasArg(options::OPT_c)) {
2347     SmallString<128> T(FinalOutput->getValue());
2348     llvm::sys::path::replace_extension(T, "dwo");
2349     return Args.MakeArgString(T);
2350   } else {
2351     // Use the compilation dir.
2352     SmallString<128> T(
2353         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2354     SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
2355     llvm::sys::path::replace_extension(F, "dwo");
2356     T += F;
2357     return Args.MakeArgString(F);
2358   }
2359 }
2360
2361 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
2362                            const Tool &T, const JobAction &JA,
2363                            const ArgList &Args, const InputInfo &Output,
2364                            const char *OutFile) {
2365   ArgStringList ExtractArgs;
2366   ExtractArgs.push_back("--extract-dwo");
2367
2368   ArgStringList StripArgs;
2369   StripArgs.push_back("--strip-dwo");
2370
2371   // Grabbing the output of the earlier compile step.
2372   StripArgs.push_back(Output.getFilename());
2373   ExtractArgs.push_back(Output.getFilename());
2374   ExtractArgs.push_back(OutFile);
2375
2376   const char *Exec =
2377     Args.MakeArgString(TC.GetProgramPath("objcopy"));
2378
2379   // First extract the dwo sections.
2380   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2381
2382   // Then remove them from the original .o file.
2383   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2384 }
2385
2386 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2387 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2388 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2389   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2390     if (A->getOption().matches(options::OPT_O4) ||
2391         A->getOption().matches(options::OPT_Ofast))
2392       return true;
2393
2394     if (A->getOption().matches(options::OPT_O0))
2395       return false;
2396
2397     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2398
2399     // Vectorize -Os.
2400     StringRef S(A->getValue());
2401     if (S == "s")
2402       return true;
2403
2404     // Don't vectorize -Oz, unless it's the slp vectorizer.
2405     if (S == "z")
2406       return isSlpVec;
2407
2408     unsigned OptLevel = 0;
2409     if (S.getAsInteger(10, OptLevel))
2410       return false;
2411
2412     return OptLevel > 1;
2413   }
2414
2415   return false;
2416 }
2417
2418 /// Add -x lang to \p CmdArgs for \p Input.
2419 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2420                              ArgStringList &CmdArgs) {
2421   // When using -verify-pch, we don't want to provide the type
2422   // 'precompiled-header' if it was inferred from the file extension
2423   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2424     return;
2425
2426   CmdArgs.push_back("-x");
2427   if (Args.hasArg(options::OPT_rewrite_objc))
2428     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2429   else
2430     CmdArgs.push_back(types::getTypeName(Input.getType()));
2431 }
2432
2433 static std::string getMSCompatibilityVersion(const char *VersionStr) {
2434   unsigned Version;
2435   if (StringRef(VersionStr).getAsInteger(10, Version))
2436     return "0";
2437
2438   if (Version < 100)
2439     return llvm::utostr_32(Version) + ".0";
2440
2441   if (Version < 10000)
2442     return llvm::utostr_32(Version / 100) + "." +
2443         llvm::utostr_32(Version % 100);
2444
2445   unsigned Build = 0, Factor = 1;
2446   for ( ; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2447     Build = Build + (Version % 10) * Factor;
2448   return llvm::utostr_32(Version / 100) + "." +
2449       llvm::utostr_32(Version % 100) + "." +
2450       llvm::utostr_32(Build);
2451 }
2452
2453 // Claim options we don't want to warn if they are unused. We do this for
2454 // options that build systems might add but are unused when assembling or only
2455 // running the preprocessor for example.
2456 static void claimNoWarnArgs(const ArgList &Args) {
2457   // Don't warn about unused -f(no-)?lto.  This can happen when we're
2458   // preprocessing, precompiling or assembling.
2459   Args.ClaimAllArgs(options::OPT_flto);
2460   Args.ClaimAllArgs(options::OPT_fno_lto);
2461 }
2462
2463 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2464                          const InputInfo &Output,
2465                          const InputInfoList &Inputs,
2466                          const ArgList &Args,
2467                          const char *LinkingOutput) const {
2468   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2469                                   options::OPT_fapple_kext);
2470   const Driver &D = getToolChain().getDriver();
2471   ArgStringList CmdArgs;
2472
2473   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2474   bool IsWindowsCygnus =
2475       getToolChain().getTriple().isWindowsCygwinEnvironment();
2476   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2477
2478   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2479
2480   // Invoke ourselves in -cc1 mode.
2481   //
2482   // FIXME: Implement custom jobs for internal actions.
2483   CmdArgs.push_back("-cc1");
2484
2485   // Add the "effective" target triple.
2486   CmdArgs.push_back("-triple");
2487   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2488   CmdArgs.push_back(Args.MakeArgString(TripleStr));
2489
2490   const llvm::Triple TT(TripleStr);
2491   if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2492                            TT.getArch() == llvm::Triple::thumb)) {
2493     unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2494     unsigned Version;
2495     TT.getArchName().substr(Offset).getAsInteger(10, Version);
2496     if (Version < 7)
2497       D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2498                                                 << TripleStr;
2499   }
2500
2501   // Push all default warning arguments that are specific to
2502   // the given target.  These come before user provided warning options
2503   // are provided.
2504   getToolChain().addClangWarningOptions(CmdArgs);
2505
2506   // Select the appropriate action.
2507   RewriteKind rewriteKind = RK_None;
2508   
2509   if (isa<AnalyzeJobAction>(JA)) {
2510     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2511     CmdArgs.push_back("-analyze");
2512   } else if (isa<MigrateJobAction>(JA)) {
2513     CmdArgs.push_back("-migrate");
2514   } else if (isa<PreprocessJobAction>(JA)) {
2515     if (Output.getType() == types::TY_Dependencies)
2516       CmdArgs.push_back("-Eonly");
2517     else {
2518       CmdArgs.push_back("-E");
2519       if (Args.hasArg(options::OPT_rewrite_objc) &&
2520           !Args.hasArg(options::OPT_g_Group))
2521         CmdArgs.push_back("-P");
2522     }
2523   } else if (isa<AssembleJobAction>(JA)) {
2524     CmdArgs.push_back("-emit-obj");
2525
2526     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2527
2528     // Also ignore explicit -force_cpusubtype_ALL option.
2529     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2530   } else if (isa<PrecompileJobAction>(JA)) {
2531     // Use PCH if the user requested it.
2532     bool UsePCH = D.CCCUsePCH;
2533
2534     if (JA.getType() == types::TY_Nothing)
2535       CmdArgs.push_back("-fsyntax-only");
2536     else if (UsePCH)
2537       CmdArgs.push_back("-emit-pch");
2538     else
2539       CmdArgs.push_back("-emit-pth");
2540   } else if (isa<VerifyPCHJobAction>(JA)) {
2541     CmdArgs.push_back("-verify-pch");
2542   } else {
2543     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2544            "Invalid action for clang tool.");
2545
2546     if (JA.getType() == types::TY_Nothing) {
2547       CmdArgs.push_back("-fsyntax-only");
2548     } else if (JA.getType() == types::TY_LLVM_IR ||
2549                JA.getType() == types::TY_LTO_IR) {
2550       CmdArgs.push_back("-emit-llvm");
2551     } else if (JA.getType() == types::TY_LLVM_BC ||
2552                JA.getType() == types::TY_LTO_BC) {
2553       CmdArgs.push_back("-emit-llvm-bc");
2554     } else if (JA.getType() == types::TY_PP_Asm) {
2555       CmdArgs.push_back("-S");
2556     } else if (JA.getType() == types::TY_AST) {
2557       CmdArgs.push_back("-emit-pch");
2558     } else if (JA.getType() == types::TY_ModuleFile) {
2559       CmdArgs.push_back("-module-file-info");
2560     } else if (JA.getType() == types::TY_RewrittenObjC) {
2561       CmdArgs.push_back("-rewrite-objc");
2562       rewriteKind = RK_NonFragile;
2563     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2564       CmdArgs.push_back("-rewrite-objc");
2565       rewriteKind = RK_Fragile;
2566     } else {
2567       assert(JA.getType() == types::TY_PP_Asm &&
2568              "Unexpected output type!");
2569     }
2570   }
2571
2572   // We normally speed up the clang process a bit by skipping destructors at
2573   // exit, but when we're generating diagnostics we can rely on some of the
2574   // cleanup.
2575   if (!C.isForDiagnostics())
2576     CmdArgs.push_back("-disable-free");
2577
2578   // Disable the verification pass in -asserts builds.
2579 #ifdef NDEBUG
2580   CmdArgs.push_back("-disable-llvm-verifier");
2581 #endif
2582
2583   // Set the main file name, so that debug info works even with
2584   // -save-temps.
2585   CmdArgs.push_back("-main-file-name");
2586   CmdArgs.push_back(getBaseInputName(Args, Inputs));
2587
2588   // Some flags which affect the language (via preprocessor
2589   // defines).
2590   if (Args.hasArg(options::OPT_static))
2591     CmdArgs.push_back("-static-define");
2592
2593   if (isa<AnalyzeJobAction>(JA)) {
2594     // Enable region store model by default.
2595     CmdArgs.push_back("-analyzer-store=region");
2596
2597     // Treat blocks as analysis entry points.
2598     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2599
2600     CmdArgs.push_back("-analyzer-eagerly-assume");
2601
2602     // Add default argument set.
2603     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2604       CmdArgs.push_back("-analyzer-checker=core");
2605
2606       if (!IsWindowsMSVC)
2607         CmdArgs.push_back("-analyzer-checker=unix");
2608
2609       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2610         CmdArgs.push_back("-analyzer-checker=osx");
2611       
2612       CmdArgs.push_back("-analyzer-checker=deadcode");
2613       
2614       if (types::isCXX(Inputs[0].getType()))
2615         CmdArgs.push_back("-analyzer-checker=cplusplus");
2616
2617       // Enable the following experimental checkers for testing.
2618       CmdArgs.push_back(
2619           "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2620       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2621       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2622       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
2623       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2624       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2625     }
2626
2627     // Set the output format. The default is plist, for (lame) historical
2628     // reasons.
2629     CmdArgs.push_back("-analyzer-output");
2630     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2631       CmdArgs.push_back(A->getValue());
2632     else
2633       CmdArgs.push_back("plist");
2634
2635     // Disable the presentation of standard compiler warnings when
2636     // using --analyze.  We only want to show static analyzer diagnostics
2637     // or frontend errors.
2638     CmdArgs.push_back("-w");
2639
2640     // Add -Xanalyzer arguments when running as analyzer.
2641     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2642   }
2643
2644   CheckCodeGenerationOptions(D, Args);
2645
2646   bool PIE = getToolChain().isPIEDefault();
2647   bool PIC = PIE || getToolChain().isPICDefault();
2648   bool IsPICLevelTwo = PIC;
2649
2650   // Android-specific defaults for PIC/PIE
2651   if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
2652     switch (getToolChain().getTriple().getArch()) {
2653     case llvm::Triple::arm:
2654     case llvm::Triple::armeb:
2655     case llvm::Triple::thumb:
2656     case llvm::Triple::thumbeb:
2657     case llvm::Triple::aarch64:
2658     case llvm::Triple::mips:
2659     case llvm::Triple::mipsel:
2660     case llvm::Triple::mips64:
2661     case llvm::Triple::mips64el:
2662       PIC = true; // "-fpic"
2663       break;
2664
2665     case llvm::Triple::x86:
2666     case llvm::Triple::x86_64:
2667       PIC = true; // "-fPIC"
2668       IsPICLevelTwo = true;
2669       break;
2670
2671     default:
2672       break;
2673     }
2674   }
2675
2676   // OpenBSD-specific defaults for PIE
2677   if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
2678     switch (getToolChain().getTriple().getArch()) {
2679     case llvm::Triple::mips64:
2680     case llvm::Triple::mips64el:
2681     case llvm::Triple::sparc:
2682     case llvm::Triple::x86:
2683     case llvm::Triple::x86_64:
2684       IsPICLevelTwo = false; // "-fpie"
2685       break;
2686
2687     case llvm::Triple::ppc:
2688     case llvm::Triple::sparcv9:
2689       IsPICLevelTwo = true; // "-fPIE"
2690       break;
2691
2692     default:
2693       break;
2694     }
2695   }
2696
2697   // For the PIC and PIE flag options, this logic is different from the
2698   // legacy logic in very old versions of GCC, as that logic was just
2699   // a bug no one had ever fixed. This logic is both more rational and
2700   // consistent with GCC's new logic now that the bugs are fixed. The last
2701   // argument relating to either PIC or PIE wins, and no other argument is
2702   // used. If the last argument is any flavor of the '-fno-...' arguments,
2703   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2704   // at the same level.
2705   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2706                                  options::OPT_fpic, options::OPT_fno_pic,
2707                                  options::OPT_fPIE, options::OPT_fno_PIE,
2708                                  options::OPT_fpie, options::OPT_fno_pie);
2709   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2710   // is forced, then neither PIC nor PIE flags will have no effect.
2711   if (!getToolChain().isPICDefaultForced()) {
2712     if (LastPICArg) {
2713       Option O = LastPICArg->getOption();
2714       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2715           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2716         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2717         PIC = PIE || O.matches(options::OPT_fPIC) ||
2718               O.matches(options::OPT_fpic);
2719         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2720                         O.matches(options::OPT_fPIC);
2721       } else {
2722         PIE = PIC = false;
2723       }
2724     }
2725   }
2726
2727   // Introduce a Darwin-specific hack. If the default is PIC but the flags
2728   // specified while enabling PIC enabled level 1 PIC, just force it back to
2729   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2730   // informal testing).
2731   if (PIC && getToolChain().getTriple().isOSDarwin())
2732     IsPICLevelTwo |= getToolChain().isPICDefault();
2733
2734   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
2735   // PIC or PIE options above, if these show up, PIC is disabled.
2736   llvm::Triple Triple(TripleStr);
2737   if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
2738     PIC = PIE = false;
2739   if (Args.hasArg(options::OPT_static))
2740     PIC = PIE = false;
2741
2742   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
2743     // This is a very special mode. It trumps the other modes, almost no one
2744     // uses it, and it isn't even valid on any OS but Darwin.
2745     if (!getToolChain().getTriple().isOSDarwin())
2746       D.Diag(diag::err_drv_unsupported_opt_for_target)
2747         << A->getSpelling() << getToolChain().getTriple().str();
2748
2749     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2750
2751     CmdArgs.push_back("-mrelocation-model");
2752     CmdArgs.push_back("dynamic-no-pic");
2753
2754     // Only a forced PIC mode can cause the actual compile to have PIC defines
2755     // etc., no flags are sufficient. This behavior was selected to closely
2756     // match that of llvm-gcc and Apple GCC before that.
2757     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
2758       CmdArgs.push_back("-pic-level");
2759       CmdArgs.push_back("2");
2760     }
2761   } else {
2762     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
2763     // handled in Clang's IRGen by the -pie-level flag.
2764     CmdArgs.push_back("-mrelocation-model");
2765     CmdArgs.push_back(PIC ? "pic" : "static");
2766
2767     if (PIC) {
2768       CmdArgs.push_back("-pic-level");
2769       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2770       if (PIE) {
2771         CmdArgs.push_back("-pie-level");
2772         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2773       }
2774     }
2775   }
2776
2777   CmdArgs.push_back("-mthread-model");
2778   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
2779     CmdArgs.push_back(A->getValue());
2780   else
2781     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
2782
2783   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2784                     options::OPT_fno_merge_all_constants))
2785     CmdArgs.push_back("-fno-merge-all-constants");
2786
2787   // LLVM Code Generator Options.
2788
2789   if (Args.hasArg(options::OPT_frewrite_map_file) ||
2790       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
2791     for (arg_iterator
2792              MFI = Args.filtered_begin(options::OPT_frewrite_map_file,
2793                                        options::OPT_frewrite_map_file_EQ),
2794              MFE = Args.filtered_end();
2795          MFI != MFE; ++MFI) {
2796       CmdArgs.push_back("-frewrite-map-file");
2797       CmdArgs.push_back((*MFI)->getValue());
2798       (*MFI)->claim();
2799     }
2800   }
2801
2802   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
2803     StringRef v = A->getValue();
2804     CmdArgs.push_back("-mllvm");
2805     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
2806     A->claim();
2807   }
2808
2809   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2810     CmdArgs.push_back("-mregparm");
2811     CmdArgs.push_back(A->getValue());
2812   }
2813
2814   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2815                                options::OPT_freg_struct_return)) {
2816     if (getToolChain().getArch() != llvm::Triple::x86) {
2817       D.Diag(diag::err_drv_unsupported_opt_for_target)
2818         << A->getSpelling() << getToolChain().getTriple().str();
2819     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2820       CmdArgs.push_back("-fpcc-struct-return");
2821     } else {
2822       assert(A->getOption().matches(options::OPT_freg_struct_return));
2823       CmdArgs.push_back("-freg-struct-return");
2824     }
2825   }
2826
2827   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2828     CmdArgs.push_back("-mrtd");
2829
2830   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2831     CmdArgs.push_back("-mdisable-fp-elim");
2832   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2833                     options::OPT_fno_zero_initialized_in_bss))
2834     CmdArgs.push_back("-mno-zero-initialized-in-bss");
2835
2836   bool OFastEnabled = isOptimizationLevelFast(Args);
2837   // If -Ofast is the optimization level, then -fstrict-aliasing should be
2838   // enabled.  This alias option is being used to simplify the hasFlag logic.
2839   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
2840     options::OPT_fstrict_aliasing;
2841   // We turn strict aliasing off by default if we're in CL mode, since MSVC
2842   // doesn't do any TBAA.
2843   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
2844   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2845                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
2846     CmdArgs.push_back("-relaxed-aliasing");
2847   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2848                     options::OPT_fno_struct_path_tbaa))
2849     CmdArgs.push_back("-no-struct-path-tbaa");
2850   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2851                    false))
2852     CmdArgs.push_back("-fstrict-enums");
2853   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2854                     options::OPT_fno_optimize_sibling_calls))
2855     CmdArgs.push_back("-mdisable-tail-calls");
2856
2857   // Handle segmented stacks.
2858   if (Args.hasArg(options::OPT_fsplit_stack))
2859     CmdArgs.push_back("-split-stacks");
2860
2861   // If -Ofast is the optimization level, then -ffast-math should be enabled.
2862   // This alias option is being used to simplify the getLastArg logic.
2863   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
2864     options::OPT_ffast_math;
2865   
2866   // Handle various floating point optimization flags, mapping them to the
2867   // appropriate LLVM code generation flags. The pattern for all of these is to
2868   // default off the codegen optimizations, and if any flag enables them and no
2869   // flag disables them after the flag enabling them, enable the codegen
2870   // optimization. This is complicated by several "umbrella" flags.
2871   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2872                                options::OPT_fno_fast_math,
2873                                options::OPT_ffinite_math_only,
2874                                options::OPT_fno_finite_math_only,
2875                                options::OPT_fhonor_infinities,
2876                                options::OPT_fno_honor_infinities))
2877     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2878         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2879         A->getOption().getID() != options::OPT_fhonor_infinities)
2880       CmdArgs.push_back("-menable-no-infs");
2881   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2882                                options::OPT_fno_fast_math,
2883                                options::OPT_ffinite_math_only,
2884                                options::OPT_fno_finite_math_only,
2885                                options::OPT_fhonor_nans,
2886                                options::OPT_fno_honor_nans))
2887     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2888         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2889         A->getOption().getID() != options::OPT_fhonor_nans)
2890       CmdArgs.push_back("-menable-no-nans");
2891
2892   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2893   bool MathErrno = getToolChain().IsMathErrnoDefault();
2894   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2895                                options::OPT_fno_fast_math,
2896                                options::OPT_fmath_errno,
2897                                options::OPT_fno_math_errno)) {
2898     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
2899     // However, turning *off* -ffast_math merely restores the toolchain default
2900     // (which may be false).
2901     if (A->getOption().getID() == options::OPT_fno_math_errno ||
2902         A->getOption().getID() == options::OPT_ffast_math ||
2903         A->getOption().getID() == options::OPT_Ofast)
2904       MathErrno = false;
2905     else if (A->getOption().getID() == options::OPT_fmath_errno)
2906       MathErrno = true;
2907   }
2908   if (MathErrno)
2909     CmdArgs.push_back("-fmath-errno");
2910
2911   // There are several flags which require disabling very specific
2912   // optimizations. Any of these being disabled forces us to turn off the
2913   // entire set of LLVM optimizations, so collect them through all the flag
2914   // madness.
2915   bool AssociativeMath = false;
2916   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2917                                options::OPT_fno_fast_math,
2918                                options::OPT_funsafe_math_optimizations,
2919                                options::OPT_fno_unsafe_math_optimizations,
2920                                options::OPT_fassociative_math,
2921                                options::OPT_fno_associative_math))
2922     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2923         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2924         A->getOption().getID() != options::OPT_fno_associative_math)
2925       AssociativeMath = true;
2926   bool ReciprocalMath = false;
2927   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2928                                options::OPT_fno_fast_math,
2929                                options::OPT_funsafe_math_optimizations,
2930                                options::OPT_fno_unsafe_math_optimizations,
2931                                options::OPT_freciprocal_math,
2932                                options::OPT_fno_reciprocal_math))
2933     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2934         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2935         A->getOption().getID() != options::OPT_fno_reciprocal_math)
2936       ReciprocalMath = true;
2937   bool SignedZeros = true;
2938   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2939                                options::OPT_fno_fast_math,
2940                                options::OPT_funsafe_math_optimizations,
2941                                options::OPT_fno_unsafe_math_optimizations,
2942                                options::OPT_fsigned_zeros,
2943                                options::OPT_fno_signed_zeros))
2944     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2945         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2946         A->getOption().getID() != options::OPT_fsigned_zeros)
2947       SignedZeros = false;
2948   bool TrappingMath = true;
2949   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2950                                options::OPT_fno_fast_math,
2951                                options::OPT_funsafe_math_optimizations,
2952                                options::OPT_fno_unsafe_math_optimizations,
2953                                options::OPT_ftrapping_math,
2954                                options::OPT_fno_trapping_math))
2955     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2956         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2957         A->getOption().getID() != options::OPT_ftrapping_math)
2958       TrappingMath = false;
2959   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2960       !TrappingMath)
2961     CmdArgs.push_back("-menable-unsafe-fp-math");
2962
2963
2964   // Validate and pass through -fp-contract option. 
2965   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2966                                options::OPT_fno_fast_math,
2967                                options::OPT_ffp_contract)) {
2968     if (A->getOption().getID() == options::OPT_ffp_contract) {
2969       StringRef Val = A->getValue();
2970       if (Val == "fast" || Val == "on" || Val == "off") {
2971         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
2972       } else {
2973         D.Diag(diag::err_drv_unsupported_option_argument)
2974           << A->getOption().getName() << Val;
2975       }
2976     } else if (A->getOption().matches(options::OPT_ffast_math) ||
2977                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
2978       // If fast-math is set then set the fp-contract mode to fast.
2979       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2980     }
2981   }
2982
2983   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
2984   // and if we find them, tell the frontend to provide the appropriate
2985   // preprocessor macros. This is distinct from enabling any optimizations as
2986   // these options induce language changes which must survive serialization
2987   // and deserialization, etc.
2988   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2989                                options::OPT_fno_fast_math))
2990       if (!A->getOption().matches(options::OPT_fno_fast_math))
2991         CmdArgs.push_back("-ffast-math");
2992   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
2993                                options::OPT_fno_fast_math))
2994     if (A->getOption().matches(options::OPT_ffinite_math_only))
2995       CmdArgs.push_back("-ffinite-math-only");
2996
2997   // Decide whether to use verbose asm. Verbose assembly is the default on
2998   // toolchains which have the integrated assembler on by default.
2999   bool IsIntegratedAssemblerDefault =
3000       getToolChain().IsIntegratedAssemblerDefault();
3001   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3002                    IsIntegratedAssemblerDefault) ||
3003       Args.hasArg(options::OPT_dA))
3004     CmdArgs.push_back("-masm-verbose");
3005
3006   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3007                     IsIntegratedAssemblerDefault))
3008     CmdArgs.push_back("-no-integrated-as");
3009
3010   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3011     CmdArgs.push_back("-mdebug-pass");
3012     CmdArgs.push_back("Structure");
3013   }
3014   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3015     CmdArgs.push_back("-mdebug-pass");
3016     CmdArgs.push_back("Arguments");
3017   }
3018
3019   // Enable -mconstructor-aliases except on darwin, where we have to
3020   // work around a linker bug;  see <rdar://problem/7651567>.
3021   if (!getToolChain().getTriple().isOSDarwin())
3022     CmdArgs.push_back("-mconstructor-aliases");
3023
3024   // Darwin's kernel doesn't support guard variables; just die if we
3025   // try to use them.
3026   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3027     CmdArgs.push_back("-fforbid-guard-variables");
3028
3029   if (Args.hasArg(options::OPT_mms_bitfields)) {
3030     CmdArgs.push_back("-mms-bitfields");
3031   }
3032
3033   // This is a coarse approximation of what llvm-gcc actually does, both
3034   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3035   // complicated ways.
3036   bool AsynchronousUnwindTables =
3037       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3038                    options::OPT_fno_asynchronous_unwind_tables,
3039                    (getToolChain().IsUnwindTablesDefault() ||
3040                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3041                        !KernelOrKext);
3042   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3043                    AsynchronousUnwindTables))
3044     CmdArgs.push_back("-munwind-tables");
3045
3046   getToolChain().addClangTargetOptions(Args, CmdArgs);
3047
3048   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3049     CmdArgs.push_back("-mlimit-float-precision");
3050     CmdArgs.push_back(A->getValue());
3051   }
3052
3053   // FIXME: Handle -mtune=.
3054   (void) Args.hasArg(options::OPT_mtune_EQ);
3055
3056   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3057     CmdArgs.push_back("-mcode-model");
3058     CmdArgs.push_back(A->getValue());
3059   }
3060
3061   // Add the target cpu
3062   std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3063   llvm::Triple ETriple(ETripleStr);
3064   std::string CPU = getCPUName(Args, ETriple);
3065   if (!CPU.empty()) {
3066     CmdArgs.push_back("-target-cpu");
3067     CmdArgs.push_back(Args.MakeArgString(CPU));
3068   }
3069
3070   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3071     CmdArgs.push_back("-mfpmath");
3072     CmdArgs.push_back(A->getValue());
3073   }
3074
3075   // Add the target features
3076   getTargetFeatures(D, ETriple, Args, CmdArgs, false);
3077
3078   // Add target specific flags.
3079   switch(getToolChain().getArch()) {
3080   default:
3081     break;
3082
3083   case llvm::Triple::arm:
3084   case llvm::Triple::armeb:
3085   case llvm::Triple::thumb:
3086   case llvm::Triple::thumbeb:
3087     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3088     break;
3089
3090   case llvm::Triple::aarch64:
3091   case llvm::Triple::aarch64_be:
3092     AddAArch64TargetArgs(Args, CmdArgs);
3093     break;
3094
3095   case llvm::Triple::mips:
3096   case llvm::Triple::mipsel:
3097   case llvm::Triple::mips64:
3098   case llvm::Triple::mips64el:
3099     AddMIPSTargetArgs(Args, CmdArgs);
3100     break;
3101
3102   case llvm::Triple::ppc:
3103   case llvm::Triple::ppc64:
3104   case llvm::Triple::ppc64le:
3105     AddPPCTargetArgs(Args, CmdArgs);
3106     break;
3107
3108   case llvm::Triple::sparc:
3109   case llvm::Triple::sparcv9:
3110     AddSparcTargetArgs(Args, CmdArgs);
3111     break;
3112
3113   case llvm::Triple::x86:
3114   case llvm::Triple::x86_64:
3115     AddX86TargetArgs(Args, CmdArgs);
3116     break;
3117
3118   case llvm::Triple::hexagon:
3119     AddHexagonTargetArgs(Args, CmdArgs);
3120     break;
3121   }
3122
3123   // Add clang-cl arguments.
3124   if (getToolChain().getDriver().IsCLMode())
3125     AddClangCLArgs(Args, CmdArgs);
3126
3127   // Pass the linker version in use.
3128   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3129     CmdArgs.push_back("-target-linker-version");
3130     CmdArgs.push_back(A->getValue());
3131   }
3132
3133   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3134     CmdArgs.push_back("-momit-leaf-frame-pointer");
3135
3136   // Explicitly error on some things we know we don't support and can't just
3137   // ignore.
3138   types::ID InputType = Inputs[0].getType();
3139   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3140     Arg *Unsupported;
3141     if (types::isCXX(InputType) &&
3142         getToolChain().getTriple().isOSDarwin() &&
3143         getToolChain().getArch() == llvm::Triple::x86) {
3144       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3145           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3146         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3147           << Unsupported->getOption().getName();
3148     }
3149   }
3150
3151   Args.AddAllArgs(CmdArgs, options::OPT_v);
3152   Args.AddLastArg(CmdArgs, options::OPT_H);
3153   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3154     CmdArgs.push_back("-header-include-file");
3155     CmdArgs.push_back(D.CCPrintHeadersFilename ?
3156                       D.CCPrintHeadersFilename : "-");
3157   }
3158   Args.AddLastArg(CmdArgs, options::OPT_P);
3159   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3160
3161   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3162     CmdArgs.push_back("-diagnostic-log-file");
3163     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
3164                       D.CCLogDiagnosticsFilename : "-");
3165   }
3166
3167   // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3168   // are preserved, all other debug options are substituted with "-g".
3169   Args.ClaimAllArgs(options::OPT_g_Group);
3170   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3171     if (A->getOption().matches(options::OPT_gline_tables_only) ||
3172         A->getOption().matches(options::OPT_g1)) {
3173       // FIXME: we should support specifying dwarf version with
3174       // -gline-tables-only.
3175       CmdArgs.push_back("-gline-tables-only");
3176       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3177       const llvm::Triple &Triple = getToolChain().getTriple();
3178       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3179           Triple.getOS() == llvm::Triple::FreeBSD ||
3180           Triple.getOS() == llvm::Triple::Solaris)
3181         CmdArgs.push_back("-gdwarf-2");
3182     } else if (A->getOption().matches(options::OPT_gdwarf_2))
3183       CmdArgs.push_back("-gdwarf-2");
3184     else if (A->getOption().matches(options::OPT_gdwarf_3))
3185       CmdArgs.push_back("-gdwarf-3");
3186     else if (A->getOption().matches(options::OPT_gdwarf_4))
3187       CmdArgs.push_back("-gdwarf-4");
3188     else if (!A->getOption().matches(options::OPT_g0) &&
3189              !A->getOption().matches(options::OPT_ggdb0)) {
3190       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3191       const llvm::Triple &Triple = getToolChain().getTriple();
3192       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3193           Triple.getOS() == llvm::Triple::FreeBSD ||
3194           Triple.getOS() == llvm::Triple::Solaris)
3195         CmdArgs.push_back("-gdwarf-2");
3196       else
3197         CmdArgs.push_back("-g");
3198     }
3199   }
3200
3201   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3202   Args.ClaimAllArgs(options::OPT_g_flags_Group);
3203   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3204                    /*Default*/ true))
3205     CmdArgs.push_back("-dwarf-column-info");
3206
3207   // FIXME: Move backend command line options to the module.
3208   // -gsplit-dwarf should turn on -g and enable the backend dwarf
3209   // splitting and extraction.
3210   // FIXME: Currently only works on Linux.
3211   if (getToolChain().getTriple().isOSLinux() &&
3212       Args.hasArg(options::OPT_gsplit_dwarf)) {
3213     CmdArgs.push_back("-g");
3214     CmdArgs.push_back("-backend-option");
3215     CmdArgs.push_back("-split-dwarf=Enable");
3216   }
3217
3218   // -ggnu-pubnames turns on gnu style pubnames in the backend.
3219   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3220     CmdArgs.push_back("-backend-option");
3221     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3222   }
3223
3224   // -gdwarf-aranges turns on the emission of the aranges section in the
3225   // backend.
3226   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3227     CmdArgs.push_back("-backend-option");
3228     CmdArgs.push_back("-generate-arange-section");
3229   }
3230
3231   if (Args.hasFlag(options::OPT_fdebug_types_section,
3232                    options::OPT_fno_debug_types_section, false)) {
3233     CmdArgs.push_back("-backend-option");
3234     CmdArgs.push_back("-generate-type-units");
3235   }
3236
3237   if (Args.hasFlag(options::OPT_ffunction_sections,
3238                    options::OPT_fno_function_sections, false)) {
3239     CmdArgs.push_back("-ffunction-sections");
3240   }
3241
3242   if (Args.hasFlag(options::OPT_fdata_sections,
3243                    options::OPT_fno_data_sections, false)) {
3244     CmdArgs.push_back("-fdata-sections");
3245   }
3246
3247   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3248
3249   if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
3250       (Args.hasArg(options::OPT_fprofile_instr_use) ||
3251        Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
3252     D.Diag(diag::err_drv_argument_not_allowed_with)
3253       << "-fprofile-instr-generate" << "-fprofile-instr-use";
3254
3255   Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3256
3257   if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
3258     A->render(Args, CmdArgs);
3259   else if (Args.hasArg(options::OPT_fprofile_instr_use))
3260     CmdArgs.push_back("-fprofile-instr-use=pgo-data");
3261
3262   if (Args.hasArg(options::OPT_ftest_coverage) ||
3263       Args.hasArg(options::OPT_coverage))
3264     CmdArgs.push_back("-femit-coverage-notes");
3265   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3266                    false) ||
3267       Args.hasArg(options::OPT_coverage))
3268     CmdArgs.push_back("-femit-coverage-data");
3269
3270   if (Args.hasArg(options::OPT_fcoverage_mapping) &&
3271       !Args.hasArg(options::OPT_fprofile_instr_generate))
3272     D.Diag(diag::err_drv_argument_only_allowed_with)
3273       << "-fcoverage-mapping" << "-fprofile-instr-generate";
3274
3275   if (Args.hasArg(options::OPT_fcoverage_mapping))
3276     CmdArgs.push_back("-fcoverage-mapping");
3277
3278   if (C.getArgs().hasArg(options::OPT_c) ||
3279       C.getArgs().hasArg(options::OPT_S)) {
3280     if (Output.isFilename()) {
3281       CmdArgs.push_back("-coverage-file");
3282       SmallString<128> CoverageFilename;
3283       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3284         CoverageFilename = FinalOutput->getValue();
3285       } else {
3286         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3287       }
3288       if (llvm::sys::path::is_relative(CoverageFilename.str())) {
3289         SmallString<128> Pwd;
3290         if (!llvm::sys::fs::current_path(Pwd)) {
3291           llvm::sys::path::append(Pwd, CoverageFilename.str());
3292           CoverageFilename.swap(Pwd);
3293         }
3294       }
3295       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3296     }
3297   }
3298
3299   // Pass options for controlling the default header search paths.
3300   if (Args.hasArg(options::OPT_nostdinc)) {
3301     CmdArgs.push_back("-nostdsysteminc");
3302     CmdArgs.push_back("-nobuiltininc");
3303   } else {
3304     if (Args.hasArg(options::OPT_nostdlibinc))
3305         CmdArgs.push_back("-nostdsysteminc");
3306     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3307     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3308   }
3309
3310   // Pass the path to compiler resource files.
3311   CmdArgs.push_back("-resource-dir");
3312   CmdArgs.push_back(D.ResourceDir.c_str());
3313
3314   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3315
3316   bool ARCMTEnabled = false;
3317   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3318     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3319                                        options::OPT_ccc_arcmt_modify,
3320                                        options::OPT_ccc_arcmt_migrate)) {
3321       ARCMTEnabled = true;
3322       switch (A->getOption().getID()) {
3323       default:
3324         llvm_unreachable("missed a case");
3325       case options::OPT_ccc_arcmt_check:
3326         CmdArgs.push_back("-arcmt-check");
3327         break;
3328       case options::OPT_ccc_arcmt_modify:
3329         CmdArgs.push_back("-arcmt-modify");
3330         break;
3331       case options::OPT_ccc_arcmt_migrate:
3332         CmdArgs.push_back("-arcmt-migrate");
3333         CmdArgs.push_back("-mt-migrate-directory");
3334         CmdArgs.push_back(A->getValue());
3335
3336         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3337         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3338         break;
3339       }
3340     }
3341   } else {
3342     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3343     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3344     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3345   }
3346
3347   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3348     if (ARCMTEnabled) {
3349       D.Diag(diag::err_drv_argument_not_allowed_with)
3350         << A->getAsString(Args) << "-ccc-arcmt-migrate";
3351     }
3352     CmdArgs.push_back("-mt-migrate-directory");
3353     CmdArgs.push_back(A->getValue());
3354
3355     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3356                      options::OPT_objcmt_migrate_subscripting,
3357                      options::OPT_objcmt_migrate_property)) {
3358       // None specified, means enable them all.
3359       CmdArgs.push_back("-objcmt-migrate-literals");
3360       CmdArgs.push_back("-objcmt-migrate-subscripting");
3361       CmdArgs.push_back("-objcmt-migrate-property");
3362     } else {
3363       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3364       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3365       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3366     }
3367   } else {
3368     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3369     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3370     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3371     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3372     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3373     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3374     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3375     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3376     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3377     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3378     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3379     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3380     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3381     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3382     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3383   }
3384
3385   // Add preprocessing options like -I, -D, etc. if we are using the
3386   // preprocessor.
3387   //
3388   // FIXME: Support -fpreprocessed
3389   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3390     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3391
3392   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3393   // that "The compiler can only warn and ignore the option if not recognized".
3394   // When building with ccache, it will pass -D options to clang even on
3395   // preprocessed inputs and configure concludes that -fPIC is not supported.
3396   Args.ClaimAllArgs(options::OPT_D);
3397
3398   // Manually translate -O4 to -O3; let clang reject others.
3399   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3400     if (A->getOption().matches(options::OPT_O4)) {
3401       CmdArgs.push_back("-O3");
3402       D.Diag(diag::warn_O4_is_O3);
3403     } else {
3404       A->render(Args, CmdArgs);
3405     }
3406   }
3407
3408   // Warn about ignored options to clang.
3409   for (arg_iterator it = Args.filtered_begin(
3410        options::OPT_clang_ignored_gcc_optimization_f_Group),
3411        ie = Args.filtered_end(); it != ie; ++it) {
3412     D.Diag(diag::warn_ignored_gcc_optimization) << (*it)->getAsString(Args);
3413   }
3414
3415   claimNoWarnArgs(Args);
3416
3417   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3418   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3419   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3420     CmdArgs.push_back("-pedantic");
3421   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3422   Args.AddLastArg(CmdArgs, options::OPT_w);
3423
3424   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3425   // (-ansi is equivalent to -std=c89 or -std=c++98).
3426   //
3427   // If a std is supplied, only add -trigraphs if it follows the
3428   // option.
3429   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3430     if (Std->getOption().matches(options::OPT_ansi))
3431       if (types::isCXX(InputType))
3432         CmdArgs.push_back("-std=c++98");
3433       else
3434         CmdArgs.push_back("-std=c89");
3435     else
3436       Std->render(Args, CmdArgs);
3437
3438     // If -f(no-)trigraphs appears after the language standard flag, honor it.
3439     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3440                                  options::OPT_ftrigraphs,
3441                                  options::OPT_fno_trigraphs))
3442       if (A != Std)
3443         A->render(Args, CmdArgs);
3444   } else {
3445     // Honor -std-default.
3446     //
3447     // FIXME: Clang doesn't correctly handle -std= when the input language
3448     // doesn't match. For the time being just ignore this for C++ inputs;
3449     // eventually we want to do all the standard defaulting here instead of
3450     // splitting it between the driver and clang -cc1.
3451     if (!types::isCXX(InputType))
3452       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3453                                 "-std=", /*Joined=*/true);
3454     else if (IsWindowsMSVC)
3455       CmdArgs.push_back("-std=c++11");
3456
3457     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3458                     options::OPT_fno_trigraphs);
3459   }
3460
3461   // GCC's behavior for -Wwrite-strings is a bit strange:
3462   //  * In C, this "warning flag" changes the types of string literals from
3463   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3464   //    for the discarded qualifier.
3465   //  * In C++, this is just a normal warning flag.
3466   //
3467   // Implementing this warning correctly in C is hard, so we follow GCC's
3468   // behavior for now. FIXME: Directly diagnose uses of a string literal as
3469   // a non-const char* in C, rather than using this crude hack.
3470   if (!types::isCXX(InputType)) {
3471     // FIXME: This should behave just like a warning flag, and thus should also
3472     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3473     Arg *WriteStrings =
3474         Args.getLastArg(options::OPT_Wwrite_strings,
3475                         options::OPT_Wno_write_strings, options::OPT_w);
3476     if (WriteStrings &&
3477         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3478       CmdArgs.push_back("-fconst-strings");
3479   }
3480
3481   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3482   // during C++ compilation, which it is by default. GCC keeps this define even
3483   // in the presence of '-w', match this behavior bug-for-bug.
3484   if (types::isCXX(InputType) &&
3485       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3486                    true)) {
3487     CmdArgs.push_back("-fdeprecated-macro");
3488   }
3489
3490   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3491   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3492     if (Asm->getOption().matches(options::OPT_fasm))
3493       CmdArgs.push_back("-fgnu-keywords");
3494     else
3495       CmdArgs.push_back("-fno-gnu-keywords");
3496   }
3497
3498   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3499     CmdArgs.push_back("-fno-dwarf-directory-asm");
3500
3501   if (ShouldDisableAutolink(Args, getToolChain()))
3502     CmdArgs.push_back("-fno-autolink");
3503
3504   // Add in -fdebug-compilation-dir if necessary.
3505   addDebugCompDirArg(Args, CmdArgs);
3506
3507   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3508                                options::OPT_ftemplate_depth_EQ)) {
3509     CmdArgs.push_back("-ftemplate-depth");
3510     CmdArgs.push_back(A->getValue());
3511   }
3512
3513   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3514     CmdArgs.push_back("-foperator-arrow-depth");
3515     CmdArgs.push_back(A->getValue());
3516   }
3517
3518   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3519     CmdArgs.push_back("-fconstexpr-depth");
3520     CmdArgs.push_back(A->getValue());
3521   }
3522
3523   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3524     CmdArgs.push_back("-fconstexpr-steps");
3525     CmdArgs.push_back(A->getValue());
3526   }
3527
3528   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3529     CmdArgs.push_back("-fbracket-depth");
3530     CmdArgs.push_back(A->getValue());
3531   }
3532
3533   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3534                                options::OPT_Wlarge_by_value_copy_def)) {
3535     if (A->getNumValues()) {
3536       StringRef bytes = A->getValue();
3537       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3538     } else
3539       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3540   }
3541
3542
3543   if (Args.hasArg(options::OPT_relocatable_pch))
3544     CmdArgs.push_back("-relocatable-pch");
3545
3546   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3547     CmdArgs.push_back("-fconstant-string-class");
3548     CmdArgs.push_back(A->getValue());
3549   }
3550
3551   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3552     CmdArgs.push_back("-ftabstop");
3553     CmdArgs.push_back(A->getValue());
3554   }
3555
3556   CmdArgs.push_back("-ferror-limit");
3557   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3558     CmdArgs.push_back(A->getValue());
3559   else
3560     CmdArgs.push_back("19");
3561
3562   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3563     CmdArgs.push_back("-fmacro-backtrace-limit");
3564     CmdArgs.push_back(A->getValue());
3565   }
3566
3567   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3568     CmdArgs.push_back("-ftemplate-backtrace-limit");
3569     CmdArgs.push_back(A->getValue());
3570   }
3571
3572   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3573     CmdArgs.push_back("-fconstexpr-backtrace-limit");
3574     CmdArgs.push_back(A->getValue());
3575   }
3576
3577   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3578     CmdArgs.push_back("-fspell-checking-limit");
3579     CmdArgs.push_back(A->getValue());
3580   }
3581
3582   // Pass -fmessage-length=.
3583   CmdArgs.push_back("-fmessage-length");
3584   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3585     CmdArgs.push_back(A->getValue());
3586   } else {
3587     // If -fmessage-length=N was not specified, determine whether this is a
3588     // terminal and, if so, implicitly define -fmessage-length appropriately.
3589     unsigned N = llvm::sys::Process::StandardErrColumns();
3590     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3591   }
3592
3593   // -fvisibility= and -fvisibility-ms-compat are of a piece.
3594   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3595                                      options::OPT_fvisibility_ms_compat)) {
3596     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3597       CmdArgs.push_back("-fvisibility");
3598       CmdArgs.push_back(A->getValue());
3599     } else {
3600       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3601       CmdArgs.push_back("-fvisibility");
3602       CmdArgs.push_back("hidden");
3603       CmdArgs.push_back("-ftype-visibility");
3604       CmdArgs.push_back("default");
3605     }
3606   }
3607
3608   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3609
3610   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3611
3612   // -fhosted is default.
3613   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3614       KernelOrKext)
3615     CmdArgs.push_back("-ffreestanding");
3616
3617   // Forward -f (flag) options which we can pass directly.
3618   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3619   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3620   Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
3621   Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
3622   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3623   // AltiVec language extensions aren't relevant for assembling.
3624   if (!isa<PreprocessJobAction>(JA) || 
3625       Output.getType() != types::TY_PP_Asm)
3626     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3627   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3628   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3629
3630   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3631   Sanitize.addArgs(Args, CmdArgs);
3632
3633   // Report an error for -faltivec on anything other than PowerPC.
3634   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
3635     if (!(getToolChain().getArch() == llvm::Triple::ppc ||
3636           getToolChain().getArch() == llvm::Triple::ppc64 ||
3637           getToolChain().getArch() == llvm::Triple::ppc64le))
3638       D.Diag(diag::err_drv_argument_only_allowed_with)
3639         << A->getAsString(Args) << "ppc/ppc64/ppc64le";
3640
3641   if (getToolChain().SupportsProfiling())
3642     Args.AddLastArg(CmdArgs, options::OPT_pg);
3643
3644   // -flax-vector-conversions is default.
3645   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3646                     options::OPT_fno_lax_vector_conversions))
3647     CmdArgs.push_back("-fno-lax-vector-conversions");
3648
3649   if (Args.getLastArg(options::OPT_fapple_kext))
3650     CmdArgs.push_back("-fapple-kext");
3651
3652   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3653   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3654   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3655   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3656   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3657
3658   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3659     CmdArgs.push_back("-ftrapv-handler");
3660     CmdArgs.push_back(A->getValue());
3661   }
3662
3663   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3664
3665   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3666   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3667   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
3668                                options::OPT_fno_wrapv)) {
3669     if (A->getOption().matches(options::OPT_fwrapv))
3670       CmdArgs.push_back("-fwrapv");
3671   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3672                                       options::OPT_fno_strict_overflow)) {
3673     if (A->getOption().matches(options::OPT_fno_strict_overflow))
3674       CmdArgs.push_back("-fwrapv");
3675   }
3676
3677   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3678                                options::OPT_fno_reroll_loops))
3679     if (A->getOption().matches(options::OPT_freroll_loops))
3680       CmdArgs.push_back("-freroll-loops");
3681
3682   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3683   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3684                   options::OPT_fno_unroll_loops);
3685
3686   Args.AddLastArg(CmdArgs, options::OPT_pthread);
3687
3688
3689   // -stack-protector=0 is default.
3690   unsigned StackProtectorLevel = 0;
3691   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3692                                options::OPT_fstack_protector_all,
3693                                options::OPT_fstack_protector_strong,
3694                                options::OPT_fstack_protector)) {
3695     if (A->getOption().matches(options::OPT_fstack_protector)) {
3696       StackProtectorLevel = std::max<unsigned>(LangOptions::SSPOn,
3697         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3698     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3699       StackProtectorLevel = LangOptions::SSPStrong;
3700     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3701       StackProtectorLevel = LangOptions::SSPReq;
3702   } else {
3703     StackProtectorLevel =
3704       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3705   }
3706   if (StackProtectorLevel) {
3707     CmdArgs.push_back("-stack-protector");
3708     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3709   }
3710
3711   // --param ssp-buffer-size=
3712   for (arg_iterator it = Args.filtered_begin(options::OPT__param),
3713        ie = Args.filtered_end(); it != ie; ++it) {
3714     StringRef Str((*it)->getValue());
3715     if (Str.startswith("ssp-buffer-size=")) {
3716       if (StackProtectorLevel) {
3717         CmdArgs.push_back("-stack-protector-buffer-size");
3718         // FIXME: Verify the argument is a valid integer.
3719         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3720       }
3721       (*it)->claim();
3722     }
3723   }
3724
3725   // Translate -mstackrealign
3726   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3727                    false)) {
3728     CmdArgs.push_back("-backend-option");
3729     CmdArgs.push_back("-force-align-stack");
3730   }
3731   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
3732                    false)) {
3733     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3734   }
3735
3736   if (Args.hasArg(options::OPT_mstack_alignment)) {
3737     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3738     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3739   }
3740
3741   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
3742       getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be)
3743     CmdArgs.push_back("-fallow-half-arguments-and-returns");
3744
3745   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3746                                options::OPT_mno_restrict_it)) {
3747     if (A->getOption().matches(options::OPT_mrestrict_it)) {
3748       CmdArgs.push_back("-backend-option");
3749       CmdArgs.push_back("-arm-restrict-it");
3750     } else {
3751       CmdArgs.push_back("-backend-option");
3752       CmdArgs.push_back("-arm-no-restrict-it");
3753     }
3754   } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
3755                                   TT.getArch() == llvm::Triple::thumb)) {
3756     // Windows on ARM expects restricted IT blocks
3757     CmdArgs.push_back("-backend-option");
3758     CmdArgs.push_back("-arm-restrict-it");
3759   }
3760
3761   if (TT.getArch() == llvm::Triple::arm ||
3762       TT.getArch() == llvm::Triple::thumb) {
3763     if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
3764                                  options::OPT_mno_long_calls)) {
3765       if (A->getOption().matches(options::OPT_mlong_calls)) {
3766         CmdArgs.push_back("-backend-option");
3767         CmdArgs.push_back("-arm-long-calls");
3768       }
3769     }
3770   }
3771
3772   // Forward -f options with positive and negative forms; we translate
3773   // these by hand.
3774   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
3775     StringRef fname = A->getValue();
3776     if (!llvm::sys::fs::exists(fname))
3777       D.Diag(diag::err_drv_no_such_file) << fname;
3778     else
3779       A->render(Args, CmdArgs);
3780   }
3781
3782   if (Args.hasArg(options::OPT_mkernel)) {
3783     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
3784       CmdArgs.push_back("-fapple-kext");
3785     if (!Args.hasArg(options::OPT_fbuiltin))
3786       CmdArgs.push_back("-fno-builtin");
3787     Args.ClaimAllArgs(options::OPT_fno_builtin);
3788   }
3789   // -fbuiltin is default.
3790   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
3791     CmdArgs.push_back("-fno-builtin");
3792
3793   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3794                     options::OPT_fno_assume_sane_operator_new))
3795     CmdArgs.push_back("-fno-assume-sane-operator-new");
3796
3797   // -fblocks=0 is default.
3798   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3799                    getToolChain().IsBlocksDefault()) ||
3800         (Args.hasArg(options::OPT_fgnu_runtime) &&
3801          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3802          !Args.hasArg(options::OPT_fno_blocks))) {
3803     CmdArgs.push_back("-fblocks");
3804
3805     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
3806         !getToolChain().hasBlocksRuntime())
3807       CmdArgs.push_back("-fblocks-runtime-optional");
3808   }
3809
3810   // -fmodules enables modules (off by default).
3811   // Users can pass -fno-cxx-modules to turn off modules support for
3812   // C++/Objective-C++ programs, which is a little less mature.
3813   bool HaveModules = false;
3814   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3815     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
3816                                      options::OPT_fno_cxx_modules, 
3817                                      true);
3818     if (AllowedInCXX || !types::isCXX(InputType)) {
3819       CmdArgs.push_back("-fmodules");
3820       HaveModules = true;
3821     }
3822   }
3823
3824   // -fmodule-maps enables module map processing (off by default) for header
3825   // checking.  It is implied by -fmodules.
3826   if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
3827                    false)) {
3828     CmdArgs.push_back("-fmodule-maps");
3829   }
3830
3831   // -fmodules-decluse checks that modules used are declared so (off by
3832   // default).
3833   if (Args.hasFlag(options::OPT_fmodules_decluse,
3834                    options::OPT_fno_modules_decluse,
3835                    false)) {
3836     CmdArgs.push_back("-fmodules-decluse");
3837   }
3838
3839   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3840   // all #included headers are part of modules.
3841   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3842                    options::OPT_fno_modules_strict_decluse,
3843                    false)) {
3844     CmdArgs.push_back("-fmodules-strict-decluse");
3845   }
3846
3847   // -fmodule-name specifies the module that is currently being built (or
3848   // used for header checking by -fmodule-maps).
3849   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
3850
3851   // -fmodule-map-file can be used to specify files containing module
3852   // definitions.
3853   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3854
3855   // -fmodule-file can be used to specify files containing precompiled modules.
3856   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3857
3858   // -fmodule-cache-path specifies where our implicitly-built module files
3859   // should be written.
3860   SmallString<128> ModuleCachePath;
3861   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3862     ModuleCachePath = A->getValue();
3863   if (HaveModules) {
3864     if (C.isForDiagnostics()) {
3865       // When generating crash reports, we want to emit the modules along with
3866       // the reproduction sources, so we ignore any provided module path.
3867       ModuleCachePath = Output.getFilename();
3868       llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
3869       llvm::sys::path::append(ModuleCachePath, "modules");
3870     } else if (ModuleCachePath.empty()) {
3871       // No module path was provided: use the default.
3872       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
3873                                              ModuleCachePath);
3874       llvm::sys::path::append(ModuleCachePath, "org.llvm.clang");
3875       llvm::sys::path::append(ModuleCachePath, "ModuleCache");
3876     }
3877     const char Arg[] = "-fmodules-cache-path=";
3878     ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
3879     CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
3880   }
3881
3882   // When building modules and generating crashdumps, we need to dump a module
3883   // dependency VFS alongside the output.
3884   if (HaveModules && C.isForDiagnostics()) {
3885     SmallString<128> VFSDir(Output.getFilename());
3886     llvm::sys::path::replace_extension(VFSDir, ".cache");
3887     // Add the cache directory as a temp so the crash diagnostics pick it up.
3888     C.addTempFile(Args.MakeArgString(VFSDir));
3889
3890     llvm::sys::path::append(VFSDir, "vfs");
3891     CmdArgs.push_back("-module-dependency-dir");
3892     CmdArgs.push_back(Args.MakeArgString(VFSDir));
3893   }
3894
3895   if (HaveModules)
3896     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3897
3898   // Pass through all -fmodules-ignore-macro arguments.
3899   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3900   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3901   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3902
3903   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3904
3905   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3906     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3907       D.Diag(diag::err_drv_argument_not_allowed_with)
3908           << A->getAsString(Args) << "-fbuild-session-timestamp";
3909
3910     llvm::sys::fs::file_status Status;
3911     if (llvm::sys::fs::status(A->getValue(), Status))
3912       D.Diag(diag::err_drv_no_such_file) << A->getValue();
3913     char TimeStamp[48];
3914     snprintf(TimeStamp, sizeof(TimeStamp), "-fbuild-session-timestamp=%" PRIu64,
3915              (uint64_t)Status.getLastModificationTime().toEpochTime());
3916     CmdArgs.push_back(Args.MakeArgString(TimeStamp));
3917   }
3918
3919   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3920     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3921                          options::OPT_fbuild_session_file))
3922       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3923
3924     Args.AddLastArg(CmdArgs,
3925                     options::OPT_fmodules_validate_once_per_build_session);
3926   }
3927
3928   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3929
3930   // -faccess-control is default.
3931   if (Args.hasFlag(options::OPT_fno_access_control,
3932                    options::OPT_faccess_control,
3933                    false))
3934     CmdArgs.push_back("-fno-access-control");
3935
3936   // -felide-constructors is the default.
3937   if (Args.hasFlag(options::OPT_fno_elide_constructors,
3938                    options::OPT_felide_constructors,
3939                    false))
3940     CmdArgs.push_back("-fno-elide-constructors");
3941
3942   // -frtti is default.
3943   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
3944       KernelOrKext) {
3945     CmdArgs.push_back("-fno-rtti");
3946
3947     // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
3948     if (Sanitize.sanitizesVptr()) {
3949       std::string NoRttiArg =
3950         Args.getLastArg(options::OPT_mkernel,
3951                         options::OPT_fapple_kext,
3952                         options::OPT_fno_rtti)->getAsString(Args);
3953       D.Diag(diag::err_drv_argument_not_allowed_with)
3954         << "-fsanitize=vptr" << NoRttiArg;
3955     }
3956   }
3957
3958   // -fshort-enums=0 is default for all architectures except Hexagon.
3959   if (Args.hasFlag(options::OPT_fshort_enums,
3960                    options::OPT_fno_short_enums,
3961                    getToolChain().getArch() ==
3962                    llvm::Triple::hexagon))
3963     CmdArgs.push_back("-fshort-enums");
3964
3965   // -fsigned-char is default.
3966   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
3967                     isSignedCharDefault(getToolChain().getTriple())))
3968     CmdArgs.push_back("-fno-signed-char");
3969
3970   // -fthreadsafe-static is default.
3971   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3972                     options::OPT_fno_threadsafe_statics))
3973     CmdArgs.push_back("-fno-threadsafe-statics");
3974
3975   // -fuse-cxa-atexit is default.
3976   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
3977                     options::OPT_fno_use_cxa_atexit,
3978                     !IsWindowsCygnus && !IsWindowsGNU &&
3979                     getToolChain().getArch() != llvm::Triple::hexagon &&
3980                     getToolChain().getArch() != llvm::Triple::xcore) ||
3981       KernelOrKext)
3982     CmdArgs.push_back("-fno-use-cxa-atexit");
3983
3984   // -fms-extensions=0 is default.
3985   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3986                    IsWindowsMSVC))
3987     CmdArgs.push_back("-fms-extensions");
3988
3989   // -fms-compatibility=0 is default.
3990   if (Args.hasFlag(options::OPT_fms_compatibility, 
3991                    options::OPT_fno_ms_compatibility,
3992                    (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
3993                                                   options::OPT_fno_ms_extensions,
3994                                                   true))))
3995     CmdArgs.push_back("-fms-compatibility");
3996
3997   // -fms-compatibility-version=17.00 is default.
3998   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3999                    IsWindowsMSVC) || Args.hasArg(options::OPT_fmsc_version) ||
4000       Args.hasArg(options::OPT_fms_compatibility_version)) {
4001     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
4002     const Arg *MSCompatibilityVersion =
4003       Args.getLastArg(options::OPT_fms_compatibility_version);
4004
4005     if (MSCVersion && MSCompatibilityVersion)
4006       D.Diag(diag::err_drv_argument_not_allowed_with)
4007           << MSCVersion->getAsString(Args)
4008           << MSCompatibilityVersion->getAsString(Args);
4009
4010     std::string Ver;
4011     if (MSCompatibilityVersion)
4012       Ver = Args.getLastArgValue(options::OPT_fms_compatibility_version);
4013     else if (MSCVersion)
4014       Ver = getMSCompatibilityVersion(MSCVersion->getValue());
4015
4016     if (Ver.empty())
4017       CmdArgs.push_back("-fms-compatibility-version=17.00");
4018     else
4019       CmdArgs.push_back(Args.MakeArgString("-fms-compatibility-version=" + Ver));
4020   }
4021
4022   // -fno-borland-extensions is default.
4023   if (Args.hasFlag(options::OPT_fborland_extensions,
4024                    options::OPT_fno_borland_extensions, false))
4025     CmdArgs.push_back("-fborland-extensions");
4026
4027   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4028   // needs it.
4029   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4030                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4031     CmdArgs.push_back("-fdelayed-template-parsing");
4032
4033   // -fgnu-keywords default varies depending on language; only pass if
4034   // specified.
4035   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4036                                options::OPT_fno_gnu_keywords))
4037     A->render(Args, CmdArgs);
4038
4039   if (Args.hasFlag(options::OPT_fgnu89_inline,
4040                    options::OPT_fno_gnu89_inline,
4041                    false))
4042     CmdArgs.push_back("-fgnu89-inline");
4043
4044   if (Args.hasArg(options::OPT_fno_inline))
4045     CmdArgs.push_back("-fno-inline");
4046
4047   if (Args.hasArg(options::OPT_fno_inline_functions))
4048     CmdArgs.push_back("-fno-inline-functions");
4049
4050   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4051
4052   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4053   // legacy is the default. Except for deployment taget of 10.5,
4054   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4055   // gets ignored silently.
4056   if (objcRuntime.isNonFragile()) {
4057     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4058                       options::OPT_fno_objc_legacy_dispatch,
4059                       objcRuntime.isLegacyDispatchDefaultForArch(
4060                         getToolChain().getArch()))) {
4061       if (getToolChain().UseObjCMixedDispatch())
4062         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4063       else
4064         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4065     }
4066   }
4067
4068   // When ObjectiveC legacy runtime is in effect on MacOSX,
4069   // turn on the option to do Array/Dictionary subscripting
4070   // by default.
4071   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
4072       getToolChain().getTriple().isMacOSX() &&
4073       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4074       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4075       objcRuntime.isNeXTFamily())
4076     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4077   
4078   // -fencode-extended-block-signature=1 is default.
4079   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4080     CmdArgs.push_back("-fencode-extended-block-signature");
4081   }
4082   
4083   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4084   // NOTE: This logic is duplicated in ToolChains.cpp.
4085   bool ARC = isObjCAutoRefCount(Args);
4086   if (ARC) {
4087     getToolChain().CheckObjCARC();
4088
4089     CmdArgs.push_back("-fobjc-arc");
4090
4091     // FIXME: It seems like this entire block, and several around it should be
4092     // wrapped in isObjC, but for now we just use it here as this is where it
4093     // was being used previously.
4094     if (types::isCXX(InputType) && types::isObjC(InputType)) {
4095       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4096         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4097       else
4098         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4099     }
4100
4101     // Allow the user to enable full exceptions code emission.
4102     // We define off for Objective-CC, on for Objective-C++.
4103     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4104                      options::OPT_fno_objc_arc_exceptions,
4105                      /*default*/ types::isCXX(InputType)))
4106       CmdArgs.push_back("-fobjc-arc-exceptions");
4107   }
4108
4109   // -fobjc-infer-related-result-type is the default, except in the Objective-C
4110   // rewriter.
4111   if (rewriteKind != RK_None)
4112     CmdArgs.push_back("-fno-objc-infer-related-result-type");
4113
4114   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4115   // takes precedence.
4116   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4117   if (!GCArg)
4118     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4119   if (GCArg) {
4120     if (ARC) {
4121       D.Diag(diag::err_drv_objc_gc_arr)
4122         << GCArg->getAsString(Args);
4123     } else if (getToolChain().SupportsObjCGC()) {
4124       GCArg->render(Args, CmdArgs);
4125     } else {
4126       // FIXME: We should move this to a hard error.
4127       D.Diag(diag::warn_drv_objc_gc_unsupported)
4128         << GCArg->getAsString(Args);
4129     }
4130   }
4131
4132   // Handle GCC-style exception args.
4133   if (!C.getDriver().IsCLMode())
4134     addExceptionArgs(Args, InputType, getToolChain().getTriple(), KernelOrKext,
4135                      objcRuntime, CmdArgs);
4136
4137   if (getToolChain().UseSjLjExceptions())
4138     CmdArgs.push_back("-fsjlj-exceptions");
4139
4140   // C++ "sane" operator new.
4141   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4142                     options::OPT_fno_assume_sane_operator_new))
4143     CmdArgs.push_back("-fno-assume-sane-operator-new");
4144
4145   // -fconstant-cfstrings is default, and may be subject to argument translation
4146   // on Darwin.
4147   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4148                     options::OPT_fno_constant_cfstrings) ||
4149       !Args.hasFlag(options::OPT_mconstant_cfstrings,
4150                     options::OPT_mno_constant_cfstrings))
4151     CmdArgs.push_back("-fno-constant-cfstrings");
4152
4153   // -fshort-wchar default varies depending on platform; only
4154   // pass if specified.
4155   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4156                                options::OPT_fno_short_wchar))
4157     A->render(Args, CmdArgs);
4158
4159   // -fno-pascal-strings is default, only pass non-default.
4160   if (Args.hasFlag(options::OPT_fpascal_strings,
4161                    options::OPT_fno_pascal_strings,
4162                    false))
4163     CmdArgs.push_back("-fpascal-strings");
4164
4165   // Honor -fpack-struct= and -fpack-struct, if given. Note that
4166   // -fno-pack-struct doesn't apply to -fpack-struct=.
4167   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4168     std::string PackStructStr = "-fpack-struct=";
4169     PackStructStr += A->getValue();
4170     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4171   } else if (Args.hasFlag(options::OPT_fpack_struct,
4172                           options::OPT_fno_pack_struct, false)) {
4173     CmdArgs.push_back("-fpack-struct=1");
4174   }
4175
4176   // Handle -fmax-type-align=N and -fno-type-align
4177   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4178   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4179     if (!SkipMaxTypeAlign) {
4180       std::string MaxTypeAlignStr = "-fmax-type-align=";
4181       MaxTypeAlignStr += A->getValue();
4182       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4183     }
4184   } else if (getToolChain().getTriple().isOSDarwin()) {
4185     if (!SkipMaxTypeAlign) {
4186       std::string MaxTypeAlignStr = "-fmax-type-align=16";
4187       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4188     }
4189   }
4190
4191   if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4192     if (!Args.hasArg(options::OPT_fcommon))
4193       CmdArgs.push_back("-fno-common");
4194     Args.ClaimAllArgs(options::OPT_fno_common);
4195   }
4196
4197   // -fcommon is default, only pass non-default.
4198   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4199     CmdArgs.push_back("-fno-common");
4200
4201   // -fsigned-bitfields is default, and clang doesn't yet support
4202   // -funsigned-bitfields.
4203   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4204                     options::OPT_funsigned_bitfields))
4205     D.Diag(diag::warn_drv_clang_unsupported)
4206       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4207
4208   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4209   if (!Args.hasFlag(options::OPT_ffor_scope,
4210                     options::OPT_fno_for_scope))
4211     D.Diag(diag::err_drv_clang_unsupported)
4212       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4213
4214   // -finput_charset=UTF-8 is default. Reject others
4215   if (Arg *inputCharset = Args.getLastArg(
4216           options::OPT_finput_charset_EQ)) {
4217       StringRef value = inputCharset->getValue();
4218       if (value != "UTF-8")
4219           D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) << value;
4220   }
4221
4222   // -fexec_charset=UTF-8 is default. Reject others
4223   if (Arg *execCharset = Args.getLastArg(
4224           options::OPT_fexec_charset_EQ)) {
4225       StringRef value = execCharset->getValue();
4226       if (value != "UTF-8")
4227           D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) << value;
4228   }
4229
4230   // -fcaret-diagnostics is default.
4231   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4232                     options::OPT_fno_caret_diagnostics, true))
4233     CmdArgs.push_back("-fno-caret-diagnostics");
4234
4235   // -fdiagnostics-fixit-info is default, only pass non-default.
4236   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4237                     options::OPT_fno_diagnostics_fixit_info))
4238     CmdArgs.push_back("-fno-diagnostics-fixit-info");
4239
4240   // Enable -fdiagnostics-show-option by default.
4241   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4242                    options::OPT_fno_diagnostics_show_option))
4243     CmdArgs.push_back("-fdiagnostics-show-option");
4244
4245   if (const Arg *A =
4246         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4247     CmdArgs.push_back("-fdiagnostics-show-category");
4248     CmdArgs.push_back(A->getValue());
4249   }
4250
4251   if (const Arg *A =
4252         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4253     CmdArgs.push_back("-fdiagnostics-format");
4254     CmdArgs.push_back(A->getValue());
4255   }
4256
4257   if (Arg *A = Args.getLastArg(
4258       options::OPT_fdiagnostics_show_note_include_stack,
4259       options::OPT_fno_diagnostics_show_note_include_stack)) {
4260     if (A->getOption().matches(
4261         options::OPT_fdiagnostics_show_note_include_stack))
4262       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4263     else
4264       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4265   }
4266
4267   // Color diagnostics are the default, unless the terminal doesn't support
4268   // them.
4269   // Support both clang's -f[no-]color-diagnostics and gcc's
4270   // -f[no-]diagnostics-colors[=never|always|auto].
4271   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4272   for (const auto &Arg : Args) {
4273     const Option &O = Arg->getOption();
4274     if (!O.matches(options::OPT_fcolor_diagnostics) &&
4275         !O.matches(options::OPT_fdiagnostics_color) &&
4276         !O.matches(options::OPT_fno_color_diagnostics) &&
4277         !O.matches(options::OPT_fno_diagnostics_color) &&
4278         !O.matches(options::OPT_fdiagnostics_color_EQ))
4279       continue;
4280
4281     Arg->claim();
4282     if (O.matches(options::OPT_fcolor_diagnostics) ||
4283         O.matches(options::OPT_fdiagnostics_color)) {
4284       ShowColors = Colors_On;
4285     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4286                O.matches(options::OPT_fno_diagnostics_color)) {
4287       ShowColors = Colors_Off;
4288     } else {
4289       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4290       StringRef value(Arg->getValue());
4291       if (value == "always")
4292         ShowColors = Colors_On;
4293       else if (value == "never")
4294         ShowColors = Colors_Off;
4295       else if (value == "auto")
4296         ShowColors = Colors_Auto;
4297       else
4298         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4299           << ("-fdiagnostics-color=" + value).str();
4300     }
4301   }
4302   if (ShowColors == Colors_On ||
4303       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4304     CmdArgs.push_back("-fcolor-diagnostics");
4305
4306   if (Args.hasArg(options::OPT_fansi_escape_codes))
4307     CmdArgs.push_back("-fansi-escape-codes");
4308
4309   if (!Args.hasFlag(options::OPT_fshow_source_location,
4310                     options::OPT_fno_show_source_location))
4311     CmdArgs.push_back("-fno-show-source-location");
4312
4313   if (!Args.hasFlag(options::OPT_fshow_column,
4314                     options::OPT_fno_show_column,
4315                     true))
4316     CmdArgs.push_back("-fno-show-column");
4317
4318   if (!Args.hasFlag(options::OPT_fspell_checking,
4319                     options::OPT_fno_spell_checking))
4320     CmdArgs.push_back("-fno-spell-checking");
4321
4322
4323   // -fno-asm-blocks is default.
4324   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4325                    false))
4326     CmdArgs.push_back("-fasm-blocks");
4327
4328   // Enable vectorization per default according to the optimization level
4329   // selected. For optimization levels that want vectorization we use the alias
4330   // option to simplify the hasFlag logic.
4331   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4332   OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
4333     options::OPT_fvectorize;
4334   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4335                    options::OPT_fno_vectorize, EnableVec))
4336     CmdArgs.push_back("-vectorize-loops");
4337
4338   // -fslp-vectorize is enabled based on the optimization level selected.
4339   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4340   OptSpecifier SLPVectAliasOption = EnableSLPVec ? options::OPT_O_Group :
4341     options::OPT_fslp_vectorize;
4342   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4343                    options::OPT_fno_slp_vectorize, EnableSLPVec))
4344     CmdArgs.push_back("-vectorize-slp");
4345
4346   // -fno-slp-vectorize-aggressive is default.
4347   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4348                    options::OPT_fno_slp_vectorize_aggressive, false))
4349     CmdArgs.push_back("-vectorize-slp-aggressive");
4350
4351   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4352     A->render(Args, CmdArgs);
4353
4354   // -fdollars-in-identifiers default varies depending on platform and
4355   // language; only pass if specified.
4356   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4357                                options::OPT_fno_dollars_in_identifiers)) {
4358     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4359       CmdArgs.push_back("-fdollars-in-identifiers");
4360     else
4361       CmdArgs.push_back("-fno-dollars-in-identifiers");
4362   }
4363
4364   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4365   // practical purposes.
4366   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4367                                options::OPT_fno_unit_at_a_time)) {
4368     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4369       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4370   }
4371
4372   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4373                    options::OPT_fno_apple_pragma_pack, false))
4374     CmdArgs.push_back("-fapple-pragma-pack");
4375
4376   // le32-specific flags: 
4377   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
4378   //                     by default.
4379   if (getToolChain().getArch() == llvm::Triple::le32) {
4380     CmdArgs.push_back("-fno-math-builtin");
4381   }
4382
4383   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4384   //
4385   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4386 #if 0
4387   if (getToolChain().getTriple().isOSDarwin() &&
4388       (getToolChain().getArch() == llvm::Triple::arm ||
4389        getToolChain().getArch() == llvm::Triple::thumb)) {
4390     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4391       CmdArgs.push_back("-fno-builtin-strcat");
4392     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4393       CmdArgs.push_back("-fno-builtin-strcpy");
4394   }
4395 #endif
4396
4397   // Enable rewrite includes if the user's asked for it or if we're generating
4398   // diagnostics.
4399   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4400   // nice to enable this when doing a crashdump for modules as well.
4401   if (Args.hasFlag(options::OPT_frewrite_includes,
4402                    options::OPT_fno_rewrite_includes, false) ||
4403       (C.isForDiagnostics() && !HaveModules))
4404     CmdArgs.push_back("-frewrite-includes");
4405
4406   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4407   if (Arg *A = Args.getLastArg(options::OPT_traditional,
4408                                options::OPT_traditional_cpp)) {
4409     if (isa<PreprocessJobAction>(JA))
4410       CmdArgs.push_back("-traditional-cpp");
4411     else
4412       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4413   }
4414
4415   Args.AddLastArg(CmdArgs, options::OPT_dM);
4416   Args.AddLastArg(CmdArgs, options::OPT_dD);
4417   
4418   // Handle serialized diagnostics.
4419   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4420     CmdArgs.push_back("-serialize-diagnostic-file");
4421     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4422   }
4423
4424   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4425     CmdArgs.push_back("-fretain-comments-from-system-headers");
4426
4427   // Forward -fcomment-block-commands to -cc1.
4428   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4429   // Forward -fparse-all-comments to -cc1.
4430   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4431
4432   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4433   // parser.
4434   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4435   bool OptDisabled = false;
4436   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
4437          ie = Args.filtered_end(); it != ie; ++it) {
4438     (*it)->claim();
4439
4440     // We translate this by hand to the -cc1 argument, since nightly test uses
4441     // it and developers have been trained to spell it with -mllvm.
4442     if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns") {
4443       CmdArgs.push_back("-disable-llvm-optzns");
4444       OptDisabled = true;
4445     } else
4446       (*it)->render(Args, CmdArgs);
4447   }
4448
4449   // With -save-temps, we want to save the unoptimized bitcode output from the
4450   // CompileJobAction, so disable optimizations if they are not already
4451   // disabled.
4452   if (Args.hasArg(options::OPT_save_temps) && !OptDisabled &&
4453       isa<CompileJobAction>(JA))
4454     CmdArgs.push_back("-disable-llvm-optzns");
4455
4456   if (Output.getType() == types::TY_Dependencies) {
4457     // Handled with other dependency code.
4458   } else if (Output.isFilename()) {
4459     CmdArgs.push_back("-o");
4460     CmdArgs.push_back(Output.getFilename());
4461   } else {
4462     assert(Output.isNothing() && "Invalid output.");
4463   }
4464
4465   for (const auto &II : Inputs) {
4466     addDashXForInput(Args, II, CmdArgs);
4467
4468     if (II.isFilename())
4469       CmdArgs.push_back(II.getFilename());
4470     else
4471       II.getInputArg().renderAsInput(Args, CmdArgs);
4472   }
4473
4474   Args.AddAllArgs(CmdArgs, options::OPT_undef);
4475
4476   const char *Exec = getToolChain().getDriver().getClangProgramPath();
4477
4478   // Optionally embed the -cc1 level arguments into the debug info, for build
4479   // analysis.
4480   if (getToolChain().UseDwarfDebugFlags()) {
4481     ArgStringList OriginalArgs;
4482     for (const auto &Arg : Args)
4483       Arg->render(Args, OriginalArgs);
4484
4485     SmallString<256> Flags;
4486     Flags += Exec;
4487     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4488       SmallString<128> EscapedArg;
4489       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
4490       Flags += " ";
4491       Flags += EscapedArg;
4492     }
4493     CmdArgs.push_back("-dwarf-debug-flags");
4494     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4495   }
4496
4497   // Add the split debug info name to the command lines here so we
4498   // can propagate it to the backend.
4499   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4500     getToolChain().getTriple().isOSLinux() &&
4501     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4502      isa<BackendJobAction>(JA));
4503   const char *SplitDwarfOut;
4504   if (SplitDwarf) {
4505     CmdArgs.push_back("-split-dwarf-file");
4506     SplitDwarfOut = SplitDebugName(Args, Inputs);
4507     CmdArgs.push_back(SplitDwarfOut);
4508   }
4509
4510   // Finally add the compile command to the compilation.
4511   if (Args.hasArg(options::OPT__SLASH_fallback) &&
4512       Output.getType() == types::TY_Object &&
4513       (InputType == types::TY_C || InputType == types::TY_CXX)) {
4514     auto CLCommand =
4515         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4516     C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
4517                                                     std::move(CLCommand)));
4518   } else {
4519     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4520   }
4521
4522
4523   // Handle the debug info splitting at object creation time if we're
4524   // creating an object.
4525   // TODO: Currently only works on linux with newer objcopy.
4526   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4527     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4528
4529   if (Arg *A = Args.getLastArg(options::OPT_pg))
4530     if (Args.hasArg(options::OPT_fomit_frame_pointer))
4531       D.Diag(diag::err_drv_argument_not_allowed_with)
4532         << "-fomit-frame-pointer" << A->getAsString(Args);
4533
4534   // Claim some arguments which clang supports automatically.
4535
4536   // -fpch-preprocess is used with gcc to add a special marker in the output to
4537   // include the PCH file. Clang's PTH solution is completely transparent, so we
4538   // do not need to deal with it at all.
4539   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4540
4541   // Claim some arguments which clang doesn't support, but we don't
4542   // care to warn the user about.
4543   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4544   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4545
4546   // Disable warnings for clang -E -emit-llvm foo.c
4547   Args.ClaimAllArgs(options::OPT_emit_llvm);
4548 }
4549
4550 /// Add options related to the Objective-C runtime/ABI.
4551 ///
4552 /// Returns true if the runtime is non-fragile.
4553 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4554                                       ArgStringList &cmdArgs,
4555                                       RewriteKind rewriteKind) const {
4556   // Look for the controlling runtime option.
4557   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
4558                                     options::OPT_fgnu_runtime,
4559                                     options::OPT_fobjc_runtime_EQ);
4560
4561   // Just forward -fobjc-runtime= to the frontend.  This supercedes
4562   // options about fragility.
4563   if (runtimeArg &&
4564       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4565     ObjCRuntime runtime;
4566     StringRef value = runtimeArg->getValue();
4567     if (runtime.tryParse(value)) {
4568       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4569         << value;
4570     }
4571
4572     runtimeArg->render(args, cmdArgs);
4573     return runtime;
4574   }
4575
4576   // Otherwise, we'll need the ABI "version".  Version numbers are
4577   // slightly confusing for historical reasons:
4578   //   1 - Traditional "fragile" ABI
4579   //   2 - Non-fragile ABI, version 1
4580   //   3 - Non-fragile ABI, version 2
4581   unsigned objcABIVersion = 1;
4582   // If -fobjc-abi-version= is present, use that to set the version.
4583   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4584     StringRef value = abiArg->getValue();
4585     if (value == "1")
4586       objcABIVersion = 1;
4587     else if (value == "2")
4588       objcABIVersion = 2;
4589     else if (value == "3")
4590       objcABIVersion = 3;
4591     else
4592       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4593         << value;
4594   } else {
4595     // Otherwise, determine if we are using the non-fragile ABI.
4596     bool nonFragileABIIsDefault = 
4597       (rewriteKind == RK_NonFragile || 
4598        (rewriteKind == RK_None &&
4599         getToolChain().IsObjCNonFragileABIDefault()));
4600     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4601                      options::OPT_fno_objc_nonfragile_abi,
4602                      nonFragileABIIsDefault)) {
4603       // Determine the non-fragile ABI version to use.
4604 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4605       unsigned nonFragileABIVersion = 1;
4606 #else
4607       unsigned nonFragileABIVersion = 2;
4608 #endif
4609
4610       if (Arg *abiArg = args.getLastArg(
4611             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4612         StringRef value = abiArg->getValue();
4613         if (value == "1")
4614           nonFragileABIVersion = 1;
4615         else if (value == "2")
4616           nonFragileABIVersion = 2;
4617         else
4618           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4619             << value;
4620       }
4621
4622       objcABIVersion = 1 + nonFragileABIVersion;
4623     } else {
4624       objcABIVersion = 1;
4625     }
4626   }
4627
4628   // We don't actually care about the ABI version other than whether
4629   // it's non-fragile.
4630   bool isNonFragile = objcABIVersion != 1;
4631
4632   // If we have no runtime argument, ask the toolchain for its default runtime.
4633   // However, the rewriter only really supports the Mac runtime, so assume that.
4634   ObjCRuntime runtime;
4635   if (!runtimeArg) {
4636     switch (rewriteKind) {
4637     case RK_None:
4638       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4639       break;
4640     case RK_Fragile:
4641       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4642       break;
4643     case RK_NonFragile:
4644       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4645       break;
4646     }
4647
4648   // -fnext-runtime
4649   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4650     // On Darwin, make this use the default behavior for the toolchain.
4651     if (getToolChain().getTriple().isOSDarwin()) {
4652       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4653
4654     // Otherwise, build for a generic macosx port.
4655     } else {
4656       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4657     }
4658
4659   // -fgnu-runtime
4660   } else {
4661     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4662     // Legacy behaviour is to target the gnustep runtime if we are i
4663     // non-fragile mode or the GCC runtime in fragile mode.
4664     if (isNonFragile)
4665       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
4666     else
4667       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4668   }
4669
4670   cmdArgs.push_back(args.MakeArgString(
4671                                  "-fobjc-runtime=" + runtime.getAsString()));
4672   return runtime;
4673 }
4674
4675 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4676   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4677   I += HaveDash;
4678   return !HaveDash;
4679 }
4680
4681 struct EHFlags {
4682   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
4683   bool Synch;
4684   bool Asynch;
4685   bool NoExceptC;
4686 };
4687
4688 /// /EH controls whether to run destructor cleanups when exceptions are
4689 /// thrown.  There are three modifiers:
4690 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4691 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4692 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4693 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
4694 ///      modifier is an optimization, so we ignore it for now.
4695 /// The default is /EHs-c-, meaning cleanups are disabled.
4696 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4697   EHFlags EH;
4698   std::vector<std::string> EHArgs = Args.getAllArgValues(options::OPT__SLASH_EH);
4699   for (auto EHVal : EHArgs) {
4700     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4701       switch (EHVal[I]) {
4702       case 'a': EH.Asynch = maybeConsumeDash(EHVal, I); continue;
4703       case 'c': EH.NoExceptC = maybeConsumeDash(EHVal, I); continue;
4704       case 's': EH.Synch = maybeConsumeDash(EHVal, I); continue;
4705       default: break;
4706       }
4707       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4708       break;
4709     }
4710   }
4711   return EH;
4712 }
4713
4714 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
4715   unsigned RTOptionID = options::OPT__SLASH_MT;
4716
4717   if (Args.hasArg(options::OPT__SLASH_LDd))
4718     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4719     // but defining _DEBUG is sticky.
4720     RTOptionID = options::OPT__SLASH_MTd;
4721
4722   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4723     RTOptionID = A->getOption().getID();
4724
4725   switch(RTOptionID) {
4726     case options::OPT__SLASH_MD:
4727       if (Args.hasArg(options::OPT__SLASH_LDd))
4728         CmdArgs.push_back("-D_DEBUG");
4729       CmdArgs.push_back("-D_MT");
4730       CmdArgs.push_back("-D_DLL");
4731       CmdArgs.push_back("--dependent-lib=msvcrt");
4732       break;
4733     case options::OPT__SLASH_MDd:
4734       CmdArgs.push_back("-D_DEBUG");
4735       CmdArgs.push_back("-D_MT");
4736       CmdArgs.push_back("-D_DLL");
4737       CmdArgs.push_back("--dependent-lib=msvcrtd");
4738       break;
4739     case options::OPT__SLASH_MT:
4740       if (Args.hasArg(options::OPT__SLASH_LDd))
4741         CmdArgs.push_back("-D_DEBUG");
4742       CmdArgs.push_back("-D_MT");
4743       CmdArgs.push_back("--dependent-lib=libcmt");
4744       break;
4745     case options::OPT__SLASH_MTd:
4746       CmdArgs.push_back("-D_DEBUG");
4747       CmdArgs.push_back("-D_MT");
4748       CmdArgs.push_back("--dependent-lib=libcmtd");
4749       break;
4750     default:
4751       llvm_unreachable("Unexpected option ID.");
4752   }
4753
4754   // This provides POSIX compatibility (maps 'open' to '_open'), which most
4755   // users want.  The /Za flag to cl.exe turns this off, but it's not
4756   // implemented in clang.
4757   CmdArgs.push_back("--dependent-lib=oldnames");
4758
4759   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4760   // would produce interleaved output, so ignore /showIncludes in such cases.
4761   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4762     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4763       A->render(Args, CmdArgs);
4764
4765   // This controls whether or not we emit RTTI data for polymorphic types.
4766   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4767                    /*default=*/false))
4768     CmdArgs.push_back("-fno-rtti-data");
4769
4770   const Driver &D = getToolChain().getDriver();
4771   EHFlags EH = parseClangCLEHFlags(D, Args);
4772   // FIXME: Do something with NoExceptC.
4773   if (EH.Synch || EH.Asynch) {
4774     CmdArgs.push_back("-fexceptions");
4775     CmdArgs.push_back("-fcxx-exceptions");
4776   }
4777
4778   // /EP should expand to -E -P.
4779   if (Args.hasArg(options::OPT__SLASH_EP)) {
4780     CmdArgs.push_back("-E");
4781     CmdArgs.push_back("-P");
4782   }
4783
4784   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4785   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4786   if (MostGeneralArg && BestCaseArg)
4787     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4788         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4789
4790   if (MostGeneralArg) {
4791     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4792     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4793     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4794
4795     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4796     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4797     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4798       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4799           << FirstConflict->getAsString(Args)
4800           << SecondConflict->getAsString(Args);
4801
4802     if (SingleArg)
4803       CmdArgs.push_back("-fms-memptr-rep=single");
4804     else if (MultipleArg)
4805       CmdArgs.push_back("-fms-memptr-rep=multiple");
4806     else
4807       CmdArgs.push_back("-fms-memptr-rep=virtual");
4808   }
4809
4810   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4811     A->render(Args, CmdArgs);
4812
4813   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4814     CmdArgs.push_back("-fdiagnostics-format");
4815     if (Args.hasArg(options::OPT__SLASH_fallback))
4816       CmdArgs.push_back("msvc-fallback");
4817     else
4818       CmdArgs.push_back("msvc");
4819   }
4820 }
4821
4822 visualstudio::Compile *Clang::getCLFallback() const {
4823   if (!CLFallback)
4824     CLFallback.reset(new visualstudio::Compile(getToolChain()));
4825   return CLFallback.get();
4826 }
4827
4828 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4829                            const InputInfo &Output,
4830                            const InputInfoList &Inputs,
4831                            const ArgList &Args,
4832                            const char *LinkingOutput) const {
4833   ArgStringList CmdArgs;
4834
4835   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4836   const InputInfo &Input = Inputs[0];
4837
4838   // Don't warn about "clang -w -c foo.s"
4839   Args.ClaimAllArgs(options::OPT_w);
4840   // and "clang -emit-llvm -c foo.s"
4841   Args.ClaimAllArgs(options::OPT_emit_llvm);
4842
4843   claimNoWarnArgs(Args);
4844
4845   // Invoke ourselves in -cc1as mode.
4846   //
4847   // FIXME: Implement custom jobs for internal actions.
4848   CmdArgs.push_back("-cc1as");
4849
4850   // Add the "effective" target triple.
4851   CmdArgs.push_back("-triple");
4852   std::string TripleStr = 
4853     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
4854   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4855
4856   // Set the output mode, we currently only expect to be used as a real
4857   // assembler.
4858   CmdArgs.push_back("-filetype");
4859   CmdArgs.push_back("obj");
4860
4861   // Set the main file name, so that debug info works even with
4862   // -save-temps or preprocessed assembly.
4863   CmdArgs.push_back("-main-file-name");
4864   CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
4865
4866   // Add the target cpu
4867   const llvm::Triple &Triple = getToolChain().getTriple();
4868   std::string CPU = getCPUName(Args, Triple);
4869   if (!CPU.empty()) {
4870     CmdArgs.push_back("-target-cpu");
4871     CmdArgs.push_back(Args.MakeArgString(CPU));
4872   }
4873
4874   // Add the target features
4875   const Driver &D = getToolChain().getDriver();
4876   getTargetFeatures(D, Triple, Args, CmdArgs, true);
4877
4878   // Ignore explicit -force_cpusubtype_ALL option.
4879   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
4880
4881   // Determine the original source input.
4882   const Action *SourceAction = &JA;
4883   while (SourceAction->getKind() != Action::InputClass) {
4884     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4885     SourceAction = SourceAction->getInputs()[0];
4886   }
4887
4888   // Forward -g and handle debug info related flags, assuming we are dealing
4889   // with an actual assembly file.
4890   if (SourceAction->getType() == types::TY_Asm ||
4891       SourceAction->getType() == types::TY_PP_Asm) {
4892     Args.ClaimAllArgs(options::OPT_g_Group);
4893     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
4894       if (!A->getOption().matches(options::OPT_g0))
4895         CmdArgs.push_back("-g");
4896
4897     if (Args.hasArg(options::OPT_gdwarf_2))
4898       CmdArgs.push_back("-gdwarf-2");
4899     if (Args.hasArg(options::OPT_gdwarf_3))
4900       CmdArgs.push_back("-gdwarf-3");
4901     if (Args.hasArg(options::OPT_gdwarf_4))
4902       CmdArgs.push_back("-gdwarf-4");
4903
4904     // Add the -fdebug-compilation-dir flag if needed.
4905     addDebugCompDirArg(Args, CmdArgs);
4906
4907     // Set the AT_producer to the clang version when using the integrated
4908     // assembler on assembly source files.
4909     CmdArgs.push_back("-dwarf-debug-producer");
4910     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4911   }
4912
4913   // Optionally embed the -cc1as level arguments into the debug info, for build
4914   // analysis.
4915   if (getToolChain().UseDwarfDebugFlags()) {
4916     ArgStringList OriginalArgs;
4917     for (const auto &Arg : Args)
4918       Arg->render(Args, OriginalArgs);
4919
4920     SmallString<256> Flags;
4921     const char *Exec = getToolChain().getDriver().getClangProgramPath();
4922     Flags += Exec;
4923     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4924       SmallString<128> EscapedArg;
4925       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
4926       Flags += " ";
4927       Flags += EscapedArg;
4928     }
4929     CmdArgs.push_back("-dwarf-debug-flags");
4930     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4931   }
4932
4933   // FIXME: Add -static support, once we have it.
4934
4935   // Consume all the warning flags. Usually this would be handled more
4936   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
4937   // doesn't handle that so rather than warning about unused flags that are
4938   // actually used, we'll lie by omission instead.
4939   // FIXME: Stop lying and consume only the appropriate driver flags
4940   for (arg_iterator it = Args.filtered_begin(options::OPT_W_Group),
4941                     ie = Args.filtered_end();
4942        it != ie; ++it)
4943     (*it)->claim();
4944
4945   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
4946                                     getToolChain().getDriver());
4947
4948   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
4949
4950   assert(Output.isFilename() && "Unexpected lipo output.");
4951   CmdArgs.push_back("-o");
4952   CmdArgs.push_back(Output.getFilename());
4953
4954   assert(Input.isFilename() && "Invalid input.");
4955   CmdArgs.push_back(Input.getFilename());
4956
4957   const char *Exec = getToolChain().getDriver().getClangProgramPath();
4958   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4959
4960   // Handle the debug info splitting at object creation time if we're
4961   // creating an object.
4962   // TODO: Currently only works on linux with newer objcopy.
4963   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
4964       getToolChain().getTriple().isOSLinux())
4965     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
4966                    SplitDebugName(Args, Inputs));
4967 }
4968
4969 void GnuTool::anchor() {}
4970
4971 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
4972                                const InputInfo &Output,
4973                                const InputInfoList &Inputs,
4974                                const ArgList &Args,
4975                                const char *LinkingOutput) const {
4976   const Driver &D = getToolChain().getDriver();
4977   ArgStringList CmdArgs;
4978
4979   for (const auto &A : Args) {
4980     if (forwardToGCC(A->getOption())) {
4981       // Don't forward any -g arguments to assembly steps.
4982       if (isa<AssembleJobAction>(JA) &&
4983           A->getOption().matches(options::OPT_g_Group))
4984         continue;
4985
4986       // Don't forward any -W arguments to assembly and link steps.
4987       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
4988           A->getOption().matches(options::OPT_W_Group))
4989         continue;
4990
4991       // It is unfortunate that we have to claim here, as this means
4992       // we will basically never report anything interesting for
4993       // platforms using a generic gcc, even if we are just using gcc
4994       // to get to the assembler.
4995       A->claim();
4996       A->render(Args, CmdArgs);
4997     }
4998   }
4999
5000   RenderExtraToolArgs(JA, CmdArgs);
5001
5002   // If using a driver driver, force the arch.
5003   if (getToolChain().getTriple().isOSDarwin()) {
5004     CmdArgs.push_back("-arch");
5005     CmdArgs.push_back(
5006       Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5007   }
5008
5009   // Try to force gcc to match the tool chain we want, if we recognize
5010   // the arch.
5011   //
5012   // FIXME: The triple class should directly provide the information we want
5013   // here.
5014   llvm::Triple::ArchType Arch = getToolChain().getArch();
5015   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5016     CmdArgs.push_back("-m32");
5017   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5018            Arch == llvm::Triple::ppc64le)
5019     CmdArgs.push_back("-m64");
5020
5021   if (Output.isFilename()) {
5022     CmdArgs.push_back("-o");
5023     CmdArgs.push_back(Output.getFilename());
5024   } else {
5025     assert(Output.isNothing() && "Unexpected output");
5026     CmdArgs.push_back("-fsyntax-only");
5027   }
5028
5029   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5030                        options::OPT_Xassembler);
5031
5032   // Only pass -x if gcc will understand it; otherwise hope gcc
5033   // understands the suffix correctly. The main use case this would go
5034   // wrong in is for linker inputs if they happened to have an odd
5035   // suffix; really the only way to get this to happen is a command
5036   // like '-x foobar a.c' which will treat a.c like a linker input.
5037   //
5038   // FIXME: For the linker case specifically, can we safely convert
5039   // inputs into '-Wl,' options?
5040   for (const auto &II : Inputs) {
5041     // Don't try to pass LLVM or AST inputs to a generic gcc.
5042     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5043         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5044       D.Diag(diag::err_drv_no_linker_llvm_support)
5045         << getToolChain().getTripleString();
5046     else if (II.getType() == types::TY_AST)
5047       D.Diag(diag::err_drv_no_ast_support)
5048         << getToolChain().getTripleString();
5049     else if (II.getType() == types::TY_ModuleFile)
5050       D.Diag(diag::err_drv_no_module_support)
5051         << getToolChain().getTripleString();
5052
5053     if (types::canTypeBeUserSpecified(II.getType())) {
5054       CmdArgs.push_back("-x");
5055       CmdArgs.push_back(types::getTypeName(II.getType()));
5056     }
5057
5058     if (II.isFilename())
5059       CmdArgs.push_back(II.getFilename());
5060     else {
5061       const Arg &A = II.getInputArg();
5062
5063       // Reverse translate some rewritten options.
5064       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5065         CmdArgs.push_back("-lstdc++");
5066         continue;
5067       }
5068
5069       // Don't render as input, we need gcc to do the translations.
5070       A.render(Args, CmdArgs);
5071     }
5072   }
5073
5074   const std::string customGCCName = D.getCCCGenericGCCName();
5075   const char *GCCName;
5076   if (!customGCCName.empty())
5077     GCCName = customGCCName.c_str();
5078   else if (D.CCCIsCXX()) {
5079     GCCName = "g++";
5080   } else
5081     GCCName = "gcc";
5082
5083   const char *Exec =
5084     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5085   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5086 }
5087
5088 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
5089                                           ArgStringList &CmdArgs) const {
5090   CmdArgs.push_back("-E");
5091 }
5092
5093 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
5094                                        ArgStringList &CmdArgs) const {
5095   const Driver &D = getToolChain().getDriver();
5096
5097   // If -flto, etc. are present then make sure not to force assembly output.
5098   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
5099       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
5100     CmdArgs.push_back("-c");
5101   else {
5102     if (JA.getType() != types::TY_PP_Asm)
5103       D.Diag(diag::err_drv_invalid_gcc_output_type)
5104         << getTypeName(JA.getType());
5105
5106     CmdArgs.push_back("-S");
5107   }
5108 }
5109
5110 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
5111                                     ArgStringList &CmdArgs) const {
5112   // The types are (hopefully) good enough.
5113 }
5114
5115 // Hexagon tools start.
5116 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
5117                                         ArgStringList &CmdArgs) const {
5118
5119 }
5120 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5121                                const InputInfo &Output,
5122                                const InputInfoList &Inputs,
5123                                const ArgList &Args,
5124                                const char *LinkingOutput) const {
5125   claimNoWarnArgs(Args);
5126
5127   const Driver &D = getToolChain().getDriver();
5128   ArgStringList CmdArgs;
5129
5130   std::string MarchString = "-march=";
5131   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5132   CmdArgs.push_back(Args.MakeArgString(MarchString));
5133
5134   RenderExtraToolArgs(JA, CmdArgs);
5135
5136   if (Output.isFilename()) {
5137     CmdArgs.push_back("-o");
5138     CmdArgs.push_back(Output.getFilename());
5139   } else {
5140     assert(Output.isNothing() && "Unexpected output");
5141     CmdArgs.push_back("-fsyntax-only");
5142   }
5143
5144   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
5145   if (!SmallDataThreshold.empty())
5146     CmdArgs.push_back(
5147       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
5148
5149   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5150                        options::OPT_Xassembler);
5151
5152   // Only pass -x if gcc will understand it; otherwise hope gcc
5153   // understands the suffix correctly. The main use case this would go
5154   // wrong in is for linker inputs if they happened to have an odd
5155   // suffix; really the only way to get this to happen is a command
5156   // like '-x foobar a.c' which will treat a.c like a linker input.
5157   //
5158   // FIXME: For the linker case specifically, can we safely convert
5159   // inputs into '-Wl,' options?
5160   for (const auto &II : Inputs) {
5161     // Don't try to pass LLVM or AST inputs to a generic gcc.
5162     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5163         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5164       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5165         << getToolChain().getTripleString();
5166     else if (II.getType() == types::TY_AST)
5167       D.Diag(clang::diag::err_drv_no_ast_support)
5168         << getToolChain().getTripleString();
5169     else if (II.getType() == types::TY_ModuleFile)
5170       D.Diag(diag::err_drv_no_module_support)
5171       << getToolChain().getTripleString();
5172
5173     if (II.isFilename())
5174       CmdArgs.push_back(II.getFilename());
5175     else
5176       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
5177       II.getInputArg().render(Args, CmdArgs);
5178   }
5179
5180   const char *GCCName = "hexagon-as";
5181   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5182   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5183 }
5184
5185 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
5186                                     ArgStringList &CmdArgs) const {
5187   // The types are (hopefully) good enough.
5188 }
5189
5190 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
5191                                const InputInfo &Output,
5192                                const InputInfoList &Inputs,
5193                                const ArgList &Args,
5194                                const char *LinkingOutput) const {
5195
5196   const toolchains::Hexagon_TC& ToolChain =
5197     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
5198   const Driver &D = ToolChain.getDriver();
5199
5200   ArgStringList CmdArgs;
5201
5202   //----------------------------------------------------------------------------
5203   //
5204   //----------------------------------------------------------------------------
5205   bool hasStaticArg = Args.hasArg(options::OPT_static);
5206   bool buildingLib = Args.hasArg(options::OPT_shared);
5207   bool buildPIE = Args.hasArg(options::OPT_pie);
5208   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5209   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5210   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5211   bool useShared = buildingLib && !hasStaticArg;
5212
5213   //----------------------------------------------------------------------------
5214   // Silence warnings for various options
5215   //----------------------------------------------------------------------------
5216
5217   Args.ClaimAllArgs(options::OPT_g_Group);
5218   Args.ClaimAllArgs(options::OPT_emit_llvm);
5219   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5220                                      // handled somewhere else.
5221   Args.ClaimAllArgs(options::OPT_static_libgcc);
5222
5223   //----------------------------------------------------------------------------
5224   //
5225   //----------------------------------------------------------------------------
5226   for (const auto &Opt : ToolChain.ExtraOpts)
5227     CmdArgs.push_back(Opt.c_str());
5228
5229   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5230   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5231
5232   if (buildingLib) {
5233     CmdArgs.push_back("-shared");
5234     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5235                                        // hexagon-gcc does
5236   }
5237
5238   if (hasStaticArg)
5239     CmdArgs.push_back("-static");
5240
5241   if (buildPIE && !buildingLib)
5242     CmdArgs.push_back("-pie");
5243
5244   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
5245   if (!SmallDataThreshold.empty()) {
5246     CmdArgs.push_back(
5247       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
5248   }
5249
5250   //----------------------------------------------------------------------------
5251   //
5252   //----------------------------------------------------------------------------
5253   CmdArgs.push_back("-o");
5254   CmdArgs.push_back(Output.getFilename());
5255
5256   const std::string MarchSuffix = "/" + MarchString;
5257   const std::string G0Suffix = "/G0";
5258   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5259   const std::string RootDir =
5260       toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5261   const std::string StartFilesDir = RootDir
5262                                     + "hexagon/lib"
5263                                     + (buildingLib
5264                                        ? MarchG0Suffix : MarchSuffix);
5265
5266   //----------------------------------------------------------------------------
5267   // moslib
5268   //----------------------------------------------------------------------------
5269   std::vector<std::string> oslibs;
5270   bool hasStandalone= false;
5271
5272   for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
5273          ie = Args.filtered_end(); it != ie; ++it) {
5274     (*it)->claim();
5275     oslibs.push_back((*it)->getValue());
5276     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5277   }
5278   if (oslibs.empty()) {
5279     oslibs.push_back("standalone");
5280     hasStandalone = true;
5281   }
5282
5283   //----------------------------------------------------------------------------
5284   // Start Files
5285   //----------------------------------------------------------------------------
5286   if (incStdLib && incStartFiles) {
5287
5288     if (!buildingLib) {
5289       if (hasStandalone) {
5290         CmdArgs.push_back(
5291           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5292       }
5293       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5294     }
5295     std::string initObj = useShared ? "/initS.o" : "/init.o";
5296     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5297   }
5298
5299   //----------------------------------------------------------------------------
5300   // Library Search Paths
5301   //----------------------------------------------------------------------------
5302   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5303   for (const auto &LibPath : LibPaths)
5304     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5305
5306   //----------------------------------------------------------------------------
5307   //
5308   //----------------------------------------------------------------------------
5309   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5310   Args.AddAllArgs(CmdArgs, options::OPT_e);
5311   Args.AddAllArgs(CmdArgs, options::OPT_s);
5312   Args.AddAllArgs(CmdArgs, options::OPT_t);
5313   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5314
5315   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5316
5317   //----------------------------------------------------------------------------
5318   // Libraries
5319   //----------------------------------------------------------------------------
5320   if (incStdLib && incDefLibs) {
5321     if (D.CCCIsCXX()) {
5322       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5323       CmdArgs.push_back("-lm");
5324     }
5325
5326     CmdArgs.push_back("--start-group");
5327
5328     if (!buildingLib) {
5329       for(std::vector<std::string>::iterator i = oslibs.begin(),
5330             e = oslibs.end(); i != e; ++i)
5331         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
5332       CmdArgs.push_back("-lc");
5333     }
5334     CmdArgs.push_back("-lgcc");
5335
5336     CmdArgs.push_back("--end-group");
5337   }
5338
5339   //----------------------------------------------------------------------------
5340   // End files
5341   //----------------------------------------------------------------------------
5342   if (incStdLib && incStartFiles) {
5343     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5344     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5345   }
5346
5347   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5348   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5349                                           CmdArgs));
5350 }
5351 // Hexagon tools end.
5352
5353 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5354 const char *arm::getARMCPUForMArch(const ArgList &Args,
5355                                    const llvm::Triple &Triple) {
5356   StringRef MArch;
5357   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
5358     // Otherwise, if we have -march= choose the base CPU for that arch.
5359     MArch = A->getValue();
5360   } else {
5361     // Otherwise, use the Arch from the triple.
5362     MArch = Triple.getArchName();
5363   }
5364
5365   // Handle -march=native.
5366   if (MArch == "native") {
5367     std::string CPU = llvm::sys::getHostCPUName();
5368     if (CPU != "generic") {
5369       // Translate the native cpu into the architecture. The switch below will
5370       // then chose the minimum cpu for that arch.
5371       MArch = std::string("arm") + arm::getLLVMArchSuffixForARM(CPU);
5372     }
5373   }
5374
5375   return Triple.getARMCPUForArch(MArch);
5376 }
5377
5378 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5379 StringRef arm::getARMTargetCPU(const ArgList &Args,
5380                                const llvm::Triple &Triple) {
5381   // FIXME: Warn on inconsistent use of -mcpu and -march.
5382   // If we have -mcpu=, use that.
5383   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
5384     StringRef MCPU = A->getValue();
5385     // Handle -mcpu=native.
5386     if (MCPU == "native")
5387       return llvm::sys::getHostCPUName();
5388     else
5389       return MCPU;
5390   }
5391
5392   return getARMCPUForMArch(Args, Triple);
5393 }
5394
5395 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5396 /// CPU.
5397 //
5398 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5399 // FIXME: tblgen this, or kill it!
5400 const char *arm::getLLVMArchSuffixForARM(StringRef CPU) {
5401   return llvm::StringSwitch<const char *>(CPU)
5402     .Case("strongarm", "v4")
5403     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
5404     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
5405     .Cases("arm920", "arm920t", "arm922t", "v4t")
5406     .Cases("arm940t", "ep9312","v4t")
5407     .Cases("arm10tdmi",  "arm1020t", "v5")
5408     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
5409     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
5410     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
5411     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
5412     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
5413     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
5414     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
5415     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "v7")
5416     .Cases("cortex-r4", "cortex-r5", "v7r")
5417     .Case("cortex-m0", "v6m")
5418     .Case("cortex-m3", "v7m")
5419     .Cases("cortex-m4", "cortex-m7", "v7em")
5420     .Case("swift", "v7s")
5421     .Case("cyclone", "v8")
5422     .Cases("cortex-a53", "cortex-a57", "v8")
5423     .Default("");
5424 }
5425
5426 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5427   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5428   return A && (A->getValue() == StringRef(Value));
5429 }
5430
5431 bool mips::isUCLibc(const ArgList &Args) {
5432   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
5433   return A && A->getOption().matches(options::OPT_muclibc);
5434 }
5435
5436 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5437   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5438     return llvm::StringSwitch<bool>(NaNArg->getValue())
5439                .Case("2008", true)
5440                .Case("legacy", false)
5441                .Default(false);
5442
5443   // NaN2008 is the default for MIPS32r6/MIPS64r6.
5444   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
5445              .Cases("mips32r6", "mips64r6", true)
5446              .Default(false);
5447
5448   return false;
5449 }
5450
5451 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
5452                          StringRef ABIName) {
5453   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
5454       Triple.getVendor() != llvm::Triple::MipsTechnologies)
5455     return false;
5456
5457   if (ABIName != "32")
5458     return false;
5459
5460   return llvm::StringSwitch<bool>(CPUName)
5461              .Cases("mips2", "mips3", "mips4", "mips5", true)
5462              .Cases("mips32", "mips32r2", true)
5463              .Cases("mips64", "mips64r2", true)
5464              .Default(false);
5465 }
5466
5467 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
5468   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
5469   // archs which Darwin doesn't use.
5470
5471   // The matching this routine does is fairly pointless, since it is neither the
5472   // complete architecture list, nor a reasonable subset. The problem is that
5473   // historically the driver driver accepts this and also ties its -march=
5474   // handling to the architecture name, so we need to be careful before removing
5475   // support for it.
5476
5477   // This code must be kept in sync with Clang's Darwin specific argument
5478   // translation.
5479
5480   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
5481     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
5482     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
5483     .Case("ppc64", llvm::Triple::ppc64)
5484     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
5485     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
5486            llvm::Triple::x86)
5487     .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
5488     // This is derived from the driver driver.
5489     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
5490     .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
5491     .Cases("armv7s", "xscale", llvm::Triple::arm)
5492     .Case("arm64", llvm::Triple::aarch64)
5493     .Case("r600", llvm::Triple::r600)
5494     .Case("amdgcn", llvm::Triple::amdgcn)
5495     .Case("nvptx", llvm::Triple::nvptx)
5496     .Case("nvptx64", llvm::Triple::nvptx64)
5497     .Case("amdil", llvm::Triple::amdil)
5498     .Case("spir", llvm::Triple::spir)
5499     .Default(llvm::Triple::UnknownArch);
5500 }
5501
5502 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
5503   llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
5504   T.setArch(Arch);
5505
5506   if (Str == "x86_64h")
5507     T.setArchName(Str);
5508   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
5509     T.setOS(llvm::Triple::UnknownOS);
5510     T.setObjectFormat(llvm::Triple::MachO);
5511   }
5512 }
5513
5514 const char *Clang::getBaseInputName(const ArgList &Args,
5515                                     const InputInfoList &Inputs) {
5516   return Args.MakeArgString(
5517     llvm::sys::path::filename(Inputs[0].getBaseInput()));
5518 }
5519
5520 const char *Clang::getBaseInputStem(const ArgList &Args,
5521                                     const InputInfoList &Inputs) {
5522   const char *Str = getBaseInputName(Args, Inputs);
5523
5524   if (const char *End = strrchr(Str, '.'))
5525     return Args.MakeArgString(std::string(Str, End));
5526
5527   return Str;
5528 }
5529
5530 const char *Clang::getDependencyFileName(const ArgList &Args,
5531                                          const InputInfoList &Inputs) {
5532   // FIXME: Think about this more.
5533   std::string Res;
5534
5535   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5536     std::string Str(OutputOpt->getValue());
5537     Res = Str.substr(0, Str.rfind('.'));
5538   } else {
5539     Res = getBaseInputStem(Args, Inputs);
5540   }
5541   return Args.MakeArgString(Res + ".d");
5542 }
5543
5544 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5545                                     const InputInfo &Output,
5546                                     const InputInfoList &Inputs,
5547                                     const ArgList &Args,
5548                                     const char *LinkingOutput) const {
5549   ArgStringList CmdArgs;
5550
5551   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5552   const InputInfo &Input = Inputs[0];
5553
5554   // Determine the original source input.
5555   const Action *SourceAction = &JA;
5556   while (SourceAction->getKind() != Action::InputClass) {
5557     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5558     SourceAction = SourceAction->getInputs()[0];
5559   }
5560
5561   // If -fno_integrated_as is used add -Q to the darwin assember driver to make
5562   // sure it runs its system assembler not clang's integrated assembler.
5563   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
5564   // FIXME: at run-time detect assembler capabilities or rely on version
5565   // information forwarded by -target-assembler-version (future)
5566   if (Args.hasArg(options::OPT_fno_integrated_as)) {
5567     const llvm::Triple &T(getToolChain().getTriple());
5568     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
5569       CmdArgs.push_back("-Q");
5570   }
5571
5572   // Forward -g, assuming we are dealing with an actual assembly file.
5573   if (SourceAction->getType() == types::TY_Asm ||
5574       SourceAction->getType() == types::TY_PP_Asm) {
5575     if (Args.hasArg(options::OPT_gstabs))
5576       CmdArgs.push_back("--gstabs");
5577     else if (Args.hasArg(options::OPT_g_Group))
5578       CmdArgs.push_back("-g");
5579   }
5580
5581   // Derived from asm spec.
5582   AddMachOArch(Args, CmdArgs);
5583
5584   // Use -force_cpusubtype_ALL on x86 by default.
5585   if (getToolChain().getArch() == llvm::Triple::x86 ||
5586       getToolChain().getArch() == llvm::Triple::x86_64 ||
5587       Args.hasArg(options::OPT_force__cpusubtype__ALL))
5588     CmdArgs.push_back("-force_cpusubtype_ALL");
5589
5590   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
5591       (((Args.hasArg(options::OPT_mkernel) ||
5592          Args.hasArg(options::OPT_fapple_kext)) &&
5593         getMachOToolChain().isKernelStatic()) ||
5594        Args.hasArg(options::OPT_static)))
5595     CmdArgs.push_back("-static");
5596
5597   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5598                        options::OPT_Xassembler);
5599
5600   assert(Output.isFilename() && "Unexpected lipo output.");
5601   CmdArgs.push_back("-o");
5602   CmdArgs.push_back(Output.getFilename());
5603
5604   assert(Input.isFilename() && "Invalid input.");
5605   CmdArgs.push_back(Input.getFilename());
5606
5607   // asm_final spec is empty.
5608
5609   const char *Exec =
5610     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5611   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5612 }
5613
5614 void darwin::MachOTool::anchor() {}
5615
5616 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
5617                                      ArgStringList &CmdArgs) const {
5618   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
5619
5620   // Derived from darwin_arch spec.
5621   CmdArgs.push_back("-arch");
5622   CmdArgs.push_back(Args.MakeArgString(ArchName));
5623
5624   // FIXME: Is this needed anymore?
5625   if (ArchName == "arm")
5626     CmdArgs.push_back("-force_cpusubtype_ALL");
5627 }
5628
5629 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
5630   // We only need to generate a temp path for LTO if we aren't compiling object
5631   // files. When compiling source files, we run 'dsymutil' after linking. We
5632   // don't run 'dsymutil' when compiling object files.
5633   for (const auto &Input : Inputs)
5634     if (Input.getType() != types::TY_Object)
5635       return true;
5636
5637   return false;
5638 }
5639
5640 void darwin::Link::AddLinkArgs(Compilation &C,
5641                                const ArgList &Args,
5642                                ArgStringList &CmdArgs,
5643                                const InputInfoList &Inputs) const {
5644   const Driver &D = getToolChain().getDriver();
5645   const toolchains::MachO &MachOTC = getMachOToolChain();
5646
5647   unsigned Version[3] = { 0, 0, 0 };
5648   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5649     bool HadExtra;
5650     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
5651                                    Version[1], Version[2], HadExtra) ||
5652         HadExtra)
5653       D.Diag(diag::err_drv_invalid_version_number)
5654         << A->getAsString(Args);
5655   }
5656
5657   // Newer linkers support -demangle. Pass it if supported and not disabled by
5658   // the user.
5659   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
5660     CmdArgs.push_back("-demangle");
5661
5662   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
5663     CmdArgs.push_back("-export_dynamic");
5664
5665   // If we are using LTO, then automatically create a temporary file path for
5666   // the linker to use, so that it's lifetime will extend past a possible
5667   // dsymutil step.
5668   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
5669     const char *TmpPath = C.getArgs().MakeArgString(
5670       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
5671     C.addTempFile(TmpPath);
5672     CmdArgs.push_back("-object_path_lto");
5673     CmdArgs.push_back(TmpPath);
5674   }
5675
5676   // Derived from the "link" spec.
5677   Args.AddAllArgs(CmdArgs, options::OPT_static);
5678   if (!Args.hasArg(options::OPT_static))
5679     CmdArgs.push_back("-dynamic");
5680   if (Args.hasArg(options::OPT_fgnu_runtime)) {
5681     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
5682     // here. How do we wish to handle such things?
5683   }
5684
5685   if (!Args.hasArg(options::OPT_dynamiclib)) {
5686     AddMachOArch(Args, CmdArgs);
5687     // FIXME: Why do this only on this path?
5688     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
5689
5690     Args.AddLastArg(CmdArgs, options::OPT_bundle);
5691     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
5692     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
5693
5694     Arg *A;
5695     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
5696         (A = Args.getLastArg(options::OPT_current__version)) ||
5697         (A = Args.getLastArg(options::OPT_install__name)))
5698       D.Diag(diag::err_drv_argument_only_allowed_with)
5699         << A->getAsString(Args) << "-dynamiclib";
5700
5701     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
5702     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
5703     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
5704   } else {
5705     CmdArgs.push_back("-dylib");
5706
5707     Arg *A;
5708     if ((A = Args.getLastArg(options::OPT_bundle)) ||
5709         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
5710         (A = Args.getLastArg(options::OPT_client__name)) ||
5711         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
5712         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
5713         (A = Args.getLastArg(options::OPT_private__bundle)))
5714       D.Diag(diag::err_drv_argument_not_allowed_with)
5715         << A->getAsString(Args) << "-dynamiclib";
5716
5717     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
5718                               "-dylib_compatibility_version");
5719     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
5720                               "-dylib_current_version");
5721
5722     AddMachOArch(Args, CmdArgs);
5723
5724     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
5725                               "-dylib_install_name");
5726   }
5727
5728   Args.AddLastArg(CmdArgs, options::OPT_all__load);
5729   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
5730   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
5731   if (MachOTC.isTargetIOSBased())
5732     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
5733   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
5734   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
5735   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
5736   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
5737   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
5738   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
5739   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
5740   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
5741   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
5742   Args.AddAllArgs(CmdArgs, options::OPT_init);
5743
5744   // Add the deployment target.
5745   MachOTC.addMinVersionArgs(Args, CmdArgs);
5746
5747   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
5748   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
5749   Args.AddLastArg(CmdArgs, options::OPT_single__module);
5750   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
5751   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
5752
5753   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
5754                                      options::OPT_fno_pie,
5755                                      options::OPT_fno_PIE)) {
5756     if (A->getOption().matches(options::OPT_fpie) ||
5757         A->getOption().matches(options::OPT_fPIE))
5758       CmdArgs.push_back("-pie");
5759     else
5760       CmdArgs.push_back("-no_pie");
5761   }
5762
5763   Args.AddLastArg(CmdArgs, options::OPT_prebind);
5764   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
5765   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
5766   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
5767   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
5768   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
5769   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
5770   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
5771   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
5772   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
5773   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
5774   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
5775   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
5776   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
5777   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
5778   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
5779
5780   // Give --sysroot= preference, over the Apple specific behavior to also use
5781   // --isysroot as the syslibroot.
5782   StringRef sysroot = C.getSysRoot();
5783   if (sysroot != "") {
5784     CmdArgs.push_back("-syslibroot");
5785     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
5786   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
5787     CmdArgs.push_back("-syslibroot");
5788     CmdArgs.push_back(A->getValue());
5789   }
5790
5791   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
5792   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
5793   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
5794   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
5795   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
5796   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
5797   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
5798   Args.AddAllArgs(CmdArgs, options::OPT_y);
5799   Args.AddLastArg(CmdArgs, options::OPT_w);
5800   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
5801   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
5802   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
5803   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
5804   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
5805   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
5806   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
5807   Args.AddLastArg(CmdArgs, options::OPT_whyload);
5808   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
5809   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
5810   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
5811   Args.AddLastArg(CmdArgs, options::OPT_Mach);
5812 }
5813
5814 enum LibOpenMP {
5815   LibUnknown,
5816   LibGOMP,
5817   LibIOMP5
5818 };
5819
5820 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
5821                                 const InputInfo &Output,
5822                                 const InputInfoList &Inputs,
5823                                 const ArgList &Args,
5824                                 const char *LinkingOutput) const {
5825   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
5826
5827   // If the number of arguments surpasses the system limits, we will encode the
5828   // input files in a separate file, shortening the command line. To this end,
5829   // build a list of input file names that can be passed via a file with the
5830   // -filelist linker option.
5831   llvm::opt::ArgStringList InputFileList;
5832
5833   // The logic here is derived from gcc's behavior; most of which
5834   // comes from specs (starting with link_command). Consult gcc for
5835   // more information.
5836   ArgStringList CmdArgs;
5837
5838   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
5839   if (Args.hasArg(options::OPT_ccc_arcmt_check,
5840                   options::OPT_ccc_arcmt_migrate)) {
5841     for (const auto &Arg : Args)
5842       Arg->claim();
5843     const char *Exec =
5844       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
5845     CmdArgs.push_back(Output.getFilename());
5846     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5847     return;
5848   }
5849
5850   // I'm not sure why this particular decomposition exists in gcc, but
5851   // we follow suite for ease of comparison.
5852   AddLinkArgs(C, Args, CmdArgs, Inputs);
5853
5854   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
5855   Args.AddAllArgs(CmdArgs, options::OPT_s);
5856   Args.AddAllArgs(CmdArgs, options::OPT_t);
5857   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5858   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5859   Args.AddLastArg(CmdArgs, options::OPT_e);
5860   Args.AddAllArgs(CmdArgs, options::OPT_r);
5861
5862   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
5863   // members of static archive libraries which implement Objective-C classes or
5864   // categories.
5865   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
5866     CmdArgs.push_back("-ObjC");
5867
5868   CmdArgs.push_back("-o");
5869   CmdArgs.push_back(Output.getFilename());
5870
5871   if (!Args.hasArg(options::OPT_nostdlib) &&
5872       !Args.hasArg(options::OPT_nostartfiles))
5873     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
5874
5875   Args.AddAllArgs(CmdArgs, options::OPT_L);
5876
5877   LibOpenMP UsedOpenMPLib = LibUnknown;
5878   if (Args.hasArg(options::OPT_fopenmp)) {
5879     UsedOpenMPLib = LibGOMP;
5880   } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
5881     UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
5882         .Case("libgomp",  LibGOMP)
5883         .Case("libiomp5", LibIOMP5)
5884         .Default(LibUnknown);
5885     if (UsedOpenMPLib == LibUnknown)
5886       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5887         << A->getOption().getName() << A->getValue();
5888   }
5889   switch (UsedOpenMPLib) {
5890   case LibGOMP:
5891     CmdArgs.push_back("-lgomp");
5892     break;
5893   case LibIOMP5:
5894     CmdArgs.push_back("-liomp5");
5895     break;
5896   case LibUnknown:
5897     break;
5898   }
5899
5900   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5901   // Build the input file for -filelist (list of linker input files) in case we
5902   // need it later
5903   for (const auto &II : Inputs) {
5904     if (!II.isFilename()) {
5905       // This is a linker input argument.
5906       // We cannot mix input arguments and file names in a -filelist input, thus
5907       // we prematurely stop our list (remaining files shall be passed as
5908       // arguments).
5909       if (InputFileList.size() > 0)
5910         break;
5911
5912       continue;
5913     }
5914
5915     InputFileList.push_back(II.getFilename());
5916   }
5917
5918   if (isObjCRuntimeLinked(Args) &&
5919       !Args.hasArg(options::OPT_nostdlib) &&
5920       !Args.hasArg(options::OPT_nodefaultlibs)) {
5921     // We use arclite library for both ARC and subscripting support.
5922     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
5923
5924     CmdArgs.push_back("-framework");
5925     CmdArgs.push_back("Foundation");
5926     // Link libobj.
5927     CmdArgs.push_back("-lobjc");
5928   }
5929
5930   if (LinkingOutput) {
5931     CmdArgs.push_back("-arch_multiple");
5932     CmdArgs.push_back("-final_output");
5933     CmdArgs.push_back(LinkingOutput);
5934   }
5935
5936   if (Args.hasArg(options::OPT_fnested_functions))
5937     CmdArgs.push_back("-allow_stack_execute");
5938
5939   if (!Args.hasArg(options::OPT_nostdlib) &&
5940       !Args.hasArg(options::OPT_nodefaultlibs)) {
5941     if (getToolChain().getDriver().CCCIsCXX())
5942       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5943
5944     // link_ssp spec is empty.
5945
5946     // Let the tool chain choose which runtime library to link.
5947     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
5948   }
5949
5950   if (!Args.hasArg(options::OPT_nostdlib) &&
5951       !Args.hasArg(options::OPT_nostartfiles)) {
5952     // endfile_spec is empty.
5953   }
5954
5955   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5956   Args.AddAllArgs(CmdArgs, options::OPT_F);
5957
5958   const char *Exec =
5959     Args.MakeArgString(getToolChain().GetLinkerPath());
5960   std::unique_ptr<Command> Cmd =
5961     llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
5962   Cmd->setInputFileList(std::move(InputFileList));
5963   C.addCommand(std::move(Cmd));
5964 }
5965
5966 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
5967                                 const InputInfo &Output,
5968                                 const InputInfoList &Inputs,
5969                                 const ArgList &Args,
5970                                 const char *LinkingOutput) const {
5971   ArgStringList CmdArgs;
5972
5973   CmdArgs.push_back("-create");
5974   assert(Output.isFilename() && "Unexpected lipo output.");
5975
5976   CmdArgs.push_back("-output");
5977   CmdArgs.push_back(Output.getFilename());
5978
5979   for (const auto &II : Inputs) {
5980     assert(II.isFilename() && "Unexpected lipo input.");
5981     CmdArgs.push_back(II.getFilename());
5982   }
5983
5984   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
5985   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5986 }
5987
5988 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
5989                                     const InputInfo &Output,
5990                                     const InputInfoList &Inputs,
5991                                     const ArgList &Args,
5992                                     const char *LinkingOutput) const {
5993   ArgStringList CmdArgs;
5994
5995   CmdArgs.push_back("-o");
5996   CmdArgs.push_back(Output.getFilename());
5997
5998   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5999   const InputInfo &Input = Inputs[0];
6000   assert(Input.isFilename() && "Unexpected dsymutil input.");
6001   CmdArgs.push_back(Input.getFilename());
6002
6003   const char *Exec =
6004     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6005   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6006 }
6007
6008 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6009                                        const InputInfo &Output,
6010                                        const InputInfoList &Inputs,
6011                                        const ArgList &Args,
6012                                        const char *LinkingOutput) const {
6013   ArgStringList CmdArgs;
6014   CmdArgs.push_back("--verify");
6015   CmdArgs.push_back("--debug-info");
6016   CmdArgs.push_back("--eh-frame");
6017   CmdArgs.push_back("--quiet");
6018
6019   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6020   const InputInfo &Input = Inputs[0];
6021   assert(Input.isFilename() && "Unexpected verify input");
6022
6023   // Grabbing the output of the earlier dsymutil run.
6024   CmdArgs.push_back(Input.getFilename());
6025
6026   const char *Exec =
6027     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6028   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6029 }
6030
6031 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6032                                       const InputInfo &Output,
6033                                       const InputInfoList &Inputs,
6034                                       const ArgList &Args,
6035                                       const char *LinkingOutput) const {
6036   claimNoWarnArgs(Args);
6037   ArgStringList CmdArgs;
6038
6039   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6040                        options::OPT_Xassembler);
6041
6042   CmdArgs.push_back("-o");
6043   CmdArgs.push_back(Output.getFilename());
6044
6045   for (const auto &II : Inputs)
6046     CmdArgs.push_back(II.getFilename());
6047
6048   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6049   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6050 }
6051
6052 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
6053                                   const InputInfo &Output,
6054                                   const InputInfoList &Inputs,
6055                                   const ArgList &Args,
6056                                   const char *LinkingOutput) const {
6057   // FIXME: Find a real GCC, don't hard-code versions here
6058   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6059   const llvm::Triple &T = getToolChain().getTriple();
6060   std::string LibPath = "/usr/lib/";
6061   llvm::Triple::ArchType Arch = T.getArch();
6062   switch (Arch) {
6063   case llvm::Triple::x86:
6064     GCCLibPath +=
6065         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6066     break;
6067   case llvm::Triple::x86_64:
6068     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6069     GCCLibPath += "/4.5.2/amd64/";
6070     LibPath += "amd64/";
6071     break;
6072   default:
6073     llvm_unreachable("Unsupported architecture");
6074   }
6075
6076   ArgStringList CmdArgs;
6077
6078   // Demangle C++ names in errors
6079   CmdArgs.push_back("-C");
6080
6081   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6082       (!Args.hasArg(options::OPT_shared))) {
6083     CmdArgs.push_back("-e");
6084     CmdArgs.push_back("_start");
6085   }
6086
6087   if (Args.hasArg(options::OPT_static)) {
6088     CmdArgs.push_back("-Bstatic");
6089     CmdArgs.push_back("-dn");
6090   } else {
6091     CmdArgs.push_back("-Bdynamic");
6092     if (Args.hasArg(options::OPT_shared)) {
6093       CmdArgs.push_back("-shared");
6094     } else {
6095       CmdArgs.push_back("--dynamic-linker");
6096       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6097     }
6098   }
6099
6100   if (Output.isFilename()) {
6101     CmdArgs.push_back("-o");
6102     CmdArgs.push_back(Output.getFilename());
6103   } else {
6104     assert(Output.isNothing() && "Invalid output.");
6105   }
6106
6107   if (!Args.hasArg(options::OPT_nostdlib) &&
6108       !Args.hasArg(options::OPT_nostartfiles)) {
6109     if (!Args.hasArg(options::OPT_shared)) {
6110       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6111       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6112       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6113       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6114     } else {
6115       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6116       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6117       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6118     }
6119     if (getToolChain().getDriver().CCCIsCXX())
6120       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6121   }
6122
6123   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6124
6125   Args.AddAllArgs(CmdArgs, options::OPT_L);
6126   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6127   Args.AddAllArgs(CmdArgs, options::OPT_e);
6128   Args.AddAllArgs(CmdArgs, options::OPT_r);
6129
6130   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6131
6132   if (!Args.hasArg(options::OPT_nostdlib) &&
6133       !Args.hasArg(options::OPT_nodefaultlibs)) {
6134     if (getToolChain().getDriver().CCCIsCXX())
6135       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6136     CmdArgs.push_back("-lgcc_s");
6137     if (!Args.hasArg(options::OPT_shared)) {
6138       CmdArgs.push_back("-lgcc");
6139       CmdArgs.push_back("-lc");
6140       CmdArgs.push_back("-lm");
6141     }
6142   }
6143
6144   if (!Args.hasArg(options::OPT_nostdlib) &&
6145       !Args.hasArg(options::OPT_nostartfiles)) {
6146     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6147   }
6148   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6149
6150   addProfileRT(getToolChain(), Args, CmdArgs);
6151
6152   const char *Exec =
6153     Args.MakeArgString(getToolChain().GetLinkerPath());
6154   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6155 }
6156
6157 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6158                                      const InputInfo &Output,
6159                                      const InputInfoList &Inputs,
6160                                      const ArgList &Args,
6161                                      const char *LinkingOutput) const {
6162   claimNoWarnArgs(Args);
6163   ArgStringList CmdArgs;
6164   bool NeedsKPIC = false;
6165
6166   switch (getToolChain().getArch()) {
6167   case llvm::Triple::x86:
6168     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6169     // instruct as in the base system to assemble 32-bit code.
6170     CmdArgs.push_back("--32");
6171     break;
6172
6173   case llvm::Triple::ppc:
6174     CmdArgs.push_back("-mppc");
6175     CmdArgs.push_back("-many");
6176     break;
6177
6178   case llvm::Triple::sparc:
6179     CmdArgs.push_back("-32");
6180     NeedsKPIC = true;
6181     break;
6182
6183   case llvm::Triple::sparcv9:
6184     CmdArgs.push_back("-64");
6185     CmdArgs.push_back("-Av9a");
6186     NeedsKPIC = true;
6187     break;
6188
6189   case llvm::Triple::mips64:
6190   case llvm::Triple::mips64el: {
6191     StringRef CPUName;
6192     StringRef ABIName;
6193     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6194
6195     CmdArgs.push_back("-mabi");
6196     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6197
6198     if (getToolChain().getArch() == llvm::Triple::mips64)
6199       CmdArgs.push_back("-EB");
6200     else
6201       CmdArgs.push_back("-EL");
6202
6203     NeedsKPIC = true;
6204     break;
6205   }
6206
6207   default:
6208     break;
6209   }
6210
6211   if (NeedsKPIC)
6212     addAssemblerKPIC(Args, CmdArgs);
6213
6214   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6215                        options::OPT_Xassembler);
6216
6217   CmdArgs.push_back("-o");
6218   CmdArgs.push_back(Output.getFilename());
6219
6220   for (const auto &II : Inputs)
6221     CmdArgs.push_back(II.getFilename());
6222
6223   const char *Exec =
6224     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6225   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6226 }
6227
6228 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6229                                  const InputInfo &Output,
6230                                  const InputInfoList &Inputs,
6231                                  const ArgList &Args,
6232                                  const char *LinkingOutput) const {
6233   const Driver &D = getToolChain().getDriver();
6234   ArgStringList CmdArgs;
6235
6236   // Silence warning for "clang -g foo.o -o foo"
6237   Args.ClaimAllArgs(options::OPT_g_Group);
6238   // and "clang -emit-llvm foo.o -o foo"
6239   Args.ClaimAllArgs(options::OPT_emit_llvm);
6240   // and for "clang -w foo.o -o foo". Other warning options are already
6241   // handled somewhere else.
6242   Args.ClaimAllArgs(options::OPT_w);
6243
6244   if (getToolChain().getArch() == llvm::Triple::mips64)
6245     CmdArgs.push_back("-EB");
6246   else if (getToolChain().getArch() == llvm::Triple::mips64el)
6247     CmdArgs.push_back("-EL");
6248
6249   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6250       (!Args.hasArg(options::OPT_shared))) {
6251     CmdArgs.push_back("-e");
6252     CmdArgs.push_back("__start");
6253   }
6254
6255   if (Args.hasArg(options::OPT_static)) {
6256     CmdArgs.push_back("-Bstatic");
6257   } else {
6258     if (Args.hasArg(options::OPT_rdynamic))
6259       CmdArgs.push_back("-export-dynamic");
6260     CmdArgs.push_back("--eh-frame-hdr");
6261     CmdArgs.push_back("-Bdynamic");
6262     if (Args.hasArg(options::OPT_shared)) {
6263       CmdArgs.push_back("-shared");
6264     } else {
6265       CmdArgs.push_back("-dynamic-linker");
6266       CmdArgs.push_back("/usr/libexec/ld.so");
6267     }
6268   }
6269
6270   if (Args.hasArg(options::OPT_nopie))
6271     CmdArgs.push_back("-nopie");
6272
6273   if (Output.isFilename()) {
6274     CmdArgs.push_back("-o");
6275     CmdArgs.push_back(Output.getFilename());
6276   } else {
6277     assert(Output.isNothing() && "Invalid output.");
6278   }
6279
6280   if (!Args.hasArg(options::OPT_nostdlib) &&
6281       !Args.hasArg(options::OPT_nostartfiles)) {
6282     if (!Args.hasArg(options::OPT_shared)) {
6283       if (Args.hasArg(options::OPT_pg))  
6284         CmdArgs.push_back(Args.MakeArgString(
6285                                 getToolChain().GetFilePath("gcrt0.o")));
6286       else
6287         CmdArgs.push_back(Args.MakeArgString(
6288                                 getToolChain().GetFilePath("crt0.o")));
6289       CmdArgs.push_back(Args.MakeArgString(
6290                               getToolChain().GetFilePath("crtbegin.o")));
6291     } else {
6292       CmdArgs.push_back(Args.MakeArgString(
6293                               getToolChain().GetFilePath("crtbeginS.o")));
6294     }
6295   }
6296
6297   std::string Triple = getToolChain().getTripleString();
6298   if (Triple.substr(0, 6) == "x86_64")
6299     Triple.replace(0, 6, "amd64");
6300   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
6301                                        "/4.2.1"));
6302
6303   Args.AddAllArgs(CmdArgs, options::OPT_L);
6304   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6305   Args.AddAllArgs(CmdArgs, options::OPT_e);
6306   Args.AddAllArgs(CmdArgs, options::OPT_s);
6307   Args.AddAllArgs(CmdArgs, options::OPT_t);
6308   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6309   Args.AddAllArgs(CmdArgs, options::OPT_r);
6310
6311   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6312
6313   if (!Args.hasArg(options::OPT_nostdlib) &&
6314       !Args.hasArg(options::OPT_nodefaultlibs)) {
6315     if (D.CCCIsCXX()) {
6316       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6317       if (Args.hasArg(options::OPT_pg)) 
6318         CmdArgs.push_back("-lm_p");
6319       else
6320         CmdArgs.push_back("-lm");
6321     }
6322
6323     // FIXME: For some reason GCC passes -lgcc before adding
6324     // the default system libraries. Just mimic this for now.
6325     CmdArgs.push_back("-lgcc");
6326
6327     if (Args.hasArg(options::OPT_pthread)) {
6328       if (!Args.hasArg(options::OPT_shared) &&
6329           Args.hasArg(options::OPT_pg))
6330          CmdArgs.push_back("-lpthread_p");
6331       else
6332          CmdArgs.push_back("-lpthread");
6333     }
6334
6335     if (!Args.hasArg(options::OPT_shared)) {
6336       if (Args.hasArg(options::OPT_pg))
6337          CmdArgs.push_back("-lc_p");
6338       else
6339          CmdArgs.push_back("-lc");
6340     }
6341
6342     CmdArgs.push_back("-lgcc");
6343   }
6344
6345   if (!Args.hasArg(options::OPT_nostdlib) &&
6346       !Args.hasArg(options::OPT_nostartfiles)) {
6347     if (!Args.hasArg(options::OPT_shared))
6348       CmdArgs.push_back(Args.MakeArgString(
6349                               getToolChain().GetFilePath("crtend.o")));
6350     else
6351       CmdArgs.push_back(Args.MakeArgString(
6352                               getToolChain().GetFilePath("crtendS.o")));
6353   }
6354
6355   const char *Exec =
6356     Args.MakeArgString(getToolChain().GetLinkerPath());
6357   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6358 }
6359
6360 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6361                                     const InputInfo &Output,
6362                                     const InputInfoList &Inputs,
6363                                     const ArgList &Args,
6364                                     const char *LinkingOutput) const {
6365   claimNoWarnArgs(Args);
6366   ArgStringList CmdArgs;
6367
6368   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6369                        options::OPT_Xassembler);
6370
6371   CmdArgs.push_back("-o");
6372   CmdArgs.push_back(Output.getFilename());
6373
6374   for (const auto &II : Inputs)
6375     CmdArgs.push_back(II.getFilename());
6376
6377   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6378   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6379 }
6380
6381 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
6382                                 const InputInfo &Output,
6383                                 const InputInfoList &Inputs,
6384                                 const ArgList &Args,
6385                                 const char *LinkingOutput) const {
6386   const Driver &D = getToolChain().getDriver();
6387   ArgStringList CmdArgs;
6388
6389   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6390       (!Args.hasArg(options::OPT_shared))) {
6391     CmdArgs.push_back("-e");
6392     CmdArgs.push_back("__start");
6393   }
6394
6395   if (Args.hasArg(options::OPT_static)) {
6396     CmdArgs.push_back("-Bstatic");
6397   } else {
6398     if (Args.hasArg(options::OPT_rdynamic))
6399       CmdArgs.push_back("-export-dynamic");
6400     CmdArgs.push_back("--eh-frame-hdr");
6401     CmdArgs.push_back("-Bdynamic");
6402     if (Args.hasArg(options::OPT_shared)) {
6403       CmdArgs.push_back("-shared");
6404     } else {
6405       CmdArgs.push_back("-dynamic-linker");
6406       CmdArgs.push_back("/usr/libexec/ld.so");
6407     }
6408   }
6409
6410   if (Output.isFilename()) {
6411     CmdArgs.push_back("-o");
6412     CmdArgs.push_back(Output.getFilename());
6413   } else {
6414     assert(Output.isNothing() && "Invalid output.");
6415   }
6416
6417   if (!Args.hasArg(options::OPT_nostdlib) &&
6418       !Args.hasArg(options::OPT_nostartfiles)) {
6419     if (!Args.hasArg(options::OPT_shared)) {
6420       if (Args.hasArg(options::OPT_pg))
6421         CmdArgs.push_back(Args.MakeArgString(
6422                                 getToolChain().GetFilePath("gcrt0.o")));
6423       else
6424         CmdArgs.push_back(Args.MakeArgString(
6425                                 getToolChain().GetFilePath("crt0.o")));
6426       CmdArgs.push_back(Args.MakeArgString(
6427                               getToolChain().GetFilePath("crtbegin.o")));
6428     } else {
6429       CmdArgs.push_back(Args.MakeArgString(
6430                               getToolChain().GetFilePath("crtbeginS.o")));
6431     }
6432   }
6433
6434   Args.AddAllArgs(CmdArgs, options::OPT_L);
6435   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6436   Args.AddAllArgs(CmdArgs, options::OPT_e);
6437
6438   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6439
6440   if (!Args.hasArg(options::OPT_nostdlib) &&
6441       !Args.hasArg(options::OPT_nodefaultlibs)) {
6442     if (D.CCCIsCXX()) {
6443       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6444       if (Args.hasArg(options::OPT_pg))
6445         CmdArgs.push_back("-lm_p");
6446       else
6447         CmdArgs.push_back("-lm");
6448     }
6449
6450     if (Args.hasArg(options::OPT_pthread)) {
6451       if (!Args.hasArg(options::OPT_shared) &&
6452           Args.hasArg(options::OPT_pg))
6453         CmdArgs.push_back("-lpthread_p");
6454       else
6455         CmdArgs.push_back("-lpthread");
6456     }
6457
6458     if (!Args.hasArg(options::OPT_shared)) {
6459       if (Args.hasArg(options::OPT_pg))
6460         CmdArgs.push_back("-lc_p");
6461       else
6462         CmdArgs.push_back("-lc");
6463     }
6464
6465     StringRef MyArch;
6466     switch (getToolChain().getTriple().getArch()) {
6467     case llvm::Triple::arm:
6468       MyArch = "arm";
6469       break;
6470     case llvm::Triple::x86:
6471       MyArch = "i386";
6472       break;
6473     case llvm::Triple::x86_64:
6474       MyArch = "amd64";
6475       break;
6476     default:
6477       llvm_unreachable("Unsupported architecture");
6478     }
6479     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
6480   }
6481
6482   if (!Args.hasArg(options::OPT_nostdlib) &&
6483       !Args.hasArg(options::OPT_nostartfiles)) {
6484     if (!Args.hasArg(options::OPT_shared))
6485       CmdArgs.push_back(Args.MakeArgString(
6486                               getToolChain().GetFilePath("crtend.o")));
6487     else
6488       CmdArgs.push_back(Args.MakeArgString(
6489                               getToolChain().GetFilePath("crtendS.o")));
6490   }
6491
6492   const char *Exec =
6493     Args.MakeArgString(getToolChain().GetLinkerPath());
6494   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6495 }
6496
6497 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6498                                      const InputInfo &Output,
6499                                      const InputInfoList &Inputs,
6500                                      const ArgList &Args,
6501                                      const char *LinkingOutput) const {
6502   claimNoWarnArgs(Args);
6503   ArgStringList CmdArgs;
6504
6505   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
6506   // instruct as in the base system to assemble 32-bit code.
6507   if (getToolChain().getArch() == llvm::Triple::x86)
6508     CmdArgs.push_back("--32");
6509   else if (getToolChain().getArch() == llvm::Triple::ppc)
6510     CmdArgs.push_back("-a32");
6511   else if (getToolChain().getArch() == llvm::Triple::mips ||
6512            getToolChain().getArch() == llvm::Triple::mipsel ||
6513            getToolChain().getArch() == llvm::Triple::mips64 ||
6514            getToolChain().getArch() == llvm::Triple::mips64el) {
6515     StringRef CPUName;
6516     StringRef ABIName;
6517     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6518
6519     CmdArgs.push_back("-march");
6520     CmdArgs.push_back(CPUName.data());
6521
6522     CmdArgs.push_back("-mabi");
6523     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6524
6525     if (getToolChain().getArch() == llvm::Triple::mips ||
6526         getToolChain().getArch() == llvm::Triple::mips64)
6527       CmdArgs.push_back("-EB");
6528     else
6529       CmdArgs.push_back("-EL");
6530
6531     addAssemblerKPIC(Args, CmdArgs);
6532   } else if (getToolChain().getArch() == llvm::Triple::arm ||
6533              getToolChain().getArch() == llvm::Triple::armeb ||
6534              getToolChain().getArch() == llvm::Triple::thumb ||
6535              getToolChain().getArch() == llvm::Triple::thumbeb) {
6536     const Driver &D = getToolChain().getDriver();
6537     const llvm::Triple &Triple = getToolChain().getTriple();
6538     StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
6539
6540     if (FloatABI == "hard") {
6541       CmdArgs.push_back("-mfpu=vfp");
6542     } else {
6543       CmdArgs.push_back("-mfpu=softvfp");
6544     }
6545
6546     switch(getToolChain().getTriple().getEnvironment()) {
6547     case llvm::Triple::GNUEABIHF:
6548     case llvm::Triple::GNUEABI:
6549     case llvm::Triple::EABI:
6550       CmdArgs.push_back("-meabi=5");
6551       break;
6552
6553     default:
6554       CmdArgs.push_back("-matpcs");
6555     }
6556   } else if (getToolChain().getArch() == llvm::Triple::sparc ||
6557              getToolChain().getArch() == llvm::Triple::sparcv9) {
6558     if (getToolChain().getArch() == llvm::Triple::sparc)
6559       CmdArgs.push_back("-Av8plusa");
6560     else
6561       CmdArgs.push_back("-Av9a");
6562
6563     addAssemblerKPIC(Args, CmdArgs);
6564   }
6565
6566   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6567                        options::OPT_Xassembler);
6568
6569   CmdArgs.push_back("-o");
6570   CmdArgs.push_back(Output.getFilename());
6571
6572   for (const auto &II : Inputs)
6573     CmdArgs.push_back(II.getFilename());
6574
6575   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6576   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6577 }
6578
6579 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6580                                  const InputInfo &Output,
6581                                  const InputInfoList &Inputs,
6582                                  const ArgList &Args,
6583                                  const char *LinkingOutput) const {
6584   const toolchains::FreeBSD& ToolChain = 
6585     static_cast<const toolchains::FreeBSD&>(getToolChain());
6586   const Driver &D = ToolChain.getDriver();
6587   const bool IsPIE =
6588     !Args.hasArg(options::OPT_shared) &&
6589     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
6590   ArgStringList CmdArgs;
6591
6592   // Silence warning for "clang -g foo.o -o foo"
6593   Args.ClaimAllArgs(options::OPT_g_Group);
6594   // and "clang -emit-llvm foo.o -o foo"
6595   Args.ClaimAllArgs(options::OPT_emit_llvm);
6596   // and for "clang -w foo.o -o foo". Other warning options are already
6597   // handled somewhere else.
6598   Args.ClaimAllArgs(options::OPT_w);
6599
6600   if (!D.SysRoot.empty())
6601     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6602
6603   if (IsPIE)
6604     CmdArgs.push_back("-pie");
6605
6606   if (Args.hasArg(options::OPT_static)) {
6607     CmdArgs.push_back("-Bstatic");
6608   } else {
6609     if (Args.hasArg(options::OPT_rdynamic))
6610       CmdArgs.push_back("-export-dynamic");
6611     CmdArgs.push_back("--eh-frame-hdr");
6612     if (Args.hasArg(options::OPT_shared)) {
6613       CmdArgs.push_back("-Bshareable");
6614     } else {
6615       CmdArgs.push_back("-dynamic-linker");
6616       CmdArgs.push_back("/libexec/ld-elf.so.1");
6617     }
6618     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
6619       llvm::Triple::ArchType Arch = ToolChain.getArch();
6620       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
6621           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6622         CmdArgs.push_back("--hash-style=both");
6623       }
6624     }
6625     CmdArgs.push_back("--enable-new-dtags");
6626   }
6627
6628   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
6629   // instruct ld in the base system to link 32-bit code.
6630   if (ToolChain.getArch() == llvm::Triple::x86) {
6631     CmdArgs.push_back("-m");
6632     CmdArgs.push_back("elf_i386_fbsd");
6633   }
6634
6635   if (ToolChain.getArch() == llvm::Triple::ppc) {
6636     CmdArgs.push_back("-m");
6637     CmdArgs.push_back("elf32ppc_fbsd");
6638   }
6639
6640   if (Arg *A = Args.getLastArg(options::OPT_G)) {
6641     if (ToolChain.getArch() == llvm::Triple::mips ||
6642       ToolChain.getArch() == llvm::Triple::mipsel ||
6643       ToolChain.getArch() == llvm::Triple::mips64 ||
6644       ToolChain.getArch() == llvm::Triple::mips64el) {
6645       StringRef v = A->getValue();
6646       CmdArgs.push_back(Args.MakeArgString("-G" + v));
6647       A->claim();
6648     }
6649   }
6650
6651   if (Output.isFilename()) {
6652     CmdArgs.push_back("-o");
6653     CmdArgs.push_back(Output.getFilename());
6654   } else {
6655     assert(Output.isNothing() && "Invalid output.");
6656   }
6657
6658   if (!Args.hasArg(options::OPT_nostdlib) &&
6659       !Args.hasArg(options::OPT_nostartfiles)) {
6660     const char *crt1 = nullptr;
6661     if (!Args.hasArg(options::OPT_shared)) {
6662       if (Args.hasArg(options::OPT_pg))
6663         crt1 = "gcrt1.o";
6664       else if (IsPIE)
6665         crt1 = "Scrt1.o";
6666       else
6667         crt1 = "crt1.o";
6668     }
6669     if (crt1)
6670       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6671
6672     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6673
6674     const char *crtbegin = nullptr;
6675     if (Args.hasArg(options::OPT_static))
6676       crtbegin = "crtbeginT.o";
6677     else if (Args.hasArg(options::OPT_shared) || IsPIE)
6678       crtbegin = "crtbeginS.o";
6679     else
6680       crtbegin = "crtbegin.o";
6681
6682     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6683   }
6684
6685   Args.AddAllArgs(CmdArgs, options::OPT_L);
6686   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6687   for (const auto &Path : Paths)
6688     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6689   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6690   Args.AddAllArgs(CmdArgs, options::OPT_e);
6691   Args.AddAllArgs(CmdArgs, options::OPT_s);
6692   Args.AddAllArgs(CmdArgs, options::OPT_t);
6693   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6694   Args.AddAllArgs(CmdArgs, options::OPT_r);
6695
6696   if (D.IsUsingLTO(Args))
6697     AddGoldPlugin(ToolChain, Args, CmdArgs);
6698
6699   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
6700   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6701
6702   if (!Args.hasArg(options::OPT_nostdlib) &&
6703       !Args.hasArg(options::OPT_nodefaultlibs)) {
6704     if (D.CCCIsCXX()) {
6705       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6706       if (Args.hasArg(options::OPT_pg))
6707         CmdArgs.push_back("-lm_p");
6708       else
6709         CmdArgs.push_back("-lm");
6710     }
6711     if (NeedsSanitizerDeps)
6712       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
6713     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
6714     // the default system libraries. Just mimic this for now.
6715     if (Args.hasArg(options::OPT_pg))
6716       CmdArgs.push_back("-lgcc_p");
6717     else
6718       CmdArgs.push_back("-lgcc");
6719     if (Args.hasArg(options::OPT_static)) {
6720       CmdArgs.push_back("-lgcc_eh");
6721     } else if (Args.hasArg(options::OPT_pg)) {
6722       CmdArgs.push_back("-lgcc_eh_p");
6723     } else {
6724       CmdArgs.push_back("--as-needed");
6725       CmdArgs.push_back("-lgcc_s");
6726       CmdArgs.push_back("--no-as-needed");
6727     }
6728
6729     if (Args.hasArg(options::OPT_pthread)) {
6730       if (Args.hasArg(options::OPT_pg))
6731         CmdArgs.push_back("-lpthread_p");
6732       else
6733         CmdArgs.push_back("-lpthread");
6734     }
6735
6736     if (Args.hasArg(options::OPT_pg)) {
6737       if (Args.hasArg(options::OPT_shared))
6738         CmdArgs.push_back("-lc");
6739       else
6740         CmdArgs.push_back("-lc_p");
6741       CmdArgs.push_back("-lgcc_p");
6742     } else {
6743       CmdArgs.push_back("-lc");
6744       CmdArgs.push_back("-lgcc");
6745     }
6746
6747     if (Args.hasArg(options::OPT_static)) {
6748       CmdArgs.push_back("-lgcc_eh");
6749     } else if (Args.hasArg(options::OPT_pg)) {
6750       CmdArgs.push_back("-lgcc_eh_p");
6751     } else {
6752       CmdArgs.push_back("--as-needed");
6753       CmdArgs.push_back("-lgcc_s");
6754       CmdArgs.push_back("--no-as-needed");
6755     }
6756   }
6757
6758   if (!Args.hasArg(options::OPT_nostdlib) &&
6759       !Args.hasArg(options::OPT_nostartfiles)) {
6760     if (Args.hasArg(options::OPT_shared) || IsPIE)
6761       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
6762     else
6763       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6764     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6765   }
6766
6767   addProfileRT(ToolChain, Args, CmdArgs);
6768
6769   const char *Exec =
6770     Args.MakeArgString(getToolChain().GetLinkerPath());
6771   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6772 }
6773
6774 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6775                                      const InputInfo &Output,
6776                                      const InputInfoList &Inputs,
6777                                      const ArgList &Args,
6778                                      const char *LinkingOutput) const {
6779   claimNoWarnArgs(Args);
6780   ArgStringList CmdArgs;
6781
6782   // GNU as needs different flags for creating the correct output format
6783   // on architectures with different ABIs or optional feature sets.
6784   switch (getToolChain().getArch()) {
6785   case llvm::Triple::x86:
6786     CmdArgs.push_back("--32");
6787     break;
6788   case llvm::Triple::arm:
6789   case llvm::Triple::armeb:
6790   case llvm::Triple::thumb:
6791   case llvm::Triple::thumbeb: {
6792     std::string MArch(arm::getARMTargetCPU(Args, getToolChain().getTriple()));
6793     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
6794     break;
6795   }
6796
6797   case llvm::Triple::mips:
6798   case llvm::Triple::mipsel:
6799   case llvm::Triple::mips64:
6800   case llvm::Triple::mips64el: {
6801     StringRef CPUName;
6802     StringRef ABIName;
6803     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6804
6805     CmdArgs.push_back("-march");
6806     CmdArgs.push_back(CPUName.data());
6807
6808     CmdArgs.push_back("-mabi");
6809     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6810
6811     if (getToolChain().getArch() == llvm::Triple::mips ||
6812         getToolChain().getArch() == llvm::Triple::mips64)
6813       CmdArgs.push_back("-EB");
6814     else
6815       CmdArgs.push_back("-EL");
6816
6817     addAssemblerKPIC(Args, CmdArgs);
6818     break;
6819   }
6820
6821   case llvm::Triple::sparc:
6822     CmdArgs.push_back("-32");
6823     addAssemblerKPIC(Args, CmdArgs);
6824     break;
6825
6826   case llvm::Triple::sparcv9:
6827     CmdArgs.push_back("-64");
6828     CmdArgs.push_back("-Av9");
6829     addAssemblerKPIC(Args, CmdArgs);
6830     break;
6831
6832   default:
6833     break;  
6834   }
6835
6836   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6837                        options::OPT_Xassembler);
6838
6839   CmdArgs.push_back("-o");
6840   CmdArgs.push_back(Output.getFilename());
6841
6842   for (const auto &II : Inputs)
6843     CmdArgs.push_back(II.getFilename());
6844
6845   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
6846   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6847 }
6848
6849 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6850                                  const InputInfo &Output,
6851                                  const InputInfoList &Inputs,
6852                                  const ArgList &Args,
6853                                  const char *LinkingOutput) const {
6854   const Driver &D = getToolChain().getDriver();
6855   ArgStringList CmdArgs;
6856
6857   if (!D.SysRoot.empty())
6858     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6859
6860   CmdArgs.push_back("--eh-frame-hdr");
6861   if (Args.hasArg(options::OPT_static)) {
6862     CmdArgs.push_back("-Bstatic");
6863   } else {
6864     if (Args.hasArg(options::OPT_rdynamic))
6865       CmdArgs.push_back("-export-dynamic");
6866     if (Args.hasArg(options::OPT_shared)) {
6867       CmdArgs.push_back("-Bshareable");
6868     } else {
6869       CmdArgs.push_back("-dynamic-linker");
6870       CmdArgs.push_back("/libexec/ld.elf_so");
6871     }
6872   }
6873
6874   // Many NetBSD architectures support more than one ABI.
6875   // Determine the correct emulation for ld.
6876   switch (getToolChain().getArch()) {
6877   case llvm::Triple::x86:
6878     CmdArgs.push_back("-m");
6879     CmdArgs.push_back("elf_i386");
6880     break;
6881   case llvm::Triple::arm:
6882   case llvm::Triple::thumb:
6883     CmdArgs.push_back("-m");
6884     switch (getToolChain().getTriple().getEnvironment()) {
6885     case llvm::Triple::EABI:
6886     case llvm::Triple::GNUEABI:
6887       CmdArgs.push_back("armelf_nbsd_eabi");
6888       break;
6889     case llvm::Triple::EABIHF:
6890     case llvm::Triple::GNUEABIHF:
6891       CmdArgs.push_back("armelf_nbsd_eabihf");
6892       break;
6893     default:
6894       CmdArgs.push_back("armelf_nbsd");
6895       break;
6896     }
6897     break;
6898   case llvm::Triple::armeb:
6899   case llvm::Triple::thumbeb:
6900     CmdArgs.push_back("-m");
6901     switch (getToolChain().getTriple().getEnvironment()) {
6902     case llvm::Triple::EABI:
6903     case llvm::Triple::GNUEABI:
6904       CmdArgs.push_back("armelfb_nbsd_eabi");
6905       break;
6906     case llvm::Triple::EABIHF:
6907     case llvm::Triple::GNUEABIHF:
6908       CmdArgs.push_back("armelfb_nbsd_eabihf");
6909       break;
6910     default:
6911       CmdArgs.push_back("armelfb_nbsd");
6912       break;
6913     }
6914     break;
6915   case llvm::Triple::mips64:
6916   case llvm::Triple::mips64el:
6917     if (mips::hasMipsAbiArg(Args, "32")) {
6918       CmdArgs.push_back("-m");
6919       if (getToolChain().getArch() == llvm::Triple::mips64)
6920         CmdArgs.push_back("elf32btsmip");
6921       else
6922         CmdArgs.push_back("elf32ltsmip");
6923    } else if (mips::hasMipsAbiArg(Args, "64")) {
6924      CmdArgs.push_back("-m");
6925      if (getToolChain().getArch() == llvm::Triple::mips64)
6926        CmdArgs.push_back("elf64btsmip");
6927      else
6928        CmdArgs.push_back("elf64ltsmip");
6929    }
6930    break;
6931   case llvm::Triple::ppc:
6932     CmdArgs.push_back("-m");
6933     CmdArgs.push_back("elf32ppc_nbsd");
6934     break;
6935
6936   case llvm::Triple::ppc64:
6937   case llvm::Triple::ppc64le:
6938     CmdArgs.push_back("-m");
6939     CmdArgs.push_back("elf64ppc");
6940     break;
6941
6942   case llvm::Triple::sparc:
6943     CmdArgs.push_back("-m");
6944     CmdArgs.push_back("elf32_sparc");
6945     break;
6946
6947   case llvm::Triple::sparcv9:
6948     CmdArgs.push_back("-m");
6949     CmdArgs.push_back("elf64_sparc");
6950     break;
6951
6952   default:
6953     break;
6954   }
6955
6956   if (Output.isFilename()) {
6957     CmdArgs.push_back("-o");
6958     CmdArgs.push_back(Output.getFilename());
6959   } else {
6960     assert(Output.isNothing() && "Invalid output.");
6961   }
6962
6963   if (!Args.hasArg(options::OPT_nostdlib) &&
6964       !Args.hasArg(options::OPT_nostartfiles)) {
6965     if (!Args.hasArg(options::OPT_shared)) {
6966       CmdArgs.push_back(Args.MakeArgString(
6967                               getToolChain().GetFilePath("crt0.o")));
6968       CmdArgs.push_back(Args.MakeArgString(
6969                               getToolChain().GetFilePath("crti.o")));
6970       CmdArgs.push_back(Args.MakeArgString(
6971                               getToolChain().GetFilePath("crtbegin.o")));
6972     } else {
6973       CmdArgs.push_back(Args.MakeArgString(
6974                               getToolChain().GetFilePath("crti.o")));
6975       CmdArgs.push_back(Args.MakeArgString(
6976                               getToolChain().GetFilePath("crtbeginS.o")));
6977     }
6978   }
6979
6980   Args.AddAllArgs(CmdArgs, options::OPT_L);
6981   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6982   Args.AddAllArgs(CmdArgs, options::OPT_e);
6983   Args.AddAllArgs(CmdArgs, options::OPT_s);
6984   Args.AddAllArgs(CmdArgs, options::OPT_t);
6985   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6986   Args.AddAllArgs(CmdArgs, options::OPT_r);
6987
6988   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6989
6990   unsigned Major, Minor, Micro;
6991   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6992   bool useLibgcc = true;
6993   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
6994     switch(getToolChain().getArch()) {
6995     case llvm::Triple::aarch64:
6996     case llvm::Triple::arm:
6997     case llvm::Triple::armeb:
6998     case llvm::Triple::thumb:
6999     case llvm::Triple::thumbeb:
7000     case llvm::Triple::ppc:
7001     case llvm::Triple::ppc64:
7002     case llvm::Triple::ppc64le:
7003     case llvm::Triple::x86:
7004     case llvm::Triple::x86_64:
7005       useLibgcc = false;
7006       break;
7007     default:
7008       break;
7009     }
7010   }
7011
7012   if (!Args.hasArg(options::OPT_nostdlib) &&
7013       !Args.hasArg(options::OPT_nodefaultlibs)) {
7014     if (D.CCCIsCXX()) {
7015       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7016       CmdArgs.push_back("-lm");
7017     }
7018     if (Args.hasArg(options::OPT_pthread))
7019       CmdArgs.push_back("-lpthread");
7020     CmdArgs.push_back("-lc");
7021
7022     if (useLibgcc) {
7023       if (Args.hasArg(options::OPT_static)) {
7024         // libgcc_eh depends on libc, so resolve as much as possible,
7025         // pull in any new requirements from libc and then get the rest
7026         // of libgcc.
7027         CmdArgs.push_back("-lgcc_eh");
7028         CmdArgs.push_back("-lc");
7029         CmdArgs.push_back("-lgcc");
7030       } else {
7031         CmdArgs.push_back("-lgcc");
7032         CmdArgs.push_back("--as-needed");
7033         CmdArgs.push_back("-lgcc_s");
7034         CmdArgs.push_back("--no-as-needed");
7035       }
7036     }
7037   }
7038
7039   if (!Args.hasArg(options::OPT_nostdlib) &&
7040       !Args.hasArg(options::OPT_nostartfiles)) {
7041     if (!Args.hasArg(options::OPT_shared))
7042       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7043                                                                   "crtend.o")));
7044     else
7045       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7046                                                                  "crtendS.o")));
7047     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7048                                                                     "crtn.o")));
7049   }
7050
7051   addProfileRT(getToolChain(), Args, CmdArgs);
7052
7053   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7054   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7055 }
7056
7057 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7058                                       const InputInfo &Output,
7059                                       const InputInfoList &Inputs,
7060                                       const ArgList &Args,
7061                                       const char *LinkingOutput) const {
7062   claimNoWarnArgs(Args);
7063
7064   ArgStringList CmdArgs;
7065   bool NeedsKPIC = false;
7066
7067   // Add --32/--64 to make sure we get the format we want.
7068   // This is incomplete
7069   if (getToolChain().getArch() == llvm::Triple::x86) {
7070     CmdArgs.push_back("--32");
7071   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
7072     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7073       CmdArgs.push_back("--x32");
7074     else
7075       CmdArgs.push_back("--64");
7076   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
7077     CmdArgs.push_back("-a32");
7078     CmdArgs.push_back("-mppc");
7079     CmdArgs.push_back("-many");
7080   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
7081     CmdArgs.push_back("-a64");
7082     CmdArgs.push_back("-mppc64");
7083     CmdArgs.push_back("-many");
7084   } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
7085     CmdArgs.push_back("-a64");
7086     CmdArgs.push_back("-mppc64");
7087     CmdArgs.push_back("-many");
7088     CmdArgs.push_back("-mlittle-endian");
7089   } else if (getToolChain().getArch() == llvm::Triple::sparc) {
7090     CmdArgs.push_back("-32");
7091     CmdArgs.push_back("-Av8plusa");
7092     NeedsKPIC = true;
7093   } else if (getToolChain().getArch() == llvm::Triple::sparcv9) {
7094     CmdArgs.push_back("-64");
7095     CmdArgs.push_back("-Av9a");
7096     NeedsKPIC = true;
7097   } else if (getToolChain().getArch() == llvm::Triple::arm ||
7098              getToolChain().getArch() == llvm::Triple::armeb) {
7099     StringRef MArch = getToolChain().getArchName();
7100     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
7101       CmdArgs.push_back("-mfpu=neon");
7102     if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a" ||
7103         MArch == "armebv8" || MArch == "armebv8a" || MArch == "armebv8-a")
7104       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7105
7106     StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7107         getToolChain().getDriver(), Args, getToolChain().getTriple());
7108     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7109
7110     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7111
7112     // FIXME: remove krait check when GNU tools support krait cpu
7113     // for now replace it with -march=armv7-a  to avoid a lower
7114     // march from being picked in the absence of a cpu flag.
7115     Arg *A;
7116     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7117       StringRef(A->getValue()) == "krait")
7118         CmdArgs.push_back("-march=armv7-a");
7119     else
7120       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7121     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7122   } else if (getToolChain().getArch() == llvm::Triple::mips ||
7123              getToolChain().getArch() == llvm::Triple::mipsel ||
7124              getToolChain().getArch() == llvm::Triple::mips64 ||
7125              getToolChain().getArch() == llvm::Triple::mips64el) {
7126     StringRef CPUName;
7127     StringRef ABIName;
7128     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7129     ABIName = getGnuCompatibleMipsABIName(ABIName);
7130
7131     CmdArgs.push_back("-march");
7132     CmdArgs.push_back(CPUName.data());
7133
7134     CmdArgs.push_back("-mabi");
7135     CmdArgs.push_back(ABIName.data());
7136
7137     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7138     // or -mshared (not implemented) is in effect.
7139     bool IsPicOrPie = false;
7140     if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7141                                  options::OPT_fpic, options::OPT_fno_pic,
7142                                  options::OPT_fPIE, options::OPT_fno_PIE,
7143                                  options::OPT_fpie, options::OPT_fno_pie)) {
7144       if (A->getOption().matches(options::OPT_fPIC) ||
7145           A->getOption().matches(options::OPT_fpic) ||
7146           A->getOption().matches(options::OPT_fPIE) ||
7147           A->getOption().matches(options::OPT_fpie))
7148         IsPicOrPie = true;
7149     }
7150     if (!IsPicOrPie)
7151       CmdArgs.push_back("-mno-shared");
7152
7153     // LLVM doesn't support -mplt yet and acts as if it is always given.
7154     // However, -mplt has no effect with the N64 ABI.
7155     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7156
7157     if (getToolChain().getArch() == llvm::Triple::mips ||
7158         getToolChain().getArch() == llvm::Triple::mips64)
7159       CmdArgs.push_back("-EB");
7160     else
7161       CmdArgs.push_back("-EL");
7162
7163     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7164       if (StringRef(A->getValue()) == "2008")
7165         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7166     }
7167
7168     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7169     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7170                                  options::OPT_mfp64)) {
7171       A->claim();
7172       A->render(Args, CmdArgs);
7173     } else if (mips::isFPXXDefault(getToolChain().getTriple(), CPUName,
7174                                    ABIName))
7175       CmdArgs.push_back("-mfpxx");
7176
7177     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7178     // -mno-mips16 is actually -no-mips16.
7179     if (Arg *A = Args.getLastArg(options::OPT_mips16,
7180                                  options::OPT_mno_mips16)) {
7181       if (A->getOption().matches(options::OPT_mips16)) {
7182         A->claim();
7183         A->render(Args, CmdArgs);
7184       } else {
7185         A->claim();
7186         CmdArgs.push_back("-no-mips16");
7187       }
7188     }
7189
7190     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7191                     options::OPT_mno_micromips);
7192     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7193     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7194
7195     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7196       // Do not use AddLastArg because not all versions of MIPS assembler
7197       // support -mmsa / -mno-msa options.
7198       if (A->getOption().matches(options::OPT_mmsa))
7199         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7200     }
7201
7202     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7203                     options::OPT_msoft_float);
7204
7205     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7206                     options::OPT_mno_odd_spreg);
7207
7208     NeedsKPIC = true;
7209   } else if (getToolChain().getArch() == llvm::Triple::systemz) {
7210     // Always pass an -march option, since our default of z10 is later
7211     // than the GNU assembler's default.
7212     StringRef CPUName = getSystemZTargetCPU(Args);
7213     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7214   }
7215
7216   if (NeedsKPIC)
7217     addAssemblerKPIC(Args, CmdArgs);
7218
7219   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7220                        options::OPT_Xassembler);
7221
7222   CmdArgs.push_back("-o");
7223   CmdArgs.push_back(Output.getFilename());
7224
7225   for (const auto &II : Inputs)
7226     CmdArgs.push_back(II.getFilename());
7227
7228   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7229   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7230
7231   // Handle the debug info splitting at object creation time if we're
7232   // creating an object.
7233   // TODO: Currently only works on linux with newer objcopy.
7234   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7235       getToolChain().getTriple().isOSLinux())
7236     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7237                    SplitDebugName(Args, Inputs));
7238 }
7239
7240 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7241                       ArgStringList &CmdArgs, const ArgList &Args) {
7242   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7243   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7244                       Args.hasArg(options::OPT_static);
7245   if (!D.CCCIsCXX())
7246     CmdArgs.push_back("-lgcc");
7247
7248   if (StaticLibgcc || isAndroid) {
7249     if (D.CCCIsCXX())
7250       CmdArgs.push_back("-lgcc");
7251   } else {
7252     if (!D.CCCIsCXX())
7253       CmdArgs.push_back("--as-needed");
7254     CmdArgs.push_back("-lgcc_s");
7255     if (!D.CCCIsCXX())
7256       CmdArgs.push_back("--no-as-needed");
7257   }
7258
7259   if (StaticLibgcc && !isAndroid)
7260     CmdArgs.push_back("-lgcc_eh");
7261   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7262     CmdArgs.push_back("-lgcc");
7263
7264   // According to Android ABI, we have to link with libdl if we are
7265   // linking with non-static libgcc.
7266   //
7267   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
7268   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7269   if (isAndroid && !StaticLibgcc)
7270     CmdArgs.push_back("-ldl");
7271 }
7272
7273 static std::string getLinuxDynamicLinker(const ArgList &Args,
7274                                          const toolchains::Linux &ToolChain) {
7275   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7276     if (ToolChain.getTriple().isArch64Bit())
7277       return "/system/bin/linker64";
7278     else
7279       return "/system/bin/linker";
7280   } else if (ToolChain.getArch() == llvm::Triple::x86 ||
7281              ToolChain.getArch() == llvm::Triple::sparc)
7282     return "/lib/ld-linux.so.2";
7283   else if (ToolChain.getArch() == llvm::Triple::aarch64)
7284     return "/lib/ld-linux-aarch64.so.1";
7285   else if (ToolChain.getArch() == llvm::Triple::aarch64_be)
7286     return "/lib/ld-linux-aarch64_be.so.1";
7287   else if (ToolChain.getArch() == llvm::Triple::arm ||
7288            ToolChain.getArch() == llvm::Triple::thumb) {
7289     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7290       return "/lib/ld-linux-armhf.so.3";
7291     else
7292       return "/lib/ld-linux.so.3";
7293   } else if (ToolChain.getArch() == llvm::Triple::armeb ||
7294              ToolChain.getArch() == llvm::Triple::thumbeb) {
7295     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7296       return "/lib/ld-linux-armhf.so.3";        /* TODO: check which dynamic linker name.  */
7297     else
7298       return "/lib/ld-linux.so.3";              /* TODO: check which dynamic linker name.  */
7299   } else if (ToolChain.getArch() == llvm::Triple::mips ||
7300              ToolChain.getArch() == llvm::Triple::mipsel ||
7301              ToolChain.getArch() == llvm::Triple::mips64 ||
7302              ToolChain.getArch() == llvm::Triple::mips64el) {
7303     StringRef CPUName;
7304     StringRef ABIName;
7305     mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
7306     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
7307
7308     StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
7309                            .Case("o32", "/lib")
7310                            .Case("n32", "/lib32")
7311                            .Case("n64", "/lib64")
7312                            .Default("/lib");
7313     StringRef LibName;
7314     if (mips::isUCLibc(Args))
7315       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
7316     else
7317       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
7318
7319     return (LibDir + "/" + LibName).str();
7320   } else if (ToolChain.getArch() == llvm::Triple::ppc)
7321     return "/lib/ld.so.1";
7322   else if (ToolChain.getArch() == llvm::Triple::ppc64) {
7323     if (ppc::hasPPCAbiArg(Args, "elfv2"))
7324       return "/lib64/ld64.so.2";
7325     return "/lib64/ld64.so.1";
7326   } else if (ToolChain.getArch() == llvm::Triple::ppc64le) {
7327     if (ppc::hasPPCAbiArg(Args, "elfv1"))
7328       return "/lib64/ld64.so.1";
7329     return "/lib64/ld64.so.2";
7330   } else if (ToolChain.getArch() == llvm::Triple::systemz)
7331     return "/lib64/ld64.so.1";
7332   else if (ToolChain.getArch() == llvm::Triple::sparcv9)
7333     return "/lib64/ld-linux.so.2";
7334   else if (ToolChain.getArch() == llvm::Triple::x86_64 &&
7335            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7336     return "/libx32/ld-linux-x32.so.2";
7337   else
7338     return "/lib64/ld-linux-x86-64.so.2";
7339 }
7340
7341 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
7342                            ArgStringList &CmdArgs, const ArgList &Args) {
7343   // Make use of compiler-rt if --rtlib option is used
7344   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
7345
7346   switch (RLT) {
7347   case ToolChain::RLT_CompilerRT:
7348     switch (TC.getTriple().getOS()) {
7349     default: llvm_unreachable("unsupported OS");
7350     case llvm::Triple::Win32:
7351     case llvm::Triple::Linux:
7352       addClangRT(TC, Args, CmdArgs);
7353       break;
7354     }
7355     break;
7356   case ToolChain::RLT_Libgcc:
7357     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
7358     break;
7359   }
7360 }
7361
7362 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
7363   switch (T.getArch()) {
7364   case llvm::Triple::x86:
7365     return "elf_i386";
7366   case llvm::Triple::aarch64:
7367     return "aarch64linux";
7368   case llvm::Triple::aarch64_be:
7369     return "aarch64_be_linux";
7370   case llvm::Triple::arm:
7371   case llvm::Triple::thumb:
7372     return "armelf_linux_eabi";
7373   case llvm::Triple::armeb:
7374   case llvm::Triple::thumbeb:
7375     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
7376   case llvm::Triple::ppc:
7377     return "elf32ppclinux";
7378   case llvm::Triple::ppc64:
7379     return "elf64ppc";
7380   case llvm::Triple::ppc64le:
7381     return "elf64lppc";
7382   case llvm::Triple::sparc:
7383     return "elf32_sparc";
7384   case llvm::Triple::sparcv9:
7385     return "elf64_sparc";
7386   case llvm::Triple::mips:
7387     return "elf32btsmip";
7388   case llvm::Triple::mipsel:
7389     return "elf32ltsmip";
7390   case llvm::Triple::mips64:
7391     if (mips::hasMipsAbiArg(Args, "n32"))
7392       return "elf32btsmipn32";
7393     return "elf64btsmip";
7394   case llvm::Triple::mips64el:
7395     if (mips::hasMipsAbiArg(Args, "n32"))
7396       return "elf32ltsmipn32";
7397     return "elf64ltsmip";
7398   case llvm::Triple::systemz:
7399     return "elf64_s390";
7400   case llvm::Triple::x86_64:
7401     if (T.getEnvironment() == llvm::Triple::GNUX32)
7402       return "elf32_x86_64";
7403     return "elf_x86_64";
7404   default:
7405     llvm_unreachable("Unexpected arch");
7406   }
7407 }
7408
7409 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
7410                                   const InputInfo &Output,
7411                                   const InputInfoList &Inputs,
7412                                   const ArgList &Args,
7413                                   const char *LinkingOutput) const {
7414   const toolchains::Linux& ToolChain =
7415     static_cast<const toolchains::Linux&>(getToolChain());
7416   const Driver &D = ToolChain.getDriver();
7417   const bool isAndroid =
7418     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
7419   const bool IsPIE =
7420     !Args.hasArg(options::OPT_shared) &&
7421     !Args.hasArg(options::OPT_static) &&
7422     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault() ||
7423      // On Android every code is PIC so every executable is PIE
7424      // Cannot use isPIEDefault here since otherwise
7425      // PIE only logic will be enabled during compilation
7426      isAndroid);
7427
7428   ArgStringList CmdArgs;
7429
7430   // Silence warning for "clang -g foo.o -o foo"
7431   Args.ClaimAllArgs(options::OPT_g_Group);
7432   // and "clang -emit-llvm foo.o -o foo"
7433   Args.ClaimAllArgs(options::OPT_emit_llvm);
7434   // and for "clang -w foo.o -o foo". Other warning options are already
7435   // handled somewhere else.
7436   Args.ClaimAllArgs(options::OPT_w);
7437
7438   if (!D.SysRoot.empty())
7439     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7440
7441   if (IsPIE)
7442     CmdArgs.push_back("-pie");
7443
7444   if (Args.hasArg(options::OPT_rdynamic))
7445     CmdArgs.push_back("-export-dynamic");
7446
7447   if (Args.hasArg(options::OPT_s))
7448     CmdArgs.push_back("-s");
7449
7450   for (const auto &Opt : ToolChain.ExtraOpts)
7451     CmdArgs.push_back(Opt.c_str());
7452
7453   if (!Args.hasArg(options::OPT_static)) {
7454     CmdArgs.push_back("--eh-frame-hdr");
7455   }
7456
7457   CmdArgs.push_back("-m");
7458   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
7459
7460   if (Args.hasArg(options::OPT_static)) {
7461     if (ToolChain.getArch() == llvm::Triple::arm ||
7462         ToolChain.getArch() == llvm::Triple::armeb ||
7463         ToolChain.getArch() == llvm::Triple::thumb ||
7464         ToolChain.getArch() == llvm::Triple::thumbeb)
7465       CmdArgs.push_back("-Bstatic");
7466     else
7467       CmdArgs.push_back("-static");
7468   } else if (Args.hasArg(options::OPT_shared)) {
7469     CmdArgs.push_back("-shared");
7470   }
7471
7472   if (ToolChain.getArch() == llvm::Triple::arm ||
7473       ToolChain.getArch() == llvm::Triple::armeb ||
7474       ToolChain.getArch() == llvm::Triple::thumb ||
7475       ToolChain.getArch() == llvm::Triple::thumbeb ||
7476       (!Args.hasArg(options::OPT_static) &&
7477        !Args.hasArg(options::OPT_shared))) {
7478     CmdArgs.push_back("-dynamic-linker");
7479     CmdArgs.push_back(Args.MakeArgString(
7480         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
7481   }
7482
7483   CmdArgs.push_back("-o");
7484   CmdArgs.push_back(Output.getFilename());
7485
7486   if (!Args.hasArg(options::OPT_nostdlib) &&
7487       !Args.hasArg(options::OPT_nostartfiles)) {
7488     if (!isAndroid) {
7489       const char *crt1 = nullptr;
7490       if (!Args.hasArg(options::OPT_shared)){
7491         if (Args.hasArg(options::OPT_pg))
7492           crt1 = "gcrt1.o";
7493         else if (IsPIE)
7494           crt1 = "Scrt1.o";
7495         else
7496           crt1 = "crt1.o";
7497       }
7498       if (crt1)
7499         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7500
7501       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7502     }
7503
7504     const char *crtbegin;
7505     if (Args.hasArg(options::OPT_static))
7506       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
7507     else if (Args.hasArg(options::OPT_shared))
7508       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
7509     else if (IsPIE)
7510       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
7511     else
7512       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
7513     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7514
7515     // Add crtfastmath.o if available and fast math is enabled.
7516     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
7517   }
7518
7519   Args.AddAllArgs(CmdArgs, options::OPT_L);
7520   Args.AddAllArgs(CmdArgs, options::OPT_u);
7521
7522   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7523
7524   for (const auto &Path : Paths)
7525     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7526
7527   if (D.IsUsingLTO(Args))
7528     AddGoldPlugin(ToolChain, Args, CmdArgs);
7529
7530   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7531     CmdArgs.push_back("--no-demangle");
7532
7533   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7534   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7535   // The profile runtime also needs access to system libraries.
7536   addProfileRT(getToolChain(), Args, CmdArgs);
7537
7538   if (D.CCCIsCXX() &&
7539       !Args.hasArg(options::OPT_nostdlib) &&
7540       !Args.hasArg(options::OPT_nodefaultlibs)) {
7541     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
7542       !Args.hasArg(options::OPT_static);
7543     if (OnlyLibstdcxxStatic)
7544       CmdArgs.push_back("-Bstatic");
7545     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7546     if (OnlyLibstdcxxStatic)
7547       CmdArgs.push_back("-Bdynamic");
7548     CmdArgs.push_back("-lm");
7549   }
7550
7551   if (!Args.hasArg(options::OPT_nostdlib)) {
7552     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
7553       if (Args.hasArg(options::OPT_static))
7554         CmdArgs.push_back("--start-group");
7555
7556       if (NeedsSanitizerDeps)
7557         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7558
7559       LibOpenMP UsedOpenMPLib = LibUnknown;
7560       if (Args.hasArg(options::OPT_fopenmp)) {
7561         UsedOpenMPLib = LibGOMP;
7562       } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
7563         UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
7564             .Case("libgomp",  LibGOMP)
7565             .Case("libiomp5", LibIOMP5)
7566             .Default(LibUnknown);
7567         if (UsedOpenMPLib == LibUnknown)
7568           D.Diag(diag::err_drv_unsupported_option_argument)
7569             << A->getOption().getName() << A->getValue();
7570       }
7571       switch (UsedOpenMPLib) {
7572       case LibGOMP:
7573         CmdArgs.push_back("-lgomp");
7574
7575         // FIXME: Exclude this for platforms with libgomp that don't require
7576         // librt. Most modern Linux platforms require it, but some may not.
7577         CmdArgs.push_back("-lrt");
7578         break;
7579       case LibIOMP5:
7580         CmdArgs.push_back("-liomp5");
7581         break;
7582       case LibUnknown:
7583         break;
7584       }
7585       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
7586
7587       if ((Args.hasArg(options::OPT_pthread) ||
7588            Args.hasArg(options::OPT_pthreads) || UsedOpenMPLib != LibUnknown) &&
7589           !isAndroid)
7590         CmdArgs.push_back("-lpthread");
7591
7592       CmdArgs.push_back("-lc");
7593
7594       if (Args.hasArg(options::OPT_static))
7595         CmdArgs.push_back("--end-group");
7596       else
7597         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
7598     }
7599
7600     if (!Args.hasArg(options::OPT_nostartfiles)) {
7601       const char *crtend;
7602       if (Args.hasArg(options::OPT_shared))
7603         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
7604       else if (IsPIE)
7605         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
7606       else
7607         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
7608
7609       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
7610       if (!isAndroid)
7611         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7612     }
7613   }
7614
7615   C.addCommand(
7616       llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
7617 }
7618
7619 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7620                                    const InputInfo &Output,
7621                                    const InputInfoList &Inputs,
7622                                    const ArgList &Args,
7623                                    const char *LinkingOutput) const {
7624   claimNoWarnArgs(Args);
7625   ArgStringList CmdArgs;
7626
7627   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7628
7629   CmdArgs.push_back("-o");
7630   CmdArgs.push_back(Output.getFilename());
7631
7632   for (const auto &II : Inputs)
7633     CmdArgs.push_back(II.getFilename());
7634
7635   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7636   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7637 }
7638
7639 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
7640                                const InputInfo &Output,
7641                                const InputInfoList &Inputs,
7642                                const ArgList &Args,
7643                                const char *LinkingOutput) const {
7644   const Driver &D = getToolChain().getDriver();
7645   ArgStringList CmdArgs;
7646
7647   if (Output.isFilename()) {
7648     CmdArgs.push_back("-o");
7649     CmdArgs.push_back(Output.getFilename());
7650   } else {
7651     assert(Output.isNothing() && "Invalid output.");
7652   }
7653
7654   if (!Args.hasArg(options::OPT_nostdlib) &&
7655       !Args.hasArg(options::OPT_nostartfiles)) {
7656       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7657       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7658       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7659       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7660   }
7661
7662   Args.AddAllArgs(CmdArgs, options::OPT_L);
7663   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7664   Args.AddAllArgs(CmdArgs, options::OPT_e);
7665
7666   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7667
7668   addProfileRT(getToolChain(), Args, CmdArgs);
7669
7670   if (!Args.hasArg(options::OPT_nostdlib) &&
7671       !Args.hasArg(options::OPT_nodefaultlibs)) {
7672     if (D.CCCIsCXX()) {
7673       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7674       CmdArgs.push_back("-lm");
7675     }
7676   }
7677
7678   if (!Args.hasArg(options::OPT_nostdlib) &&
7679       !Args.hasArg(options::OPT_nostartfiles)) {
7680     if (Args.hasArg(options::OPT_pthread))
7681       CmdArgs.push_back("-lpthread");
7682     CmdArgs.push_back("-lc");
7683     CmdArgs.push_back("-lCompilerRT-Generic");
7684     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
7685     CmdArgs.push_back(
7686          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7687   }
7688
7689   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7690   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7691 }
7692
7693 /// DragonFly Tools
7694
7695 // For now, DragonFly Assemble does just about the same as for
7696 // FreeBSD, but this may change soon.
7697 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7698                                        const InputInfo &Output,
7699                                        const InputInfoList &Inputs,
7700                                        const ArgList &Args,
7701                                        const char *LinkingOutput) const {
7702   claimNoWarnArgs(Args);
7703   ArgStringList CmdArgs;
7704
7705   // When building 32-bit code on DragonFly/pc64, we have to explicitly
7706   // instruct as in the base system to assemble 32-bit code.
7707   if (getToolChain().getArch() == llvm::Triple::x86)
7708     CmdArgs.push_back("--32");
7709
7710   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7711
7712   CmdArgs.push_back("-o");
7713   CmdArgs.push_back(Output.getFilename());
7714
7715   for (const auto &II : Inputs)
7716     CmdArgs.push_back(II.getFilename());
7717
7718   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7719   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7720 }
7721
7722 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
7723                                    const InputInfo &Output,
7724                                    const InputInfoList &Inputs,
7725                                    const ArgList &Args,
7726                                    const char *LinkingOutput) const {
7727   const Driver &D = getToolChain().getDriver();
7728   ArgStringList CmdArgs;
7729   bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
7730
7731   if (!D.SysRoot.empty())
7732     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7733
7734   CmdArgs.push_back("--eh-frame-hdr");
7735   if (Args.hasArg(options::OPT_static)) {
7736     CmdArgs.push_back("-Bstatic");
7737   } else {
7738     if (Args.hasArg(options::OPT_rdynamic))
7739       CmdArgs.push_back("-export-dynamic");
7740     if (Args.hasArg(options::OPT_shared))
7741       CmdArgs.push_back("-Bshareable");
7742     else {
7743       CmdArgs.push_back("-dynamic-linker");
7744       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
7745     }
7746     CmdArgs.push_back("--hash-style=both");
7747   }
7748
7749   // When building 32-bit code on DragonFly/pc64, we have to explicitly
7750   // instruct ld in the base system to link 32-bit code.
7751   if (getToolChain().getArch() == llvm::Triple::x86) {
7752     CmdArgs.push_back("-m");
7753     CmdArgs.push_back("elf_i386");
7754   }
7755
7756   if (Output.isFilename()) {
7757     CmdArgs.push_back("-o");
7758     CmdArgs.push_back(Output.getFilename());
7759   } else {
7760     assert(Output.isNothing() && "Invalid output.");
7761   }
7762
7763   if (!Args.hasArg(options::OPT_nostdlib) &&
7764       !Args.hasArg(options::OPT_nostartfiles)) {
7765     if (!Args.hasArg(options::OPT_shared)) {
7766       if (Args.hasArg(options::OPT_pg))
7767         CmdArgs.push_back(Args.MakeArgString(
7768                                 getToolChain().GetFilePath("gcrt1.o")));
7769       else {
7770         if (Args.hasArg(options::OPT_pie))
7771           CmdArgs.push_back(Args.MakeArgString(
7772                                   getToolChain().GetFilePath("Scrt1.o")));
7773         else
7774           CmdArgs.push_back(Args.MakeArgString(
7775                                   getToolChain().GetFilePath("crt1.o")));
7776       }
7777     }
7778     CmdArgs.push_back(Args.MakeArgString(
7779                             getToolChain().GetFilePath("crti.o")));
7780     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
7781       CmdArgs.push_back(Args.MakeArgString(
7782                               getToolChain().GetFilePath("crtbeginS.o")));
7783     else
7784       CmdArgs.push_back(Args.MakeArgString(
7785                               getToolChain().GetFilePath("crtbegin.o")));
7786   }
7787
7788   Args.AddAllArgs(CmdArgs, options::OPT_L);
7789   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7790   Args.AddAllArgs(CmdArgs, options::OPT_e);
7791
7792   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7793
7794   if (!Args.hasArg(options::OPT_nostdlib) &&
7795       !Args.hasArg(options::OPT_nodefaultlibs)) {
7796     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
7797     //         rpaths
7798     if (UseGCC47)
7799       CmdArgs.push_back("-L/usr/lib/gcc47");
7800     else
7801       CmdArgs.push_back("-L/usr/lib/gcc44");
7802
7803     if (!Args.hasArg(options::OPT_static)) {
7804       if (UseGCC47) {
7805         CmdArgs.push_back("-rpath");
7806         CmdArgs.push_back("/usr/lib/gcc47");
7807       } else {
7808         CmdArgs.push_back("-rpath");
7809         CmdArgs.push_back("/usr/lib/gcc44");
7810       }
7811     }
7812
7813     if (D.CCCIsCXX()) {
7814       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7815       CmdArgs.push_back("-lm");
7816     }
7817
7818     if (Args.hasArg(options::OPT_pthread))
7819       CmdArgs.push_back("-lpthread");
7820
7821     if (!Args.hasArg(options::OPT_nolibc)) {
7822       CmdArgs.push_back("-lc");
7823     }
7824
7825     if (UseGCC47) {
7826       if (Args.hasArg(options::OPT_static) ||
7827           Args.hasArg(options::OPT_static_libgcc)) {
7828         CmdArgs.push_back("-lgcc");
7829         CmdArgs.push_back("-lgcc_eh");
7830       } else {
7831         if (Args.hasArg(options::OPT_shared_libgcc)) {
7832           CmdArgs.push_back("-lgcc_pic");
7833           if (!Args.hasArg(options::OPT_shared))
7834             CmdArgs.push_back("-lgcc");
7835         } else {
7836           CmdArgs.push_back("-lgcc");
7837           CmdArgs.push_back("--as-needed");
7838           CmdArgs.push_back("-lgcc_pic");
7839           CmdArgs.push_back("--no-as-needed");
7840         }
7841       }
7842     } else {
7843       if (Args.hasArg(options::OPT_shared)) {
7844         CmdArgs.push_back("-lgcc_pic");
7845       } else {
7846         CmdArgs.push_back("-lgcc");
7847       }
7848     }
7849   }
7850
7851   if (!Args.hasArg(options::OPT_nostdlib) &&
7852       !Args.hasArg(options::OPT_nostartfiles)) {
7853     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
7854       CmdArgs.push_back(Args.MakeArgString(
7855                               getToolChain().GetFilePath("crtendS.o")));
7856     else
7857       CmdArgs.push_back(Args.MakeArgString(
7858                               getToolChain().GetFilePath("crtend.o")));
7859     CmdArgs.push_back(Args.MakeArgString(
7860                             getToolChain().GetFilePath("crtn.o")));
7861   }
7862
7863   addProfileRT(getToolChain(), Args, CmdArgs);
7864
7865   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7866   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7867 }
7868
7869 // Try to find Exe from a Visual Studio distribution.  This first tries to find
7870 // an installed copy of Visual Studio and, failing that, looks in the PATH,
7871 // making sure that whatever executable that's found is not a same-named exe
7872 // from clang itself to prevent clang from falling back to itself.
7873 static std::string FindVisualStudioExecutable(const ToolChain &TC,
7874                                               const char *Exe,
7875                                               const char *ClangProgramPath) {
7876   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
7877   std::string visualStudioBinDir;
7878   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
7879                                          visualStudioBinDir)) {
7880     SmallString<128> FilePath(visualStudioBinDir);
7881     llvm::sys::path::append(FilePath, Exe);
7882     if (llvm::sys::fs::can_execute(FilePath.c_str()))
7883       return FilePath.str();
7884   }
7885
7886   return Exe;
7887 }
7888
7889 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
7890                                       const InputInfo &Output,
7891                                       const InputInfoList &Inputs,
7892                                       const ArgList &Args,
7893                                       const char *LinkingOutput) const {
7894   ArgStringList CmdArgs;
7895   const ToolChain &TC = getToolChain();
7896
7897   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
7898   if (Output.isFilename())
7899     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
7900                                          Output.getFilename()));
7901
7902   if (!Args.hasArg(options::OPT_nostdlib) &&
7903       !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
7904     CmdArgs.push_back("-defaultlib:libcmt");
7905
7906   if (!llvm::sys::Process::GetEnv("LIB")) {
7907     // If the VC environment hasn't been configured (perhaps because the user
7908     // did not run vcvarsall), try to build a consistent link environment.  If
7909     // the environment variable is set however, assume the user knows what he's
7910     // doing.
7911     std::string VisualStudioDir;
7912     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
7913     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
7914       SmallString<128> LibDir(VisualStudioDir);
7915       llvm::sys::path::append(LibDir, "VC", "lib");
7916       switch (MSVC.getArch()) {
7917       case llvm::Triple::x86:
7918         // x86 just puts the libraries directly in lib
7919         break;
7920       case llvm::Triple::x86_64:
7921         llvm::sys::path::append(LibDir, "amd64");
7922         break;
7923       case llvm::Triple::arm:
7924         llvm::sys::path::append(LibDir, "arm");
7925         break;
7926       default:
7927         break;
7928       }
7929       CmdArgs.push_back(
7930           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
7931     }
7932
7933     std::string WindowsSdkLibPath;
7934     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
7935       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
7936                                            WindowsSdkLibPath.c_str()));
7937   }
7938
7939   CmdArgs.push_back("-nologo");
7940
7941   if (Args.hasArg(options::OPT_g_Group))
7942     CmdArgs.push_back("-debug");
7943
7944   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
7945   if (DLL) {
7946     CmdArgs.push_back(Args.MakeArgString("-dll"));
7947
7948     SmallString<128> ImplibName(Output.getFilename());
7949     llvm::sys::path::replace_extension(ImplibName, "lib");
7950     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
7951                                          ImplibName.str()));
7952   }
7953
7954   if (TC.getSanitizerArgs().needsAsanRt()) {
7955     CmdArgs.push_back(Args.MakeArgString("-debug"));
7956     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
7957     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
7958       static const char *CompilerRTComponents[] = {
7959         "asan_dynamic",
7960         "asan_dynamic_runtime_thunk",
7961       };
7962       for (const auto &Component : CompilerRTComponents)
7963         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
7964       // Make sure the dynamic runtime thunk is not optimized out at link time
7965       // to ensure proper SEH handling.
7966       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
7967     } else if (DLL) {
7968       CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
7969     } else {
7970       static const char *CompilerRTComponents[] = {
7971         "asan",
7972         "asan_cxx",
7973       };
7974       for (const auto &Component : CompilerRTComponents)
7975         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
7976     }
7977   }
7978
7979   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
7980
7981   // Add filenames, libraries, and other linker inputs.
7982   for (const auto &Input : Inputs) {
7983     if (Input.isFilename()) {
7984       CmdArgs.push_back(Input.getFilename());
7985       continue;
7986     }
7987
7988     const Arg &A = Input.getInputArg();
7989
7990     // Render -l options differently for the MSVC linker.
7991     if (A.getOption().matches(options::OPT_l)) {
7992       StringRef Lib = A.getValue();
7993       const char *LinkLibArg;
7994       if (Lib.endswith(".lib"))
7995         LinkLibArg = Args.MakeArgString(Lib);
7996       else
7997         LinkLibArg = Args.MakeArgString(Lib + ".lib");
7998       CmdArgs.push_back(LinkLibArg);
7999       continue;
8000     }
8001
8002     // Otherwise, this is some other kind of linker input option like -Wl, -z,
8003     // or -L. Render it, even if MSVC doesn't understand it.
8004     A.renderAsInput(Args, CmdArgs);
8005   }
8006
8007   // We need to special case some linker paths.  In the case of lld, we need to
8008   // translate 'lld' into 'lld-link', and in the case of the regular msvc
8009   // linker, we need to use a special search algorithm.
8010   llvm::SmallString<128> linkPath;
8011   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8012   if (Linker.equals_lower("lld"))
8013     Linker = "lld-link";
8014
8015   if (Linker.equals_lower("link")) {
8016     // If we're using the MSVC linker, it's not sufficient to just use link
8017     // from the program PATH, because other environments like GnuWin32 install
8018     // their own link.exe which may come first.
8019     linkPath = FindVisualStudioExecutable(TC, "link.exe",
8020                                           C.getDriver().getClangProgramPath());
8021   } else {
8022     linkPath = Linker;
8023     llvm::sys::path::replace_extension(linkPath, "exe");
8024     linkPath = TC.GetProgramPath(linkPath.c_str());
8025   }
8026
8027   const char *Exec = Args.MakeArgString(linkPath);
8028   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8029 }
8030
8031 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
8032                                          const InputInfo &Output,
8033                                          const InputInfoList &Inputs,
8034                                          const ArgList &Args,
8035                                          const char *LinkingOutput) const {
8036   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8037 }
8038
8039 std::unique_ptr<Command> visualstudio::Compile::GetCommand(
8040     Compilation &C, const JobAction &JA, const InputInfo &Output,
8041     const InputInfoList &Inputs, const ArgList &Args,
8042     const char *LinkingOutput) const {
8043   ArgStringList CmdArgs;
8044   CmdArgs.push_back("/nologo");
8045   CmdArgs.push_back("/c"); // Compile only.
8046   CmdArgs.push_back("/W0"); // No warnings.
8047
8048   // The goal is to be able to invoke this tool correctly based on
8049   // any flag accepted by clang-cl.
8050
8051   // These are spelled the same way in clang and cl.exe,.
8052   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8053   Args.AddAllArgs(CmdArgs, options::OPT_I);
8054
8055   // Optimization level.
8056   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8057     if (A->getOption().getID() == options::OPT_O0) {
8058       CmdArgs.push_back("/Od");
8059     } else {
8060       StringRef OptLevel = A->getValue();
8061       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8062         A->render(Args, CmdArgs);
8063       else if (OptLevel == "3")
8064         CmdArgs.push_back("/Ox");
8065     }
8066   }
8067
8068   // Flags for which clang-cl have an alias.
8069   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8070
8071   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8072                    /*default=*/false))
8073     CmdArgs.push_back("/GR-");
8074   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8075                                options::OPT_fno_function_sections))
8076     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8077                           ? "/Gy"
8078                           : "/Gy-");
8079   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8080                                options::OPT_fno_data_sections))
8081     CmdArgs.push_back(
8082         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8083   if (Args.hasArg(options::OPT_fsyntax_only))
8084     CmdArgs.push_back("/Zs");
8085   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8086     CmdArgs.push_back("/Z7");
8087
8088   std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
8089   for (const auto &Include : Includes)
8090     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8091
8092   // Flags that can simply be passed through.
8093   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8094   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8095   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8096
8097   // The order of these flags is relevant, so pick the last one.
8098   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8099                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8100     A->render(Args, CmdArgs);
8101
8102
8103   // Input filename.
8104   assert(Inputs.size() == 1);
8105   const InputInfo &II = Inputs[0];
8106   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8107   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8108   if (II.isFilename())
8109     CmdArgs.push_back(II.getFilename());
8110   else
8111     II.getInputArg().renderAsInput(Args, CmdArgs);
8112
8113   // Output filename.
8114   assert(Output.getType() == types::TY_Object);
8115   const char *Fo = Args.MakeArgString(std::string("/Fo") +
8116                                       Output.getFilename());
8117   CmdArgs.push_back(Fo);
8118
8119   const Driver &D = getToolChain().getDriver();
8120   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8121                                                 D.getClangProgramPath());
8122   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
8123                                     CmdArgs);
8124 }
8125
8126
8127 /// XCore Tools
8128 // We pass assemble and link construction to the xcc tool.
8129
8130 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8131                                        const InputInfo &Output,
8132                                        const InputInfoList &Inputs,
8133                                        const ArgList &Args,
8134                                        const char *LinkingOutput) const {
8135   claimNoWarnArgs(Args);
8136   ArgStringList CmdArgs;
8137
8138   CmdArgs.push_back("-o");
8139   CmdArgs.push_back(Output.getFilename());
8140
8141   CmdArgs.push_back("-c");
8142
8143   if (Args.hasArg(options::OPT_v))
8144     CmdArgs.push_back("-v");
8145
8146   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8147     if (!A->getOption().matches(options::OPT_g0))
8148       CmdArgs.push_back("-g");
8149
8150   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
8151                    false))
8152     CmdArgs.push_back("-fverbose-asm");
8153
8154   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
8155                        options::OPT_Xassembler);
8156
8157   for (const auto &II : Inputs)
8158     CmdArgs.push_back(II.getFilename());
8159
8160   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
8161   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8162 }
8163
8164 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
8165                                    const InputInfo &Output,
8166                                    const InputInfoList &Inputs,
8167                                    const ArgList &Args,
8168                                    const char *LinkingOutput) const {
8169   ArgStringList CmdArgs;
8170
8171   if (Output.isFilename()) {
8172     CmdArgs.push_back("-o");
8173     CmdArgs.push_back(Output.getFilename());
8174   } else {
8175     assert(Output.isNothing() && "Invalid output.");
8176   }
8177
8178   if (Args.hasArg(options::OPT_v))
8179     CmdArgs.push_back("-v");
8180
8181   if (exceptionSettings(Args, getToolChain().getTriple()))
8182     CmdArgs.push_back("-fexceptions");
8183
8184   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8185
8186   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
8187   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8188 }
8189
8190 void CrossWindows::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8191                                           const InputInfo &Output,
8192                                           const InputInfoList &Inputs,
8193                                           const ArgList &Args,
8194                                           const char *LinkingOutput) const {
8195   claimNoWarnArgs(Args);
8196   const auto &TC =
8197       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
8198   ArgStringList CmdArgs;
8199   const char *Exec;
8200
8201   switch (TC.getArch()) {
8202   default: llvm_unreachable("unsupported architecture");
8203   case llvm::Triple::arm:
8204   case llvm::Triple::thumb:
8205     break;
8206   case llvm::Triple::x86:
8207     CmdArgs.push_back("--32");
8208     break;
8209   case llvm::Triple::x86_64:
8210     CmdArgs.push_back("--64");
8211     break;
8212   }
8213
8214   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8215
8216   CmdArgs.push_back("-o");
8217   CmdArgs.push_back(Output.getFilename());
8218
8219   for (const auto &Input : Inputs)
8220     CmdArgs.push_back(Input.getFilename());
8221
8222   const std::string Assembler = TC.GetProgramPath("as");
8223   Exec = Args.MakeArgString(Assembler);
8224
8225   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8226 }
8227
8228 void CrossWindows::Link::ConstructJob(Compilation &C, const JobAction &JA,
8229                                       const InputInfo &Output,
8230                                       const InputInfoList &Inputs,
8231                                       const ArgList &Args,
8232                                       const char *LinkingOutput) const {
8233   const auto &TC =
8234       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
8235   const llvm::Triple &T = TC.getTriple();
8236   const Driver &D = TC.getDriver();
8237   SmallString<128> EntryPoint;
8238   ArgStringList CmdArgs;
8239   const char *Exec;
8240
8241   // Silence warning for "clang -g foo.o -o foo"
8242   Args.ClaimAllArgs(options::OPT_g_Group);
8243   // and "clang -emit-llvm foo.o -o foo"
8244   Args.ClaimAllArgs(options::OPT_emit_llvm);
8245   // and for "clang -w foo.o -o foo"
8246   Args.ClaimAllArgs(options::OPT_w);
8247   // Other warning options are already handled somewhere else.
8248
8249   if (!D.SysRoot.empty())
8250     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8251
8252   if (Args.hasArg(options::OPT_pie))
8253     CmdArgs.push_back("-pie");
8254   if (Args.hasArg(options::OPT_rdynamic))
8255     CmdArgs.push_back("-export-dynamic");
8256   if (Args.hasArg(options::OPT_s))
8257     CmdArgs.push_back("--strip-all");
8258
8259   CmdArgs.push_back("-m");
8260   switch (TC.getArch()) {
8261   default: llvm_unreachable("unsupported architecture");
8262   case llvm::Triple::arm:
8263   case llvm::Triple::thumb:
8264     // FIXME: this is incorrect for WinCE
8265     CmdArgs.push_back("thumb2pe");
8266     break;
8267   case llvm::Triple::x86:
8268     CmdArgs.push_back("i386pe");
8269     EntryPoint.append("_");
8270     break;
8271   case llvm::Triple::x86_64:
8272     CmdArgs.push_back("i386pep");
8273     break;
8274   }
8275
8276   if (Args.hasArg(options::OPT_shared)) {
8277     switch (T.getArch()) {
8278     default: llvm_unreachable("unsupported architecture");
8279     case llvm::Triple::arm:
8280     case llvm::Triple::thumb:
8281     case llvm::Triple::x86_64:
8282       EntryPoint.append("_DllMainCRTStartup");
8283       break;
8284     case llvm::Triple::x86:
8285       EntryPoint.append("_DllMainCRTStartup@12");
8286       break;
8287     }
8288
8289     CmdArgs.push_back("-shared");
8290     CmdArgs.push_back("-Bdynamic");
8291
8292     CmdArgs.push_back("--enable-auto-image-base");
8293
8294     CmdArgs.push_back("--entry");
8295     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
8296   } else {
8297     EntryPoint.append("mainCRTStartup");
8298
8299     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
8300                                                        : "-Bdynamic");
8301
8302     if (!Args.hasArg(options::OPT_nostdlib) &&
8303         !Args.hasArg(options::OPT_nostartfiles)) {
8304       CmdArgs.push_back("--entry");
8305       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
8306     }
8307
8308     // FIXME: handle subsystem
8309   }
8310
8311   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
8312   CmdArgs.push_back("--allow-multiple-definition");
8313
8314   CmdArgs.push_back("-o");
8315   CmdArgs.push_back(Output.getFilename());
8316
8317   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
8318     SmallString<261> ImpLib(Output.getFilename());
8319     llvm::sys::path::replace_extension(ImpLib, ".lib");
8320
8321     CmdArgs.push_back("--out-implib");
8322     CmdArgs.push_back(Args.MakeArgString(ImpLib));
8323   }
8324
8325   if (!Args.hasArg(options::OPT_nostdlib) &&
8326       !Args.hasArg(options::OPT_nostartfiles)) {
8327     const std::string CRTPath(D.SysRoot + "/usr/lib/");
8328     const char *CRTBegin;
8329
8330     CRTBegin =
8331         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
8332     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
8333   }
8334
8335   Args.AddAllArgs(CmdArgs, options::OPT_L);
8336
8337   const auto &Paths = TC.getFilePaths();
8338   for (const auto &Path : Paths)
8339     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8340
8341   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
8342
8343   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8344       !Args.hasArg(options::OPT_nodefaultlibs)) {
8345     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
8346                      !Args.hasArg(options::OPT_static);
8347     if (StaticCXX)
8348       CmdArgs.push_back("-Bstatic");
8349     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
8350     if (StaticCXX)
8351       CmdArgs.push_back("-Bdynamic");
8352   }
8353
8354   if (!Args.hasArg(options::OPT_nostdlib)) {
8355     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8356       // TODO handle /MT[d] /MD[d]
8357       CmdArgs.push_back("-lmsvcrt");
8358       AddRunTimeLibs(TC, D, CmdArgs, Args);
8359     }
8360   }
8361
8362   const std::string Linker = TC.GetProgramPath("ld");
8363   Exec = Args.MakeArgString(Linker);
8364
8365   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8366 }