]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Update mandoc to 1.13.4 release
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
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/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
45
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56                                       std::vector<const char *> &Features,
57                                       OptSpecifier Group) {
58   for (const Arg *A : Args.filtered(Group)) {
59     StringRef Name = A->getOption().getName();
60     A->claim();
61
62     // Skip over "-m".
63     assert(Name.startswith("m") && "Invalid feature name.");
64     Name = Name.substr(1);
65
66     bool IsNegative = Name.startswith("no-");
67     if (IsNegative)
68       Name = Name.substr(3);
69     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
70   }
71 }
72
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74                                          const llvm::Triple &Triple) {
75   if (Triple.getArch() == llvm::Triple::sparcv9) {
76     return llvm::StringSwitch<const char *>(Name)
77           .Case("niagara", "-Av9b")
78           .Case("niagara2", "-Av9b")
79           .Case("niagara3", "-Av9d")
80           .Case("niagara4", "-Av9d")
81           .Default("-Av9");
82   } else {
83     return llvm::StringSwitch<const char *>(Name)
84           .Case("v8", "-Av8")
85           .Case("supersparc", "-Av8")
86           .Case("sparclite", "-Asparclite")
87           .Case("f934", "-Asparclite")
88           .Case("hypersparc", "-Av8")
89           .Case("sparclite86x", "-Asparclite")
90           .Case("sparclet", "-Asparclet")
91           .Case("tsc701", "-Asparclet")
92           .Case("v9", "-Av8plus")
93           .Case("ultrasparc", "-Av8plus")
94           .Case("ultrasparc3", "-Av8plus")
95           .Case("niagara", "-Av8plusb")
96           .Case("niagara2", "-Av8plusb")
97           .Case("niagara3", "-Av8plusd")
98           .Case("niagara4", "-Av8plusd")
99           .Default("-Av8");
100   }
101 }
102
103 /// CheckPreprocessingOptions - Perform some validation of preprocessing
104 /// arguments that is shared with gcc.
105 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
106   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
107     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
108         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
109       D.Diag(diag::err_drv_argument_only_allowed_with)
110           << A->getBaseArg().getAsString(Args)
111           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
112     }
113   }
114 }
115
116 /// CheckCodeGenerationOptions - Perform some validation of code generation
117 /// arguments that is shared with gcc.
118 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
119   // In gcc, only ARM checks this, but it seems reasonable to check universally.
120   if (Args.hasArg(options::OPT_static))
121     if (const Arg *A =
122             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
123       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
124                                                       << "-static";
125 }
126
127 // Add backslashes to escape spaces and other backslashes.
128 // This is used for the space-separated argument list specified with
129 // the -dwarf-debug-flags option.
130 static void EscapeSpacesAndBackslashes(const char *Arg,
131                                        SmallVectorImpl<char> &Res) {
132   for (; *Arg; ++Arg) {
133     switch (*Arg) {
134     default:
135       break;
136     case ' ':
137     case '\\':
138       Res.push_back('\\');
139       break;
140     }
141     Res.push_back(*Arg);
142   }
143 }
144
145 // Quote target names for inclusion in GNU Make dependency files.
146 // Only the characters '$', '#', ' ', '\t' are quoted.
147 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
148   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
149     switch (Target[i]) {
150     case ' ':
151     case '\t':
152       // Escape the preceding backslashes
153       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
154         Res.push_back('\\');
155
156       // Escape the space/tab
157       Res.push_back('\\');
158       break;
159     case '$':
160       Res.push_back('$');
161       break;
162     case '#':
163       Res.push_back('\\');
164       break;
165     default:
166       break;
167     }
168
169     Res.push_back(Target[i]);
170   }
171 }
172
173 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
174                              const char *ArgName, const char *EnvVar) {
175   const char *DirList = ::getenv(EnvVar);
176   bool CombinedArg = false;
177
178   if (!DirList)
179     return; // Nothing to do.
180
181   StringRef Name(ArgName);
182   if (Name.equals("-I") || Name.equals("-L"))
183     CombinedArg = true;
184
185   StringRef Dirs(DirList);
186   if (Dirs.empty()) // Empty string should not add '.'.
187     return;
188
189   StringRef::size_type Delim;
190   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
191     if (Delim == 0) { // Leading colon.
192       if (CombinedArg) {
193         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
194       } else {
195         CmdArgs.push_back(ArgName);
196         CmdArgs.push_back(".");
197       }
198     } else {
199       if (CombinedArg) {
200         CmdArgs.push_back(
201             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
202       } else {
203         CmdArgs.push_back(ArgName);
204         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
205       }
206     }
207     Dirs = Dirs.substr(Delim + 1);
208   }
209
210   if (Dirs.empty()) { // Trailing colon.
211     if (CombinedArg) {
212       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
213     } else {
214       CmdArgs.push_back(ArgName);
215       CmdArgs.push_back(".");
216     }
217   } else { // Add the last path.
218     if (CombinedArg) {
219       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
220     } else {
221       CmdArgs.push_back(ArgName);
222       CmdArgs.push_back(Args.MakeArgString(Dirs));
223     }
224   }
225 }
226
227 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
228                             const ArgList &Args, ArgStringList &CmdArgs) {
229   const Driver &D = TC.getDriver();
230
231   // Add extra linker input arguments which are not treated as inputs
232   // (constructed via -Xarch_).
233   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
234
235   for (const auto &II : Inputs) {
236     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
237       // Don't try to pass LLVM inputs unless we have native support.
238       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
239
240     // Add filenames immediately.
241     if (II.isFilename()) {
242       CmdArgs.push_back(II.getFilename());
243       continue;
244     }
245
246     // Otherwise, this is a linker input argument.
247     const Arg &A = II.getInputArg();
248
249     // Handle reserved library options.
250     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
251       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
252     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
253       TC.AddCCKextLibArgs(Args, CmdArgs);
254     else if (A.getOption().matches(options::OPT_z)) {
255       // Pass -z prefix for gcc linker compatibility.
256       A.claim();
257       A.render(Args, CmdArgs);
258     } else {
259       A.renderAsInput(Args, CmdArgs);
260     }
261   }
262
263   // LIBRARY_PATH - included following the user specified library paths.
264   //                and only supported on native toolchains.
265   if (!TC.isCrossCompiling())
266     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
267 }
268
269 /// \brief Determine whether Objective-C automated reference counting is
270 /// enabled.
271 static bool isObjCAutoRefCount(const ArgList &Args) {
272   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
273 }
274
275 /// \brief Determine whether we are linking the ObjC runtime.
276 static bool isObjCRuntimeLinked(const ArgList &Args) {
277   if (isObjCAutoRefCount(Args)) {
278     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
279     return true;
280   }
281   return Args.hasArg(options::OPT_fobjc_link_runtime);
282 }
283
284 static bool forwardToGCC(const Option &O) {
285   // Don't forward inputs from the original command line.  They are added from
286   // InputInfoList.
287   return O.getKind() != Option::InputClass &&
288          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
289 }
290
291 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
292                                     const Driver &D, const ArgList &Args,
293                                     ArgStringList &CmdArgs,
294                                     const InputInfo &Output,
295                                     const InputInfoList &Inputs,
296                                     const ToolChain *AuxToolChain) const {
297   Arg *A;
298
299   CheckPreprocessingOptions(D, Args);
300
301   Args.AddLastArg(CmdArgs, options::OPT_C);
302   Args.AddLastArg(CmdArgs, options::OPT_CC);
303
304   // Handle dependency file generation.
305   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
306       (A = Args.getLastArg(options::OPT_MD)) ||
307       (A = Args.getLastArg(options::OPT_MMD))) {
308     // Determine the output location.
309     const char *DepFile;
310     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
311       DepFile = MF->getValue();
312       C.addFailureResultFile(DepFile, &JA);
313     } else if (Output.getType() == types::TY_Dependencies) {
314       DepFile = Output.getFilename();
315     } else if (A->getOption().matches(options::OPT_M) ||
316                A->getOption().matches(options::OPT_MM)) {
317       DepFile = "-";
318     } else {
319       DepFile = getDependencyFileName(Args, Inputs);
320       C.addFailureResultFile(DepFile, &JA);
321     }
322     CmdArgs.push_back("-dependency-file");
323     CmdArgs.push_back(DepFile);
324
325     // Add a default target if one wasn't specified.
326     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
327       const char *DepTarget;
328
329       // If user provided -o, that is the dependency target, except
330       // when we are only generating a dependency file.
331       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
332       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
333         DepTarget = OutputOpt->getValue();
334       } else {
335         // Otherwise derive from the base input.
336         //
337         // FIXME: This should use the computed output file location.
338         SmallString<128> P(Inputs[0].getBaseInput());
339         llvm::sys::path::replace_extension(P, "o");
340         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
341       }
342
343       CmdArgs.push_back("-MT");
344       SmallString<128> Quoted;
345       QuoteTarget(DepTarget, Quoted);
346       CmdArgs.push_back(Args.MakeArgString(Quoted));
347     }
348
349     if (A->getOption().matches(options::OPT_M) ||
350         A->getOption().matches(options::OPT_MD))
351       CmdArgs.push_back("-sys-header-deps");
352     if ((isa<PrecompileJobAction>(JA) &&
353          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
354         Args.hasArg(options::OPT_fmodule_file_deps))
355       CmdArgs.push_back("-module-file-deps");
356   }
357
358   if (Args.hasArg(options::OPT_MG)) {
359     if (!A || A->getOption().matches(options::OPT_MD) ||
360         A->getOption().matches(options::OPT_MMD))
361       D.Diag(diag::err_drv_mg_requires_m_or_mm);
362     CmdArgs.push_back("-MG");
363   }
364
365   Args.AddLastArg(CmdArgs, options::OPT_MP);
366   Args.AddLastArg(CmdArgs, options::OPT_MV);
367
368   // Convert all -MQ <target> args to -MT <quoted target>
369   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
370     A->claim();
371
372     if (A->getOption().matches(options::OPT_MQ)) {
373       CmdArgs.push_back("-MT");
374       SmallString<128> Quoted;
375       QuoteTarget(A->getValue(), Quoted);
376       CmdArgs.push_back(Args.MakeArgString(Quoted));
377
378       // -MT flag - no change
379     } else {
380       A->render(Args, CmdArgs);
381     }
382   }
383
384   // Add -i* options, and automatically translate to
385   // -include-pch/-include-pth for transparent PCH support. It's
386   // wonky, but we include looking for .gch so we can support seamless
387   // replacement into a build system already set up to be generating
388   // .gch files.
389   bool RenderedImplicitInclude = false;
390   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
391     if (A->getOption().matches(options::OPT_include)) {
392       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
393       RenderedImplicitInclude = true;
394
395       // Use PCH if the user requested it.
396       bool UsePCH = D.CCCUsePCH;
397
398       bool FoundPTH = false;
399       bool FoundPCH = false;
400       SmallString<128> P(A->getValue());
401       // We want the files to have a name like foo.h.pch. Add a dummy extension
402       // so that replace_extension does the right thing.
403       P += ".dummy";
404       if (UsePCH) {
405         llvm::sys::path::replace_extension(P, "pch");
406         if (llvm::sys::fs::exists(P))
407           FoundPCH = true;
408       }
409
410       if (!FoundPCH) {
411         llvm::sys::path::replace_extension(P, "pth");
412         if (llvm::sys::fs::exists(P))
413           FoundPTH = true;
414       }
415
416       if (!FoundPCH && !FoundPTH) {
417         llvm::sys::path::replace_extension(P, "gch");
418         if (llvm::sys::fs::exists(P)) {
419           FoundPCH = UsePCH;
420           FoundPTH = !UsePCH;
421         }
422       }
423
424       if (FoundPCH || FoundPTH) {
425         if (IsFirstImplicitInclude) {
426           A->claim();
427           if (UsePCH)
428             CmdArgs.push_back("-include-pch");
429           else
430             CmdArgs.push_back("-include-pth");
431           CmdArgs.push_back(Args.MakeArgString(P));
432           continue;
433         } else {
434           // Ignore the PCH if not first on command line and emit warning.
435           D.Diag(diag::warn_drv_pch_not_first_include) << P
436                                                        << A->getAsString(Args);
437         }
438       }
439     }
440
441     // Not translated, render as usual.
442     A->claim();
443     A->render(Args, CmdArgs);
444   }
445
446   Args.AddAllArgs(CmdArgs,
447                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
448                    options::OPT_F, options::OPT_index_header_map});
449
450   // Add -Wp, and -Xpreprocessor if using the preprocessor.
451
452   // FIXME: There is a very unfortunate problem here, some troubled
453   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
454   // really support that we would have to parse and then translate
455   // those options. :(
456   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
457                        options::OPT_Xpreprocessor);
458
459   // -I- is a deprecated GCC feature, reject it.
460   if (Arg *A = Args.getLastArg(options::OPT_I_))
461     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
462
463   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
464   // -isysroot to the CC1 invocation.
465   StringRef sysroot = C.getSysRoot();
466   if (sysroot != "") {
467     if (!Args.hasArg(options::OPT_isysroot)) {
468       CmdArgs.push_back("-isysroot");
469       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
470     }
471   }
472
473   // Parse additional include paths from environment variables.
474   // FIXME: We should probably sink the logic for handling these from the
475   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
476   // CPATH - included following the user specified includes (but prior to
477   // builtin and standard includes).
478   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
479   // C_INCLUDE_PATH - system includes enabled when compiling C.
480   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
481   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
482   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
483   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
484   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
485   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
486   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
487
488   // Optional AuxToolChain indicates that we need to include headers
489   // for more than one target. If that's the case, add include paths
490   // from AuxToolChain right after include paths of the same kind for
491   // the current target.
492
493   // Add C++ include arguments, if needed.
494   if (types::isCXX(Inputs[0].getType())) {
495     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
496     if (AuxToolChain)
497       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
498   }
499
500   // Add system include arguments.
501   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
502   if (AuxToolChain)
503       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
504
505   // Add CUDA include arguments, if needed.
506   if (types::isCuda(Inputs[0].getType()))
507     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
508 }
509
510 // FIXME: Move to target hook.
511 static bool isSignedCharDefault(const llvm::Triple &Triple) {
512   switch (Triple.getArch()) {
513   default:
514     return true;
515
516   case llvm::Triple::aarch64:
517   case llvm::Triple::aarch64_be:
518   case llvm::Triple::arm:
519   case llvm::Triple::armeb:
520   case llvm::Triple::thumb:
521   case llvm::Triple::thumbeb:
522     if (Triple.isOSDarwin() || Triple.isOSWindows())
523       return true;
524     return false;
525
526   case llvm::Triple::ppc:
527   case llvm::Triple::ppc64:
528     if (Triple.isOSDarwin())
529       return true;
530     return false;
531
532   case llvm::Triple::hexagon:
533   case llvm::Triple::ppc64le:
534   case llvm::Triple::systemz:
535   case llvm::Triple::xcore:
536     return false;
537   }
538 }
539
540 static bool isNoCommonDefault(const llvm::Triple &Triple) {
541   switch (Triple.getArch()) {
542   default:
543     return false;
544
545   case llvm::Triple::xcore:
546   case llvm::Triple::wasm32:
547   case llvm::Triple::wasm64:
548     return true;
549   }
550 }
551
552 // ARM tools start.
553
554 // Get SubArch (vN).
555 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
556   llvm::StringRef Arch = Triple.getArchName();
557   return llvm::ARM::parseArchVersion(Arch);
558 }
559
560 // True if M-profile.
561 static bool isARMMProfile(const llvm::Triple &Triple) {
562   llvm::StringRef Arch = Triple.getArchName();
563   unsigned Profile = llvm::ARM::parseArchProfile(Arch);
564   return Profile == llvm::ARM::PK_M;
565 }
566
567 // Get Arch/CPU from args.
568 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
569                                   llvm::StringRef &CPU, bool FromAs = false) {
570   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
571     CPU = A->getValue();
572   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
573     Arch = A->getValue();
574   if (!FromAs)
575     return;
576
577   for (const Arg *A :
578        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
579     StringRef Value = A->getValue();
580     if (Value.startswith("-mcpu="))
581       CPU = Value.substr(6);
582     if (Value.startswith("-march="))
583       Arch = Value.substr(7);
584   }
585 }
586
587 // Handle -mhwdiv=.
588 // FIXME: Use ARMTargetParser.
589 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
590                                 const ArgList &Args, StringRef HWDiv,
591                                 std::vector<const char *> &Features) {
592   unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
593   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
594     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
595 }
596
597 // Handle -mfpu=.
598 static void getARMFPUFeatures(const Driver &D, const Arg *A,
599                               const ArgList &Args, StringRef FPU,
600                               std::vector<const char *> &Features) {
601   unsigned FPUID = llvm::ARM::parseFPU(FPU);
602   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
603     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
604 }
605
606 // Decode ARM features from string like +[no]featureA+[no]featureB+...
607 static bool DecodeARMFeatures(const Driver &D, StringRef text,
608                               std::vector<const char *> &Features) {
609   SmallVector<StringRef, 8> Split;
610   text.split(Split, StringRef("+"), -1, false);
611
612   for (StringRef Feature : Split) {
613     const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
614     if (FeatureName)
615       Features.push_back(FeatureName);
616     else
617       return false;
618   }
619   return true;
620 }
621
622 // Check if -march is valid by checking if it can be canonicalised and parsed.
623 // getARMArch is used here instead of just checking the -march value in order
624 // to handle -march=native correctly.
625 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
626                              llvm::StringRef ArchName,
627                              std::vector<const char *> &Features,
628                              const llvm::Triple &Triple) {
629   std::pair<StringRef, StringRef> Split = ArchName.split("+");
630
631   std::string MArch = arm::getARMArch(ArchName, Triple);
632   if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
633       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
634     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
635 }
636
637 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
638 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
639                             llvm::StringRef CPUName, llvm::StringRef ArchName,
640                             std::vector<const char *> &Features,
641                             const llvm::Triple &Triple) {
642   std::pair<StringRef, StringRef> Split = CPUName.split("+");
643
644   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
645   if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
646       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
647     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
648 }
649
650 static bool useAAPCSForMachO(const llvm::Triple &T) {
651   // The backend is hardwired to assume AAPCS for M-class processors, ensure
652   // the frontend matches that.
653   return T.getEnvironment() == llvm::Triple::EABI ||
654          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
655 }
656
657 // Select the float ABI as determined by -msoft-float, -mhard-float, and
658 // -mfloat-abi=.
659 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
660   const Driver &D = TC.getDriver();
661   const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
662   auto SubArch = getARMSubArchVersionNumber(Triple);
663   arm::FloatABI ABI = FloatABI::Invalid;
664   if (Arg *A =
665           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
666                           options::OPT_mfloat_abi_EQ)) {
667     if (A->getOption().matches(options::OPT_msoft_float)) {
668       ABI = FloatABI::Soft;
669     } else if (A->getOption().matches(options::OPT_mhard_float)) {
670       ABI = FloatABI::Hard;
671     } else {
672       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
673                 .Case("soft", FloatABI::Soft)
674                 .Case("softfp", FloatABI::SoftFP)
675                 .Case("hard", FloatABI::Hard)
676                 .Default(FloatABI::Invalid);
677       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
678         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
679         ABI = FloatABI::Soft;
680       }
681     }
682
683     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
684     // "apcs-gnu".
685     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
686         ABI == FloatABI::Hard) {
687       D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
688                                                        << Triple.getArchName();
689     }
690   }
691
692   // If unspecified, choose the default based on the platform.
693   if (ABI == FloatABI::Invalid) {
694     switch (Triple.getOS()) {
695     case llvm::Triple::Darwin:
696     case llvm::Triple::MacOSX:
697     case llvm::Triple::IOS:
698     case llvm::Triple::TvOS: {
699       // Darwin defaults to "softfp" for v6 and v7.
700       ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
701       break;
702     }
703     case llvm::Triple::WatchOS:
704       ABI = FloatABI::Hard;
705       break;
706
707     // FIXME: this is invalid for WindowsCE
708     case llvm::Triple::Win32:
709       ABI = FloatABI::Hard;
710       break;
711
712     case llvm::Triple::FreeBSD:
713       switch (Triple.getEnvironment()) {
714       case llvm::Triple::GNUEABIHF:
715         ABI = FloatABI::Hard;
716         break;
717       default:
718         // FreeBSD defaults to soft float
719         ABI = FloatABI::Soft;
720         break;
721       }
722       break;
723
724     default:
725       switch (Triple.getEnvironment()) {
726       case llvm::Triple::GNUEABIHF:
727       case llvm::Triple::EABIHF:
728         ABI = FloatABI::Hard;
729         break;
730       case llvm::Triple::GNUEABI:
731       case llvm::Triple::EABI:
732         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
733         ABI = FloatABI::SoftFP;
734         break;
735       case llvm::Triple::Android:
736         ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
737         break;
738       default:
739         // Assume "soft", but warn the user we are guessing.
740         ABI = FloatABI::Soft;
741         if (Triple.getOS() != llvm::Triple::UnknownOS ||
742             !Triple.isOSBinFormatMachO())
743           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
744         break;
745       }
746     }
747   }
748
749   assert(ABI != FloatABI::Invalid && "must select an ABI");
750   return ABI;
751 }
752
753 static void getARMTargetFeatures(const ToolChain &TC,
754                                  const llvm::Triple &Triple,
755                                  const ArgList &Args,
756                                  std::vector<const char *> &Features,
757                                  bool ForAS) {
758   const Driver &D = TC.getDriver();
759
760   bool KernelOrKext =
761       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
762   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
763   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
764   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
765
766   if (!ForAS) {
767     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
768     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
769     // stripped out by the ARM target. We should probably pass this a new
770     // -target-option, which is handled by the -cc1/-cc1as invocation.
771     //
772     // FIXME2:  For consistency, it would be ideal if we set up the target
773     // machine state the same when using the frontend or the assembler. We don't
774     // currently do that for the assembler, we pass the options directly to the
775     // backend and never even instantiate the frontend TargetInfo. If we did,
776     // and used its handleTargetFeatures hook, then we could ensure the
777     // assembler and the frontend behave the same.
778
779     // Use software floating point operations?
780     if (ABI == arm::FloatABI::Soft)
781       Features.push_back("+soft-float");
782
783     // Use software floating point argument passing?
784     if (ABI != arm::FloatABI::Hard)
785       Features.push_back("+soft-float-abi");
786   } else {
787     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
788     // to the assembler correctly.
789     for (const Arg *A :
790          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
791       StringRef Value = A->getValue();
792       if (Value.startswith("-mfpu=")) {
793         WaFPU = A;
794       } else if (Value.startswith("-mcpu=")) {
795         WaCPU = A;
796       } else if (Value.startswith("-mhwdiv=")) {
797         WaHDiv = A;
798       } else if (Value.startswith("-march=")) {
799         WaArch = A;
800       }
801     }
802   }
803
804   // Check -march. ClangAs gives preference to -Wa,-march=.
805   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
806   StringRef ArchName;
807   if (WaArch) {
808     if (ArchArg)
809       D.Diag(clang::diag::warn_drv_unused_argument)
810           << ArchArg->getAsString(Args);
811     ArchName = StringRef(WaArch->getValue()).substr(7);
812     checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
813     // FIXME: Set Arch.
814     D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
815   } else if (ArchArg) {
816     ArchName = ArchArg->getValue();
817     checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
818   }
819
820   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
821   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
822   StringRef CPUName;
823   if (WaCPU) {
824     if (CPUArg)
825       D.Diag(clang::diag::warn_drv_unused_argument)
826           << CPUArg->getAsString(Args);
827     CPUName = StringRef(WaCPU->getValue()).substr(6);
828     checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
829   } else if (CPUArg) {
830     CPUName = CPUArg->getValue();
831     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
832   }
833
834   // Add CPU features for generic CPUs
835   if (CPUName == "native") {
836     llvm::StringMap<bool> HostFeatures;
837     if (llvm::sys::getHostCPUFeatures(HostFeatures))
838       for (auto &F : HostFeatures)
839         Features.push_back(
840             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
841   }
842
843   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
844   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
845   if (WaFPU) {
846     if (FPUArg)
847       D.Diag(clang::diag::warn_drv_unused_argument)
848           << FPUArg->getAsString(Args);
849     getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
850                       Features);
851   } else if (FPUArg) {
852     getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
853   }
854
855   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
856   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
857   if (WaHDiv) {
858     if (HDivArg)
859       D.Diag(clang::diag::warn_drv_unused_argument)
860           << HDivArg->getAsString(Args);
861     getARMHWDivFeatures(D, WaHDiv, Args,
862                         StringRef(WaHDiv->getValue()).substr(8), Features);
863   } else if (HDivArg)
864     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
865
866   // Setting -msoft-float effectively disables NEON because of the GCC
867   // implementation, although the same isn't true of VFP or VFP3.
868   if (ABI == arm::FloatABI::Soft) {
869     Features.push_back("-neon");
870     // Also need to explicitly disable features which imply NEON.
871     Features.push_back("-crypto");
872   }
873
874   // En/disable crc code generation.
875   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
876     if (A->getOption().matches(options::OPT_mcrc))
877       Features.push_back("+crc");
878     else
879       Features.push_back("-crc");
880   }
881
882   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
883     Features.insert(Features.begin(), "+v8.1a");
884   }
885
886   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
887   // neither options are specified, see if we are compiling for kernel/kext and
888   // decide whether to pass "+long-calls" based on the OS and its version.
889   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
890                                options::OPT_mno_long_calls)) {
891     if (A->getOption().matches(options::OPT_mlong_calls))
892       Features.push_back("+long-calls");
893   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
894              !Triple.isWatchOS()) {
895       Features.push_back("+long-calls");
896   }
897
898   // Kernel code has more strict alignment requirements.
899   if (KernelOrKext)
900     Features.push_back("+strict-align");
901   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
902                                     options::OPT_munaligned_access)) {
903     if (A->getOption().matches(options::OPT_munaligned_access)) {
904       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
905       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
906         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
907     } else
908       Features.push_back("+strict-align");
909   } else {
910     // Assume pre-ARMv6 doesn't support unaligned accesses.
911     //
912     // ARMv6 may or may not support unaligned accesses depending on the
913     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
914     // Darwin and NetBSD targets support unaligned accesses, and others don't.
915     //
916     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
917     // which raises an alignment fault on unaligned accesses. Linux
918     // defaults this bit to 0 and handles it as a system-wide (not
919     // per-process) setting. It is therefore safe to assume that ARMv7+
920     // Linux targets support unaligned accesses. The same goes for NaCl.
921     //
922     // The above behavior is consistent with GCC.
923     int VersionNum = getARMSubArchVersionNumber(Triple);
924     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
925       if (VersionNum < 6 ||
926           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
927         Features.push_back("+strict-align");
928     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
929       if (VersionNum < 7)
930         Features.push_back("+strict-align");
931     } else
932       Features.push_back("+strict-align");
933   }
934
935   // llvm does not support reserving registers in general. There is support
936   // for reserving r9 on ARM though (defined as a platform-specific register
937   // in ARM EABI).
938   if (Args.hasArg(options::OPT_ffixed_r9))
939     Features.push_back("+reserve-r9");
940
941   // The kext linker doesn't know how to deal with movw/movt.
942   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
943     Features.push_back("+no-movt");
944 }
945
946 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
947                              ArgStringList &CmdArgs, bool KernelOrKext) const {
948   // Select the ABI to use.
949   // FIXME: Support -meabi.
950   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
951   const char *ABIName = nullptr;
952   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
953     ABIName = A->getValue();
954   } else if (Triple.isOSBinFormatMachO()) {
955     if (useAAPCSForMachO(Triple)) {
956       ABIName = "aapcs";
957     } else if (Triple.isWatchOS()) {
958       ABIName = "aapcs16";
959     } else {
960       ABIName = "apcs-gnu";
961     }
962   } else if (Triple.isOSWindows()) {
963     // FIXME: this is invalid for WindowsCE
964     ABIName = "aapcs";
965   } else {
966     // Select the default based on the platform.
967     switch (Triple.getEnvironment()) {
968     case llvm::Triple::Android:
969     case llvm::Triple::GNUEABI:
970     case llvm::Triple::GNUEABIHF:
971       ABIName = "aapcs-linux";
972       break;
973     case llvm::Triple::EABIHF:
974     case llvm::Triple::EABI:
975       ABIName = "aapcs";
976       break;
977     default:
978       if (Triple.getOS() == llvm::Triple::NetBSD)
979         ABIName = "apcs-gnu";
980       else
981         ABIName = "aapcs";
982       break;
983     }
984   }
985   CmdArgs.push_back("-target-abi");
986   CmdArgs.push_back(ABIName);
987
988   // Determine floating point ABI from the options & target defaults.
989   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
990   if (ABI == arm::FloatABI::Soft) {
991     // Floating point operations and argument passing are soft.
992     // FIXME: This changes CPP defines, we need -target-soft-float.
993     CmdArgs.push_back("-msoft-float");
994     CmdArgs.push_back("-mfloat-abi");
995     CmdArgs.push_back("soft");
996   } else if (ABI == arm::FloatABI::SoftFP) {
997     // Floating point operations are hard, but argument passing is soft.
998     CmdArgs.push_back("-mfloat-abi");
999     CmdArgs.push_back("soft");
1000   } else {
1001     // Floating point operations and argument passing are hard.
1002     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1003     CmdArgs.push_back("-mfloat-abi");
1004     CmdArgs.push_back("hard");
1005   }
1006
1007   // Forward the -mglobal-merge option for explicit control over the pass.
1008   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1009                                options::OPT_mno_global_merge)) {
1010     CmdArgs.push_back("-backend-option");
1011     if (A->getOption().matches(options::OPT_mno_global_merge))
1012       CmdArgs.push_back("-arm-global-merge=false");
1013     else
1014       CmdArgs.push_back("-arm-global-merge=true");
1015   }
1016
1017   if (!Args.hasFlag(options::OPT_mimplicit_float,
1018                     options::OPT_mno_implicit_float, true))
1019     CmdArgs.push_back("-no-implicit-float");
1020 }
1021 // ARM tools end.
1022
1023 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1024 /// targeting.
1025 static std::string getAArch64TargetCPU(const ArgList &Args) {
1026   Arg *A;
1027   std::string CPU;
1028   // If we have -mtune or -mcpu, use that.
1029   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1030     CPU = StringRef(A->getValue()).lower();
1031   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1032     StringRef Mcpu = A->getValue();
1033     CPU = Mcpu.split("+").first.lower();
1034   }
1035
1036   // Handle CPU name is 'native'.
1037   if (CPU == "native")
1038     return llvm::sys::getHostCPUName();
1039   else if (CPU.size())
1040     return CPU;
1041
1042   // Make sure we pick "cyclone" if -arch is used.
1043   // FIXME: Should this be picked by checking the target triple instead?
1044   if (Args.getLastArg(options::OPT_arch))
1045     return "cyclone";
1046
1047   return "generic";
1048 }
1049
1050 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1051                                  ArgStringList &CmdArgs) const {
1052   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1053   llvm::Triple Triple(TripleStr);
1054
1055   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1056       Args.hasArg(options::OPT_mkernel) ||
1057       Args.hasArg(options::OPT_fapple_kext))
1058     CmdArgs.push_back("-disable-red-zone");
1059
1060   if (!Args.hasFlag(options::OPT_mimplicit_float,
1061                     options::OPT_mno_implicit_float, true))
1062     CmdArgs.push_back("-no-implicit-float");
1063
1064   const char *ABIName = nullptr;
1065   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1066     ABIName = A->getValue();
1067   else if (Triple.isOSDarwin())
1068     ABIName = "darwinpcs";
1069   else
1070     ABIName = "aapcs";
1071
1072   CmdArgs.push_back("-target-abi");
1073   CmdArgs.push_back(ABIName);
1074
1075   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1076                                options::OPT_mno_fix_cortex_a53_835769)) {
1077     CmdArgs.push_back("-backend-option");
1078     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1079       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1080     else
1081       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1082   } else if (Triple.isAndroid()) {
1083     // Enabled A53 errata (835769) workaround by default on android
1084     CmdArgs.push_back("-backend-option");
1085     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1086   }
1087
1088   // Forward the -mglobal-merge option for explicit control over the pass.
1089   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1090                                options::OPT_mno_global_merge)) {
1091     CmdArgs.push_back("-backend-option");
1092     if (A->getOption().matches(options::OPT_mno_global_merge))
1093       CmdArgs.push_back("-aarch64-global-merge=false");
1094     else
1095       CmdArgs.push_back("-aarch64-global-merge=true");
1096   }
1097 }
1098
1099 // Get CPU and ABI names. They are not independent
1100 // so we have to calculate them together.
1101 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1102                             StringRef &CPUName, StringRef &ABIName) {
1103   const char *DefMips32CPU = "mips32r2";
1104   const char *DefMips64CPU = "mips64r2";
1105
1106   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1107   // default for mips64(el)?-img-linux-gnu.
1108   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1109       Triple.getEnvironment() == llvm::Triple::GNU) {
1110     DefMips32CPU = "mips32r6";
1111     DefMips64CPU = "mips64r6";
1112   }
1113
1114   // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1115   if (Triple.isAndroid())
1116     DefMips64CPU = "mips64r6";
1117
1118   // MIPS3 is the default for mips64*-unknown-openbsd.
1119   if (Triple.getOS() == llvm::Triple::OpenBSD)
1120     DefMips64CPU = "mips3";
1121
1122   if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1123     CPUName = A->getValue();
1124
1125   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1126     ABIName = A->getValue();
1127     // Convert a GNU style Mips ABI name to the name
1128     // accepted by LLVM Mips backend.
1129     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1130                   .Case("32", "o32")
1131                   .Case("64", "n64")
1132                   .Default(ABIName);
1133   }
1134
1135   // Setup default CPU and ABI names.
1136   if (CPUName.empty() && ABIName.empty()) {
1137     switch (Triple.getArch()) {
1138     default:
1139       llvm_unreachable("Unexpected triple arch name");
1140     case llvm::Triple::mips:
1141     case llvm::Triple::mipsel:
1142       CPUName = DefMips32CPU;
1143       break;
1144     case llvm::Triple::mips64:
1145     case llvm::Triple::mips64el:
1146       CPUName = DefMips64CPU;
1147       break;
1148     }
1149   }
1150
1151   if (ABIName.empty()) {
1152     // Deduce ABI name from the target triple.
1153     if (Triple.getArch() == llvm::Triple::mips ||
1154         Triple.getArch() == llvm::Triple::mipsel)
1155       ABIName = "o32";
1156     else
1157       ABIName = "n64";
1158   }
1159
1160   if (CPUName.empty()) {
1161     // Deduce CPU name from ABI name.
1162     CPUName = llvm::StringSwitch<const char *>(ABIName)
1163                   .Cases("o32", "eabi", DefMips32CPU)
1164                   .Cases("n32", "n64", DefMips64CPU)
1165                   .Default("");
1166   }
1167
1168   // FIXME: Warn on inconsistent use of -march and -mabi.
1169 }
1170
1171 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1172                                       const llvm::Triple &Triple) {
1173   StringRef CPUName, ABIName;
1174   tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1175   return llvm::StringSwitch<std::string>(ABIName)
1176       .Case("o32", "")
1177       .Case("n32", "32")
1178       .Case("n64", "64");
1179 }
1180
1181 // Convert ABI name to the GNU tools acceptable variant.
1182 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1183   return llvm::StringSwitch<llvm::StringRef>(ABI)
1184       .Case("o32", "32")
1185       .Case("n64", "64")
1186       .Default(ABI);
1187 }
1188
1189 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1190 // and -mfloat-abi=.
1191 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1192   mips::FloatABI ABI = mips::FloatABI::Invalid;
1193   if (Arg *A =
1194           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1195                           options::OPT_mfloat_abi_EQ)) {
1196     if (A->getOption().matches(options::OPT_msoft_float))
1197       ABI = mips::FloatABI::Soft;
1198     else if (A->getOption().matches(options::OPT_mhard_float))
1199       ABI = mips::FloatABI::Hard;
1200     else {
1201       ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1202                 .Case("soft", mips::FloatABI::Soft)
1203                 .Case("hard", mips::FloatABI::Hard)
1204                 .Default(mips::FloatABI::Invalid);
1205       if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1206         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1207         ABI = mips::FloatABI::Hard;
1208       }
1209     }
1210   }
1211
1212   // If unspecified, choose the default based on the platform.
1213   if (ABI == mips::FloatABI::Invalid) {
1214     // Assume "hard", because it's a default value used by gcc.
1215     // When we start to recognize specific target MIPS processors,
1216     // we will be able to select the default more correctly.
1217     ABI = mips::FloatABI::Hard;
1218   }
1219
1220   assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1221   return ABI;
1222 }
1223
1224 static void AddTargetFeature(const ArgList &Args,
1225                              std::vector<const char *> &Features,
1226                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1227                              StringRef FeatureName) {
1228   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1229     if (A->getOption().matches(OnOpt))
1230       Features.push_back(Args.MakeArgString("+" + FeatureName));
1231     else
1232       Features.push_back(Args.MakeArgString("-" + FeatureName));
1233   }
1234 }
1235
1236 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1237                                   const ArgList &Args,
1238                                   std::vector<const char *> &Features) {
1239   StringRef CPUName;
1240   StringRef ABIName;
1241   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1242   ABIName = getGnuCompatibleMipsABIName(ABIName);
1243
1244   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1245                    options::OPT_mabicalls, "noabicalls");
1246
1247   mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1248   if (FloatABI == mips::FloatABI::Soft) {
1249     // FIXME: Note, this is a hack. We need to pass the selected float
1250     // mode to the MipsTargetInfoBase to define appropriate macros there.
1251     // Now it is the only method.
1252     Features.push_back("+soft-float");
1253   }
1254
1255   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1256     StringRef Val = StringRef(A->getValue());
1257     if (Val == "2008") {
1258       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1259         Features.push_back("+nan2008");
1260       else {
1261         Features.push_back("-nan2008");
1262         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1263       }
1264     } else if (Val == "legacy") {
1265       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1266         Features.push_back("-nan2008");
1267       else {
1268         Features.push_back("+nan2008");
1269         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1270       }
1271     } else
1272       D.Diag(diag::err_drv_unsupported_option_argument)
1273           << A->getOption().getName() << Val;
1274   }
1275
1276   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1277                    options::OPT_mdouble_float, "single-float");
1278   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1279                    "mips16");
1280   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1281                    options::OPT_mno_micromips, "micromips");
1282   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1283                    "dsp");
1284   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1285                    "dspr2");
1286   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1287                    "msa");
1288
1289   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1290   // pass -mfpxx
1291   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1292                                options::OPT_mfp64)) {
1293     if (A->getOption().matches(options::OPT_mfp32))
1294       Features.push_back(Args.MakeArgString("-fp64"));
1295     else if (A->getOption().matches(options::OPT_mfpxx)) {
1296       Features.push_back(Args.MakeArgString("+fpxx"));
1297       Features.push_back(Args.MakeArgString("+nooddspreg"));
1298     } else
1299       Features.push_back(Args.MakeArgString("+fp64"));
1300   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1301     Features.push_back(Args.MakeArgString("+fpxx"));
1302     Features.push_back(Args.MakeArgString("+nooddspreg"));
1303   }
1304
1305   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1306                    options::OPT_modd_spreg, "nooddspreg");
1307 }
1308
1309 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1310                               ArgStringList &CmdArgs) const {
1311   const Driver &D = getToolChain().getDriver();
1312   StringRef CPUName;
1313   StringRef ABIName;
1314   const llvm::Triple &Triple = getToolChain().getTriple();
1315   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1316
1317   CmdArgs.push_back("-target-abi");
1318   CmdArgs.push_back(ABIName.data());
1319
1320   mips::FloatABI ABI = getMipsFloatABI(D, Args);
1321   if (ABI == mips::FloatABI::Soft) {
1322     // Floating point operations and argument passing are soft.
1323     CmdArgs.push_back("-msoft-float");
1324     CmdArgs.push_back("-mfloat-abi");
1325     CmdArgs.push_back("soft");
1326   } else {
1327     // Floating point operations and argument passing are hard.
1328     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1329     CmdArgs.push_back("-mfloat-abi");
1330     CmdArgs.push_back("hard");
1331   }
1332
1333   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1334     if (A->getOption().matches(options::OPT_mxgot)) {
1335       CmdArgs.push_back("-mllvm");
1336       CmdArgs.push_back("-mxgot");
1337     }
1338   }
1339
1340   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1341                                options::OPT_mno_ldc1_sdc1)) {
1342     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1343       CmdArgs.push_back("-mllvm");
1344       CmdArgs.push_back("-mno-ldc1-sdc1");
1345     }
1346   }
1347
1348   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1349                                options::OPT_mno_check_zero_division)) {
1350     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1351       CmdArgs.push_back("-mllvm");
1352       CmdArgs.push_back("-mno-check-zero-division");
1353     }
1354   }
1355
1356   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1357     StringRef v = A->getValue();
1358     CmdArgs.push_back("-mllvm");
1359     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1360     A->claim();
1361   }
1362 }
1363
1364 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1365 static std::string getPPCTargetCPU(const ArgList &Args) {
1366   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1367     StringRef CPUName = A->getValue();
1368
1369     if (CPUName == "native") {
1370       std::string CPU = llvm::sys::getHostCPUName();
1371       if (!CPU.empty() && CPU != "generic")
1372         return CPU;
1373       else
1374         return "";
1375     }
1376
1377     return llvm::StringSwitch<const char *>(CPUName)
1378         .Case("common", "generic")
1379         .Case("440", "440")
1380         .Case("440fp", "440")
1381         .Case("450", "450")
1382         .Case("601", "601")
1383         .Case("602", "602")
1384         .Case("603", "603")
1385         .Case("603e", "603e")
1386         .Case("603ev", "603ev")
1387         .Case("604", "604")
1388         .Case("604e", "604e")
1389         .Case("620", "620")
1390         .Case("630", "pwr3")
1391         .Case("G3", "g3")
1392         .Case("7400", "7400")
1393         .Case("G4", "g4")
1394         .Case("7450", "7450")
1395         .Case("G4+", "g4+")
1396         .Case("750", "750")
1397         .Case("970", "970")
1398         .Case("G5", "g5")
1399         .Case("a2", "a2")
1400         .Case("a2q", "a2q")
1401         .Case("e500mc", "e500mc")
1402         .Case("e5500", "e5500")
1403         .Case("power3", "pwr3")
1404         .Case("power4", "pwr4")
1405         .Case("power5", "pwr5")
1406         .Case("power5x", "pwr5x")
1407         .Case("power6", "pwr6")
1408         .Case("power6x", "pwr6x")
1409         .Case("power7", "pwr7")
1410         .Case("power8", "pwr8")
1411         .Case("pwr3", "pwr3")
1412         .Case("pwr4", "pwr4")
1413         .Case("pwr5", "pwr5")
1414         .Case("pwr5x", "pwr5x")
1415         .Case("pwr6", "pwr6")
1416         .Case("pwr6x", "pwr6x")
1417         .Case("pwr7", "pwr7")
1418         .Case("pwr8", "pwr8")
1419         .Case("powerpc", "ppc")
1420         .Case("powerpc64", "ppc64")
1421         .Case("powerpc64le", "ppc64le")
1422         .Default("");
1423   }
1424
1425   return "";
1426 }
1427
1428 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1429                                  const ArgList &Args,
1430                                  std::vector<const char *> &Features) {
1431   handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1432
1433   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1434   if (FloatABI == ppc::FloatABI::Soft &&
1435       !(Triple.getArch() == llvm::Triple::ppc64 ||
1436         Triple.getArch() == llvm::Triple::ppc64le))
1437     Features.push_back("+soft-float");
1438   else if (FloatABI == ppc::FloatABI::Soft &&
1439            (Triple.getArch() == llvm::Triple::ppc64 ||
1440             Triple.getArch() == llvm::Triple::ppc64le))
1441     D.Diag(diag::err_drv_invalid_mfloat_abi)
1442         << "soft float is not supported for ppc64";
1443
1444   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1445   AddTargetFeature(Args, Features, options::OPT_faltivec,
1446                    options::OPT_fno_altivec, "altivec");
1447 }
1448
1449 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1450   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1451   if (Arg *A =
1452           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1453                           options::OPT_mfloat_abi_EQ)) {
1454     if (A->getOption().matches(options::OPT_msoft_float))
1455       ABI = ppc::FloatABI::Soft;
1456     else if (A->getOption().matches(options::OPT_mhard_float))
1457       ABI = ppc::FloatABI::Hard;
1458     else {
1459       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1460                 .Case("soft", ppc::FloatABI::Soft)
1461                 .Case("hard", ppc::FloatABI::Hard)
1462                 .Default(ppc::FloatABI::Invalid);
1463       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1464         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1465         ABI = ppc::FloatABI::Hard;
1466       }
1467     }
1468   }
1469
1470   // If unspecified, choose the default based on the platform.
1471   if (ABI == ppc::FloatABI::Invalid) {
1472     ABI = ppc::FloatABI::Hard;
1473   }
1474
1475   return ABI;
1476 }
1477
1478 void Clang::AddPPCTargetArgs(const ArgList &Args,
1479                              ArgStringList &CmdArgs) const {
1480   // Select the ABI to use.
1481   const char *ABIName = nullptr;
1482   if (getToolChain().getTriple().isOSLinux())
1483     switch (getToolChain().getArch()) {
1484     case llvm::Triple::ppc64: {
1485       // When targeting a processor that supports QPX, or if QPX is
1486       // specifically enabled, default to using the ABI that supports QPX (so
1487       // long as it is not specifically disabled).
1488       bool HasQPX = false;
1489       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1490         HasQPX = A->getValue() == StringRef("a2q");
1491       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1492       if (HasQPX) {
1493         ABIName = "elfv1-qpx";
1494         break;
1495       }
1496
1497       ABIName = "elfv1";
1498       break;
1499     }
1500     case llvm::Triple::ppc64le:
1501       ABIName = "elfv2";
1502       break;
1503     default:
1504       break;
1505     }
1506
1507   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1508     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1509     // the option if given as we don't have backend support for any targets
1510     // that don't use the altivec abi.
1511     if (StringRef(A->getValue()) != "altivec")
1512       ABIName = A->getValue();
1513
1514   ppc::FloatABI FloatABI =
1515       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1516
1517   if (FloatABI == ppc::FloatABI::Soft) {
1518     // Floating point operations and argument passing are soft.
1519     CmdArgs.push_back("-msoft-float");
1520     CmdArgs.push_back("-mfloat-abi");
1521     CmdArgs.push_back("soft");
1522   } else {
1523     // Floating point operations and argument passing are hard.
1524     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1525     CmdArgs.push_back("-mfloat-abi");
1526     CmdArgs.push_back("hard");
1527   }
1528
1529   if (ABIName) {
1530     CmdArgs.push_back("-target-abi");
1531     CmdArgs.push_back(ABIName);
1532   }
1533 }
1534
1535 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1536   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1537   return A && (A->getValue() == StringRef(Value));
1538 }
1539
1540 /// Get the (LLVM) name of the R600 gpu we are targeting.
1541 static std::string getR600TargetGPU(const ArgList &Args) {
1542   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1543     const char *GPUName = A->getValue();
1544     return llvm::StringSwitch<const char *>(GPUName)
1545         .Cases("rv630", "rv635", "r600")
1546         .Cases("rv610", "rv620", "rs780", "rs880")
1547         .Case("rv740", "rv770")
1548         .Case("palm", "cedar")
1549         .Cases("sumo", "sumo2", "sumo")
1550         .Case("hemlock", "cypress")
1551         .Case("aruba", "cayman")
1552         .Default(GPUName);
1553   }
1554   return "";
1555 }
1556
1557 void Clang::AddSparcTargetArgs(const ArgList &Args,
1558                                ArgStringList &CmdArgs) const {
1559   const Driver &D = getToolChain().getDriver();
1560   std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1561
1562   bool SoftFloatABI = false;
1563   if (Arg *A =
1564           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1565     if (A->getOption().matches(options::OPT_msoft_float))
1566       SoftFloatABI = true;
1567   }
1568
1569   // Only the hard-float ABI on Sparc is standardized, and it is the
1570   // default. GCC also supports a nonstandard soft-float ABI mode, and
1571   // perhaps LLVM should implement that, too. However, since llvm
1572   // currently does not support Sparc soft-float, at all, display an
1573   // error if it's requested.
1574   if (SoftFloatABI) {
1575     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1576                                                      << Triple;
1577   }
1578 }
1579
1580 static const char *getSystemZTargetCPU(const ArgList &Args) {
1581   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1582     return A->getValue();
1583   return "z10";
1584 }
1585
1586 static void getSystemZTargetFeatures(const ArgList &Args,
1587                                      std::vector<const char *> &Features) {
1588   // -m(no-)htm overrides use of the transactional-execution facility.
1589   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1590     if (A->getOption().matches(options::OPT_mhtm))
1591       Features.push_back("+transactional-execution");
1592     else
1593       Features.push_back("-transactional-execution");
1594   }
1595   // -m(no-)vx overrides use of the vector facility.
1596   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1597     if (A->getOption().matches(options::OPT_mvx))
1598       Features.push_back("+vector");
1599     else
1600       Features.push_back("-vector");
1601   }
1602 }
1603
1604 static const char *getX86TargetCPU(const ArgList &Args,
1605                                    const llvm::Triple &Triple) {
1606   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1607     if (StringRef(A->getValue()) != "native") {
1608       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1609         return "core-avx2";
1610
1611       return A->getValue();
1612     }
1613
1614     // FIXME: Reject attempts to use -march=native unless the target matches
1615     // the host.
1616     //
1617     // FIXME: We should also incorporate the detected target features for use
1618     // with -native.
1619     std::string CPU = llvm::sys::getHostCPUName();
1620     if (!CPU.empty() && CPU != "generic")
1621       return Args.MakeArgString(CPU);
1622   }
1623
1624   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1625     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1626     StringRef Arch = A->getValue();
1627     const char *CPU;
1628     if (Triple.getArch() == llvm::Triple::x86) {
1629       CPU = llvm::StringSwitch<const char *>(Arch)
1630                 .Case("IA32", "i386")
1631                 .Case("SSE", "pentium3")
1632                 .Case("SSE2", "pentium4")
1633                 .Case("AVX", "sandybridge")
1634                 .Case("AVX2", "haswell")
1635                 .Default(nullptr);
1636     } else {
1637       CPU = llvm::StringSwitch<const char *>(Arch)
1638                 .Case("AVX", "sandybridge")
1639                 .Case("AVX2", "haswell")
1640                 .Default(nullptr);
1641     }
1642     if (CPU)
1643       return CPU;
1644   }
1645
1646   // Select the default CPU if none was given (or detection failed).
1647
1648   if (Triple.getArch() != llvm::Triple::x86_64 &&
1649       Triple.getArch() != llvm::Triple::x86)
1650     return nullptr; // This routine is only handling x86 targets.
1651
1652   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1653
1654   // FIXME: Need target hooks.
1655   if (Triple.isOSDarwin()) {
1656     if (Triple.getArchName() == "x86_64h")
1657       return "core-avx2";
1658     return Is64Bit ? "core2" : "yonah";
1659   }
1660
1661   // Set up default CPU name for PS4 compilers.
1662   if (Triple.isPS4CPU())
1663     return "btver2";
1664
1665   // On Android use targets compatible with gcc
1666   if (Triple.isAndroid())
1667     return Is64Bit ? "x86-64" : "i686";
1668
1669   // Everything else goes to x86-64 in 64-bit mode.
1670   if (Is64Bit)
1671     return "x86-64";
1672
1673   switch (Triple.getOS()) {
1674   case llvm::Triple::FreeBSD:
1675   case llvm::Triple::NetBSD:
1676   case llvm::Triple::OpenBSD:
1677     return "i486";
1678   case llvm::Triple::Haiku:
1679     return "i586";
1680   case llvm::Triple::Bitrig:
1681     return "i686";
1682   default:
1683     // Fallback to p4.
1684     return "pentium4";
1685   }
1686 }
1687
1688 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1689 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1690   // If we have -mcpu=, use that.
1691   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1692     StringRef CPU = A->getValue();
1693
1694 #ifdef __wasm__
1695     // Handle "native" by examining the host. "native" isn't meaningful when
1696     // cross compiling, so only support this when the host is also WebAssembly.
1697     if (CPU == "native")
1698       return llvm::sys::getHostCPUName();
1699 #endif
1700
1701     return CPU;
1702   }
1703
1704   return "generic";
1705 }
1706
1707 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1708                               bool FromAs = false) {
1709   switch (T.getArch()) {
1710   default:
1711     return "";
1712
1713   case llvm::Triple::aarch64:
1714   case llvm::Triple::aarch64_be:
1715     return getAArch64TargetCPU(Args);
1716
1717   case llvm::Triple::arm:
1718   case llvm::Triple::armeb:
1719   case llvm::Triple::thumb:
1720   case llvm::Triple::thumbeb: {
1721     StringRef MArch, MCPU;
1722     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1723     return arm::getARMTargetCPU(MCPU, MArch, T);
1724   }
1725   case llvm::Triple::mips:
1726   case llvm::Triple::mipsel:
1727   case llvm::Triple::mips64:
1728   case llvm::Triple::mips64el: {
1729     StringRef CPUName;
1730     StringRef ABIName;
1731     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1732     return CPUName;
1733   }
1734
1735   case llvm::Triple::nvptx:
1736   case llvm::Triple::nvptx64:
1737     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1738       return A->getValue();
1739     return "";
1740
1741   case llvm::Triple::ppc:
1742   case llvm::Triple::ppc64:
1743   case llvm::Triple::ppc64le: {
1744     std::string TargetCPUName = getPPCTargetCPU(Args);
1745     // LLVM may default to generating code for the native CPU,
1746     // but, like gcc, we default to a more generic option for
1747     // each architecture. (except on Darwin)
1748     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1749       if (T.getArch() == llvm::Triple::ppc64)
1750         TargetCPUName = "ppc64";
1751       else if (T.getArch() == llvm::Triple::ppc64le)
1752         TargetCPUName = "ppc64le";
1753       else
1754         TargetCPUName = "ppc";
1755     }
1756     return TargetCPUName;
1757   }
1758
1759   case llvm::Triple::sparc:
1760   case llvm::Triple::sparcel:
1761   case llvm::Triple::sparcv9:
1762     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763       return A->getValue();
1764     return "";
1765
1766   case llvm::Triple::x86:
1767   case llvm::Triple::x86_64:
1768     return getX86TargetCPU(Args, T);
1769
1770   case llvm::Triple::hexagon:
1771     return "hexagon" +
1772            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1773
1774   case llvm::Triple::systemz:
1775     return getSystemZTargetCPU(Args);
1776
1777   case llvm::Triple::r600:
1778   case llvm::Triple::amdgcn:
1779     return getR600TargetGPU(Args);
1780
1781   case llvm::Triple::wasm32:
1782   case llvm::Triple::wasm64:
1783     return getWebAssemblyTargetCPU(Args);
1784   }
1785 }
1786
1787 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1788                           ArgStringList &CmdArgs, bool IsThinLTO) {
1789   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1790   // as gold requires -plugin to come before any -plugin-opt that -Wl might
1791   // forward.
1792   CmdArgs.push_back("-plugin");
1793   std::string Plugin =
1794       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1795   CmdArgs.push_back(Args.MakeArgString(Plugin));
1796
1797   // Try to pass driver level flags relevant to LTO code generation down to
1798   // the plugin.
1799
1800   // Handle flags for selecting CPU variants.
1801   std::string CPU = getCPUName(Args, ToolChain.getTriple());
1802   if (!CPU.empty())
1803     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1804
1805   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1806     StringRef OOpt;
1807     if (A->getOption().matches(options::OPT_O4) ||
1808         A->getOption().matches(options::OPT_Ofast))
1809       OOpt = "3";
1810     else if (A->getOption().matches(options::OPT_O))
1811       OOpt = A->getValue();
1812     else if (A->getOption().matches(options::OPT_O0))
1813       OOpt = "0";
1814     if (!OOpt.empty())
1815       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
1816   }
1817
1818   if (IsThinLTO)
1819     CmdArgs.push_back("-plugin-opt=thinlto");
1820 }
1821
1822 /// This is a helper function for validating the optional refinement step
1823 /// parameter in reciprocal argument strings. Return false if there is an error
1824 /// parsing the refinement step. Otherwise, return true and set the Position
1825 /// of the refinement step in the input string.
1826 static bool getRefinementStep(StringRef In, const Driver &D,
1827                               const Arg &A, size_t &Position) {
1828   const char RefinementStepToken = ':';
1829   Position = In.find(RefinementStepToken);
1830   if (Position != StringRef::npos) {
1831     StringRef Option = A.getOption().getName();
1832     StringRef RefStep = In.substr(Position + 1);
1833     // Allow exactly one numeric character for the additional refinement
1834     // step parameter. This is reasonable for all currently-supported
1835     // operations and architectures because we would expect that a larger value
1836     // of refinement steps would cause the estimate "optimization" to
1837     // under-perform the native operation. Also, if the estimate does not
1838     // converge quickly, it probably will not ever converge, so further
1839     // refinement steps will not produce a better answer.
1840     if (RefStep.size() != 1) {
1841       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1842       return false;
1843     }
1844     char RefStepChar = RefStep[0];
1845     if (RefStepChar < '0' || RefStepChar > '9') {
1846       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1847       return false;
1848     }
1849   }
1850   return true;
1851 }
1852
1853 /// The -mrecip flag requires processing of many optional parameters.
1854 static void ParseMRecip(const Driver &D, const ArgList &Args,
1855                         ArgStringList &OutStrings) {
1856   StringRef DisabledPrefixIn = "!";
1857   StringRef DisabledPrefixOut = "!";
1858   StringRef EnabledPrefixOut = "";
1859   StringRef Out = "-mrecip=";
1860
1861   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1862   if (!A)
1863     return;
1864
1865   unsigned NumOptions = A->getNumValues();
1866   if (NumOptions == 0) {
1867     // No option is the same as "all".
1868     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1869     return;
1870   }
1871
1872   // Pass through "all", "none", or "default" with an optional refinement step.
1873   if (NumOptions == 1) {
1874     StringRef Val = A->getValue(0);
1875     size_t RefStepLoc;
1876     if (!getRefinementStep(Val, D, *A, RefStepLoc))
1877       return;
1878     StringRef ValBase = Val.slice(0, RefStepLoc);
1879     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1880       OutStrings.push_back(Args.MakeArgString(Out + Val));
1881       return;
1882     }
1883   }
1884
1885   // Each reciprocal type may be enabled or disabled individually.
1886   // Check each input value for validity, concatenate them all back together,
1887   // and pass through.
1888
1889   llvm::StringMap<bool> OptionStrings;
1890   OptionStrings.insert(std::make_pair("divd", false));
1891   OptionStrings.insert(std::make_pair("divf", false));
1892   OptionStrings.insert(std::make_pair("vec-divd", false));
1893   OptionStrings.insert(std::make_pair("vec-divf", false));
1894   OptionStrings.insert(std::make_pair("sqrtd", false));
1895   OptionStrings.insert(std::make_pair("sqrtf", false));
1896   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1897   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1898
1899   for (unsigned i = 0; i != NumOptions; ++i) {
1900     StringRef Val = A->getValue(i);
1901
1902     bool IsDisabled = Val.startswith(DisabledPrefixIn);
1903     // Ignore the disablement token for string matching.
1904     if (IsDisabled)
1905       Val = Val.substr(1);
1906
1907     size_t RefStep;
1908     if (!getRefinementStep(Val, D, *A, RefStep))
1909       return;
1910
1911     StringRef ValBase = Val.slice(0, RefStep);
1912     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1913     if (OptionIter == OptionStrings.end()) {
1914       // Try again specifying float suffix.
1915       OptionIter = OptionStrings.find(ValBase.str() + 'f');
1916       if (OptionIter == OptionStrings.end()) {
1917         // The input name did not match any known option string.
1918         D.Diag(diag::err_drv_unknown_argument) << Val;
1919         return;
1920       }
1921       // The option was specified without a float or double suffix.
1922       // Make sure that the double entry was not already specified.
1923       // The float entry will be checked below.
1924       if (OptionStrings[ValBase.str() + 'd']) {
1925         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1926         return;
1927       }
1928     }
1929
1930     if (OptionIter->second == true) {
1931       // Duplicate option specified.
1932       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1933       return;
1934     }
1935
1936     // Mark the matched option as found. Do not allow duplicate specifiers.
1937     OptionIter->second = true;
1938
1939     // If the precision was not specified, also mark the double entry as found.
1940     if (ValBase.back() != 'f' && ValBase.back() != 'd')
1941       OptionStrings[ValBase.str() + 'd'] = true;
1942
1943     // Build the output string.
1944     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1945     Out = Args.MakeArgString(Out + Prefix + Val);
1946     if (i != NumOptions - 1)
1947       Out = Args.MakeArgString(Out + ",");
1948   }
1949
1950   OutStrings.push_back(Args.MakeArgString(Out));
1951 }
1952
1953 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1954                                  const ArgList &Args,
1955                                  std::vector<const char *> &Features) {
1956   // If -march=native, autodetect the feature list.
1957   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1958     if (StringRef(A->getValue()) == "native") {
1959       llvm::StringMap<bool> HostFeatures;
1960       if (llvm::sys::getHostCPUFeatures(HostFeatures))
1961         for (auto &F : HostFeatures)
1962           Features.push_back(
1963               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1964     }
1965   }
1966
1967   if (Triple.getArchName() == "x86_64h") {
1968     // x86_64h implies quite a few of the more modern subtarget features
1969     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1970     Features.push_back("-rdrnd");
1971     Features.push_back("-aes");
1972     Features.push_back("-pclmul");
1973     Features.push_back("-rtm");
1974     Features.push_back("-hle");
1975     Features.push_back("-fsgsbase");
1976   }
1977
1978   const llvm::Triple::ArchType ArchType = Triple.getArch();
1979   // Add features to be compatible with gcc for Android.
1980   if (Triple.isAndroid()) {
1981     if (ArchType == llvm::Triple::x86_64) {
1982       Features.push_back("+sse4.2");
1983       Features.push_back("+popcnt");
1984     } else
1985       Features.push_back("+ssse3");
1986   }
1987
1988   // Set features according to the -arch flag on MSVC.
1989   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1990     StringRef Arch = A->getValue();
1991     bool ArchUsed = false;
1992     // First, look for flags that are shared in x86 and x86-64.
1993     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1994       if (Arch == "AVX" || Arch == "AVX2") {
1995         ArchUsed = true;
1996         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1997       }
1998     }
1999     // Then, look for x86-specific flags.
2000     if (ArchType == llvm::Triple::x86) {
2001       if (Arch == "IA32") {
2002         ArchUsed = true;
2003       } else if (Arch == "SSE" || Arch == "SSE2") {
2004         ArchUsed = true;
2005         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2006       }
2007     }
2008     if (!ArchUsed)
2009       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2010   }
2011
2012   // Now add any that the user explicitly requested on the command line,
2013   // which may override the defaults.
2014   handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2015 }
2016
2017 void Clang::AddX86TargetArgs(const ArgList &Args,
2018                              ArgStringList &CmdArgs) const {
2019   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2020       Args.hasArg(options::OPT_mkernel) ||
2021       Args.hasArg(options::OPT_fapple_kext))
2022     CmdArgs.push_back("-disable-red-zone");
2023
2024   // Default to avoid implicit floating-point for kernel/kext code, but allow
2025   // that to be overridden with -mno-soft-float.
2026   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2027                           Args.hasArg(options::OPT_fapple_kext));
2028   if (Arg *A = Args.getLastArg(
2029           options::OPT_msoft_float, options::OPT_mno_soft_float,
2030           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2031     const Option &O = A->getOption();
2032     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2033                        O.matches(options::OPT_msoft_float));
2034   }
2035   if (NoImplicitFloat)
2036     CmdArgs.push_back("-no-implicit-float");
2037
2038   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2039     StringRef Value = A->getValue();
2040     if (Value == "intel" || Value == "att") {
2041       CmdArgs.push_back("-mllvm");
2042       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2043     } else {
2044       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2045           << A->getOption().getName() << Value;
2046     }
2047   }
2048 }
2049
2050 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2051                                  ArgStringList &CmdArgs) const {
2052   CmdArgs.push_back("-mqdsp6-compat");
2053   CmdArgs.push_back("-Wreturn-type");
2054
2055   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2056     std::string N = llvm::utostr(G.getValue());
2057     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2058     CmdArgs.push_back("-mllvm");
2059     CmdArgs.push_back(Args.MakeArgString(Opt));
2060   }
2061
2062   if (!Args.hasArg(options::OPT_fno_short_enums))
2063     CmdArgs.push_back("-fshort-enums");
2064   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2065     CmdArgs.push_back("-mllvm");
2066     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2067   }
2068   CmdArgs.push_back("-mllvm");
2069   CmdArgs.push_back("-machine-sink-split=0");
2070 }
2071
2072 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2073                                      ArgStringList &CmdArgs) const {
2074   // Default to "hidden" visibility.
2075   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2076                    options::OPT_fvisibility_ms_compat)) {
2077     CmdArgs.push_back("-fvisibility");
2078     CmdArgs.push_back("hidden");
2079   }
2080 }
2081
2082 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2083 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2084                                   std::vector<const char *> &Features) {
2085   SmallVector<StringRef, 8> Split;
2086   text.split(Split, StringRef("+"), -1, false);
2087
2088   for (StringRef Feature : Split) {
2089     const char *result = llvm::StringSwitch<const char *>(Feature)
2090                              .Case("fp", "+fp-armv8")
2091                              .Case("simd", "+neon")
2092                              .Case("crc", "+crc")
2093                              .Case("crypto", "+crypto")
2094                              .Case("fp16", "+fullfp16")
2095                              .Case("profile", "+spe")
2096                              .Case("nofp", "-fp-armv8")
2097                              .Case("nosimd", "-neon")
2098                              .Case("nocrc", "-crc")
2099                              .Case("nocrypto", "-crypto")
2100                              .Case("nofp16", "-fullfp16")
2101                              .Case("noprofile", "-spe")
2102                              .Default(nullptr);
2103     if (result)
2104       Features.push_back(result);
2105     else if (Feature == "neon" || Feature == "noneon")
2106       D.Diag(diag::err_drv_no_neon_modifier);
2107     else
2108       return false;
2109   }
2110   return true;
2111 }
2112
2113 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2114 // decode CPU and feature.
2115 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2116                               std::vector<const char *> &Features) {
2117   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2118   CPU = Split.first;
2119   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2120       CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1") {
2121     Features.push_back("+neon");
2122     Features.push_back("+crc");
2123     Features.push_back("+crypto");
2124   } else if (CPU == "generic") {
2125     Features.push_back("+neon");
2126   } else {
2127     return false;
2128   }
2129
2130   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2131     return false;
2132
2133   return true;
2134 }
2135
2136 static bool
2137 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2138                                 const ArgList &Args,
2139                                 std::vector<const char *> &Features) {
2140   std::string MarchLowerCase = March.lower();
2141   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2142
2143   if (Split.first == "armv8-a" || Split.first == "armv8a") {
2144     // ok, no additional features.
2145   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2146     Features.push_back("+v8.1a");
2147   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2148     Features.push_back("+v8.2a");
2149   } else {
2150     return false;
2151   }
2152
2153   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2154     return false;
2155
2156   return true;
2157 }
2158
2159 static bool
2160 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2161                                const ArgList &Args,
2162                                std::vector<const char *> &Features) {
2163   StringRef CPU;
2164   std::string McpuLowerCase = Mcpu.lower();
2165   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2166     return false;
2167
2168   return true;
2169 }
2170
2171 static bool
2172 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2173                                      const ArgList &Args,
2174                                      std::vector<const char *> &Features) {
2175   std::string MtuneLowerCase = Mtune.lower();
2176   // Handle CPU name is 'native'.
2177   if (MtuneLowerCase == "native")
2178     MtuneLowerCase = llvm::sys::getHostCPUName();
2179   if (MtuneLowerCase == "cyclone") {
2180     Features.push_back("+zcm");
2181     Features.push_back("+zcz");
2182   }
2183   return true;
2184 }
2185
2186 static bool
2187 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2188                                     const ArgList &Args,
2189                                     std::vector<const char *> &Features) {
2190   StringRef CPU;
2191   std::vector<const char *> DecodedFeature;
2192   std::string McpuLowerCase = Mcpu.lower();
2193   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2194     return false;
2195
2196   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2197 }
2198
2199 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2200                                      std::vector<const char *> &Features) {
2201   Arg *A;
2202   bool success = true;
2203   // Enable NEON by default.
2204   Features.push_back("+neon");
2205   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2206     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2207   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2208     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2209   else if (Args.hasArg(options::OPT_arch))
2210     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2211                                              Features);
2212
2213   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2214     success =
2215         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2216   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2217     success =
2218         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2219   else if (Args.hasArg(options::OPT_arch))
2220     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2221                                                   Args, Features);
2222
2223   if (!success)
2224     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2225
2226   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2227     Features.push_back("-fp-armv8");
2228     Features.push_back("-crypto");
2229     Features.push_back("-neon");
2230   }
2231
2232   // En/disable crc
2233   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2234     if (A->getOption().matches(options::OPT_mcrc))
2235       Features.push_back("+crc");
2236     else
2237       Features.push_back("-crc");
2238   }
2239
2240   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2241                                options::OPT_munaligned_access))
2242     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2243       Features.push_back("+strict-align");
2244
2245   if (Args.hasArg(options::OPT_ffixed_x18))
2246     Features.push_back("+reserve-x18");
2247 }
2248
2249 static void getHexagonTargetFeatures(const ArgList &Args,
2250                                      std::vector<const char *> &Features) {
2251   bool HasHVX = false, HasHVXD = false;
2252
2253   // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2254   // doing dependent option handling here rather than in initFeatureMap or a
2255   // similar handler.
2256   for (auto &A : Args) {
2257     auto &Opt = A->getOption();
2258     if (Opt.matches(options::OPT_mhexagon_hvx))
2259       HasHVX = true;
2260     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2261       HasHVXD = HasHVX = false;
2262     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2263       HasHVXD = HasHVX = true;
2264     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2265       HasHVXD = false;
2266     else
2267       continue;
2268     A->claim();
2269   }
2270
2271   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
2272   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2273 }
2274
2275 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2276                                          std::vector<const char *> &Features) {
2277   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2278 }
2279
2280 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2281                               const ArgList &Args, ArgStringList &CmdArgs,
2282                               bool ForAS) {
2283   const Driver &D = TC.getDriver();
2284   std::vector<const char *> Features;
2285   switch (Triple.getArch()) {
2286   default:
2287     break;
2288   case llvm::Triple::mips:
2289   case llvm::Triple::mipsel:
2290   case llvm::Triple::mips64:
2291   case llvm::Triple::mips64el:
2292     getMIPSTargetFeatures(D, Triple, Args, Features);
2293     break;
2294
2295   case llvm::Triple::arm:
2296   case llvm::Triple::armeb:
2297   case llvm::Triple::thumb:
2298   case llvm::Triple::thumbeb:
2299     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2300     break;
2301
2302   case llvm::Triple::ppc:
2303   case llvm::Triple::ppc64:
2304   case llvm::Triple::ppc64le:
2305     getPPCTargetFeatures(D, Triple, Args, Features);
2306     break;
2307   case llvm::Triple::systemz:
2308     getSystemZTargetFeatures(Args, Features);
2309     break;
2310   case llvm::Triple::aarch64:
2311   case llvm::Triple::aarch64_be:
2312     getAArch64TargetFeatures(D, Args, Features);
2313     break;
2314   case llvm::Triple::x86:
2315   case llvm::Triple::x86_64:
2316     getX86TargetFeatures(D, Triple, Args, Features);
2317     break;
2318   case llvm::Triple::hexagon:
2319     getHexagonTargetFeatures(Args, Features);
2320     break;
2321   case llvm::Triple::wasm32:
2322   case llvm::Triple::wasm64:
2323     getWebAssemblyTargetFeatures(Args, Features);
2324     break;
2325   }
2326
2327   // Find the last of each feature.
2328   llvm::StringMap<unsigned> LastOpt;
2329   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2330     const char *Name = Features[I];
2331     assert(Name[0] == '-' || Name[0] == '+');
2332     LastOpt[Name + 1] = I;
2333   }
2334
2335   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2336     // If this feature was overridden, ignore it.
2337     const char *Name = Features[I];
2338     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2339     assert(LastI != LastOpt.end());
2340     unsigned Last = LastI->second;
2341     if (Last != I)
2342       continue;
2343
2344     CmdArgs.push_back("-target-feature");
2345     CmdArgs.push_back(Name);
2346   }
2347 }
2348
2349 static bool
2350 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2351                                           const llvm::Triple &Triple) {
2352   // We use the zero-cost exception tables for Objective-C if the non-fragile
2353   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2354   // later.
2355   if (runtime.isNonFragile())
2356     return true;
2357
2358   if (!Triple.isMacOSX())
2359     return false;
2360
2361   return (!Triple.isMacOSXVersionLT(10, 5) &&
2362           (Triple.getArch() == llvm::Triple::x86_64 ||
2363            Triple.getArch() == llvm::Triple::arm));
2364 }
2365
2366 /// Adds exception related arguments to the driver command arguments. There's a
2367 /// master flag, -fexceptions and also language specific flags to enable/disable
2368 /// C++ and Objective-C exceptions. This makes it possible to for example
2369 /// disable C++ exceptions but enable Objective-C exceptions.
2370 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2371                              const ToolChain &TC, bool KernelOrKext,
2372                              const ObjCRuntime &objcRuntime,
2373                              ArgStringList &CmdArgs) {
2374   const Driver &D = TC.getDriver();
2375   const llvm::Triple &Triple = TC.getTriple();
2376
2377   if (KernelOrKext) {
2378     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2379     // arguments now to avoid warnings about unused arguments.
2380     Args.ClaimAllArgs(options::OPT_fexceptions);
2381     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2382     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2383     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2384     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2385     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2386     return;
2387   }
2388
2389   // See if the user explicitly enabled exceptions.
2390   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2391                          false);
2392
2393   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2394   // is not necessarily sensible, but follows GCC.
2395   if (types::isObjC(InputType) &&
2396       Args.hasFlag(options::OPT_fobjc_exceptions,
2397                    options::OPT_fno_objc_exceptions, true)) {
2398     CmdArgs.push_back("-fobjc-exceptions");
2399
2400     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2401   }
2402
2403   if (types::isCXX(InputType)) {
2404     // Disable C++ EH by default on XCore, PS4, and MSVC.
2405     // FIXME: Remove MSVC from this list once things work.
2406     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2407                                 !Triple.isPS4CPU() &&
2408                                 !Triple.isWindowsMSVCEnvironment();
2409     Arg *ExceptionArg = Args.getLastArg(
2410         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2411         options::OPT_fexceptions, options::OPT_fno_exceptions);
2412     if (ExceptionArg)
2413       CXXExceptionsEnabled =
2414           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2415           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2416
2417     if (CXXExceptionsEnabled) {
2418       if (Triple.isPS4CPU()) {
2419         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2420         assert(ExceptionArg &&
2421                "On the PS4 exceptions should only be enabled if passing "
2422                "an argument");
2423         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2424           const Arg *RTTIArg = TC.getRTTIArg();
2425           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2426           D.Diag(diag::err_drv_argument_not_allowed_with)
2427               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2428         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2429           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2430       } else
2431         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2432
2433       CmdArgs.push_back("-fcxx-exceptions");
2434
2435       EH = true;
2436     }
2437   }
2438
2439   if (EH)
2440     CmdArgs.push_back("-fexceptions");
2441 }
2442
2443 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2444   bool Default = true;
2445   if (TC.getTriple().isOSDarwin()) {
2446     // The native darwin assembler doesn't support the linker_option directives,
2447     // so we disable them if we think the .s file will be passed to it.
2448     Default = TC.useIntegratedAs();
2449   }
2450   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2451                        Default);
2452 }
2453
2454 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2455                                         const ToolChain &TC) {
2456   bool UseDwarfDirectory =
2457       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2458                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2459   return !UseDwarfDirectory;
2460 }
2461
2462 /// \brief Check whether the given input tree contains any compilation actions.
2463 static bool ContainsCompileAction(const Action *A) {
2464   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2465     return true;
2466
2467   for (const auto &Act : *A)
2468     if (ContainsCompileAction(Act))
2469       return true;
2470
2471   return false;
2472 }
2473
2474 /// \brief Check if -relax-all should be passed to the internal assembler.
2475 /// This is done by default when compiling non-assembler source with -O0.
2476 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2477   bool RelaxDefault = true;
2478
2479   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2480     RelaxDefault = A->getOption().matches(options::OPT_O0);
2481
2482   if (RelaxDefault) {
2483     RelaxDefault = false;
2484     for (const auto &Act : C.getActions()) {
2485       if (ContainsCompileAction(Act)) {
2486         RelaxDefault = true;
2487         break;
2488       }
2489     }
2490   }
2491
2492   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2493                       RelaxDefault);
2494 }
2495
2496 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2497 // to the corresponding DebugInfoKind.
2498 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2499   assert(A.getOption().matches(options::OPT_gN_Group) &&
2500          "Not a -g option that specifies a debug-info level");
2501   if (A.getOption().matches(options::OPT_g0) ||
2502       A.getOption().matches(options::OPT_ggdb0))
2503     return CodeGenOptions::NoDebugInfo;
2504   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2505       A.getOption().matches(options::OPT_ggdb1))
2506     return CodeGenOptions::DebugLineTablesOnly;
2507   return CodeGenOptions::LimitedDebugInfo;
2508 }
2509
2510 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2511 // on mismatch. The StringRef input (rather than an Arg) allows
2512 // for use by the "-Xassembler" option parser.
2513 static unsigned DwarfVersionNum(StringRef ArgValue) {
2514   return llvm::StringSwitch<unsigned>(ArgValue)
2515       .Case("-gdwarf-2", 2)
2516       .Case("-gdwarf-3", 3)
2517       .Case("-gdwarf-4", 4)
2518       .Case("-gdwarf-5", 5)
2519       .Default(0);
2520 }
2521
2522 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2523                                     CodeGenOptions::DebugInfoKind DebugInfoKind,
2524                                     unsigned DwarfVersion,
2525                                     llvm::DebuggerKind DebuggerTuning) {
2526   switch (DebugInfoKind) {
2527   case CodeGenOptions::DebugLineTablesOnly:
2528     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2529     break;
2530   case CodeGenOptions::LimitedDebugInfo:
2531     CmdArgs.push_back("-debug-info-kind=limited");
2532     break;
2533   case CodeGenOptions::FullDebugInfo:
2534     CmdArgs.push_back("-debug-info-kind=standalone");
2535     break;
2536   default:
2537     break;
2538   }
2539   if (DwarfVersion > 0)
2540     CmdArgs.push_back(
2541         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2542   switch (DebuggerTuning) {
2543   case llvm::DebuggerKind::GDB:
2544     CmdArgs.push_back("-debugger-tuning=gdb");
2545     break;
2546   case llvm::DebuggerKind::LLDB:
2547     CmdArgs.push_back("-debugger-tuning=lldb");
2548     break;
2549   case llvm::DebuggerKind::SCE:
2550     CmdArgs.push_back("-debugger-tuning=sce");
2551     break;
2552   default:
2553     break;
2554   }
2555 }
2556
2557 static void CollectArgsForIntegratedAssembler(Compilation &C,
2558                                               const ArgList &Args,
2559                                               ArgStringList &CmdArgs,
2560                                               const Driver &D) {
2561   if (UseRelaxAll(C, Args))
2562     CmdArgs.push_back("-mrelax-all");
2563
2564   // Only default to -mincremental-linker-compatible if we think we are
2565   // targeting the MSVC linker.
2566   bool DefaultIncrementalLinkerCompatible =
2567       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2568   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2569                    options::OPT_mno_incremental_linker_compatible,
2570                    DefaultIncrementalLinkerCompatible))
2571     CmdArgs.push_back("-mincremental-linker-compatible");
2572
2573   // When passing -I arguments to the assembler we sometimes need to
2574   // unconditionally take the next argument.  For example, when parsing
2575   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2576   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2577   // arg after parsing the '-I' arg.
2578   bool TakeNextArg = false;
2579
2580   // When using an integrated assembler, translate -Wa, and -Xassembler
2581   // options.
2582   bool CompressDebugSections = false;
2583   for (const Arg *A :
2584        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2585     A->claim();
2586
2587     for (StringRef Value : A->getValues()) {
2588       if (TakeNextArg) {
2589         CmdArgs.push_back(Value.data());
2590         TakeNextArg = false;
2591         continue;
2592       }
2593
2594       switch (C.getDefaultToolChain().getArch()) {
2595       default:
2596         break;
2597       case llvm::Triple::mips:
2598       case llvm::Triple::mipsel:
2599       case llvm::Triple::mips64:
2600       case llvm::Triple::mips64el:
2601         if (Value == "--trap") {
2602           CmdArgs.push_back("-target-feature");
2603           CmdArgs.push_back("+use-tcc-in-div");
2604           continue;
2605         }
2606         if (Value == "--break") {
2607           CmdArgs.push_back("-target-feature");
2608           CmdArgs.push_back("-use-tcc-in-div");
2609           continue;
2610         }
2611         if (Value.startswith("-msoft-float")) {
2612           CmdArgs.push_back("-target-feature");
2613           CmdArgs.push_back("+soft-float");
2614           continue;
2615         }
2616         if (Value.startswith("-mhard-float")) {
2617           CmdArgs.push_back("-target-feature");
2618           CmdArgs.push_back("-soft-float");
2619           continue;
2620         }
2621         break;
2622       }
2623
2624       if (Value == "-force_cpusubtype_ALL") {
2625         // Do nothing, this is the default and we don't support anything else.
2626       } else if (Value == "-L") {
2627         CmdArgs.push_back("-msave-temp-labels");
2628       } else if (Value == "--fatal-warnings") {
2629         CmdArgs.push_back("-massembler-fatal-warnings");
2630       } else if (Value == "--noexecstack") {
2631         CmdArgs.push_back("-mnoexecstack");
2632       } else if (Value == "-compress-debug-sections" ||
2633                  Value == "--compress-debug-sections") {
2634         CompressDebugSections = true;
2635       } else if (Value == "-nocompress-debug-sections" ||
2636                  Value == "--nocompress-debug-sections") {
2637         CompressDebugSections = false;
2638       } else if (Value.startswith("-I")) {
2639         CmdArgs.push_back(Value.data());
2640         // We need to consume the next argument if the current arg is a plain
2641         // -I. The next arg will be the include directory.
2642         if (Value == "-I")
2643           TakeNextArg = true;
2644       } else if (Value.startswith("-gdwarf-")) {
2645         // "-gdwarf-N" options are not cc1as options.
2646         unsigned DwarfVersion = DwarfVersionNum(Value);
2647         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2648           CmdArgs.push_back(Value.data());
2649         } else {
2650           RenderDebugEnablingArgs(
2651               Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2652               llvm::DebuggerKind::Default);
2653         }
2654       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2655                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2656         // Do nothing, we'll validate it later.
2657       } else {
2658         D.Diag(diag::err_drv_unsupported_option_argument)
2659             << A->getOption().getName() << Value;
2660       }
2661     }
2662   }
2663   if (CompressDebugSections) {
2664     if (llvm::zlib::isAvailable())
2665       CmdArgs.push_back("-compress-debug-sections");
2666     else
2667       D.Diag(diag::warn_debug_compression_unavailable);
2668   }
2669 }
2670
2671 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2672 // FIXME: Make sure we can also emit shared objects if they're requested
2673 // and available, check for possible errors, etc.
2674 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2675                        ArgStringList &CmdArgs) {
2676   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2677 }
2678
2679 namespace {
2680 enum OpenMPRuntimeKind {
2681   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2682   /// without knowing what runtime to target.
2683   OMPRT_Unknown,
2684
2685   /// The LLVM OpenMP runtime. When completed and integrated, this will become
2686   /// the default for Clang.
2687   OMPRT_OMP,
2688
2689   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2690   /// this runtime but can swallow the pragmas, and find and link against the
2691   /// runtime library itself.
2692   OMPRT_GOMP,
2693
2694   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2695   /// OpenMP runtime. We support this mode for users with existing dependencies
2696   /// on this runtime library name.
2697   OMPRT_IOMP5
2698 };
2699 }
2700
2701 /// Compute the desired OpenMP runtime from the flag provided.
2702 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2703                                           const ArgList &Args) {
2704   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2705
2706   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2707   if (A)
2708     RuntimeName = A->getValue();
2709
2710   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2711                 .Case("libomp", OMPRT_OMP)
2712                 .Case("libgomp", OMPRT_GOMP)
2713                 .Case("libiomp5", OMPRT_IOMP5)
2714                 .Default(OMPRT_Unknown);
2715
2716   if (RT == OMPRT_Unknown) {
2717     if (A)
2718       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2719           << A->getOption().getName() << A->getValue();
2720     else
2721       // FIXME: We could use a nicer diagnostic here.
2722       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2723   }
2724
2725   return RT;
2726 }
2727
2728 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2729                               const ArgList &Args) {
2730   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2731                     options::OPT_fno_openmp, false))
2732     return;
2733
2734   switch (getOpenMPRuntime(TC, Args)) {
2735   case OMPRT_OMP:
2736     CmdArgs.push_back("-lomp");
2737     break;
2738   case OMPRT_GOMP:
2739     CmdArgs.push_back("-lgomp");
2740     break;
2741   case OMPRT_IOMP5:
2742     CmdArgs.push_back("-liomp5");
2743     break;
2744   case OMPRT_Unknown:
2745     // Already diagnosed.
2746     break;
2747   }
2748 }
2749
2750 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2751                                 ArgStringList &CmdArgs, StringRef Sanitizer,
2752                                 bool IsShared) {
2753   // Static runtimes must be forced into executable, so we wrap them in
2754   // whole-archive.
2755   if (!IsShared) CmdArgs.push_back("-whole-archive");
2756   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2757   if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2758 }
2759
2760 // Tries to use a file with the list of dynamic symbols that need to be exported
2761 // from the runtime library. Returns true if the file was found.
2762 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2763                                     ArgStringList &CmdArgs,
2764                                     StringRef Sanitizer) {
2765   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2766   if (llvm::sys::fs::exists(SanRT + ".syms")) {
2767     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2768     return true;
2769   }
2770   return false;
2771 }
2772
2773 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2774                                      ArgStringList &CmdArgs) {
2775   // Force linking against the system libraries sanitizers depends on
2776   // (see PR15823 why this is necessary).
2777   CmdArgs.push_back("--no-as-needed");
2778   CmdArgs.push_back("-lpthread");
2779   CmdArgs.push_back("-lrt");
2780   CmdArgs.push_back("-lm");
2781   // There's no libdl on FreeBSD.
2782   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2783     CmdArgs.push_back("-ldl");
2784 }
2785
2786 static void
2787 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2788                          SmallVectorImpl<StringRef> &SharedRuntimes,
2789                          SmallVectorImpl<StringRef> &StaticRuntimes,
2790                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2791   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2792   // Collect shared runtimes.
2793   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2794     SharedRuntimes.push_back("asan");
2795   }
2796
2797   // Collect static runtimes.
2798   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2799     // Don't link static runtimes into DSOs or if compiling for Android.
2800     return;
2801   }
2802   if (SanArgs.needsAsanRt()) {
2803     if (SanArgs.needsSharedAsanRt()) {
2804       HelperStaticRuntimes.push_back("asan-preinit");
2805     } else {
2806       StaticRuntimes.push_back("asan");
2807       if (SanArgs.linkCXXRuntimes())
2808         StaticRuntimes.push_back("asan_cxx");
2809     }
2810   }
2811   if (SanArgs.needsDfsanRt())
2812     StaticRuntimes.push_back("dfsan");
2813   if (SanArgs.needsLsanRt())
2814     StaticRuntimes.push_back("lsan");
2815   if (SanArgs.needsMsanRt()) {
2816     StaticRuntimes.push_back("msan");
2817     if (SanArgs.linkCXXRuntimes())
2818       StaticRuntimes.push_back("msan_cxx");
2819   }
2820   if (SanArgs.needsTsanRt()) {
2821     StaticRuntimes.push_back("tsan");
2822     if (SanArgs.linkCXXRuntimes())
2823       StaticRuntimes.push_back("tsan_cxx");
2824   }
2825   if (SanArgs.needsUbsanRt()) {
2826     StaticRuntimes.push_back("ubsan_standalone");
2827     if (SanArgs.linkCXXRuntimes())
2828       StaticRuntimes.push_back("ubsan_standalone_cxx");
2829   }
2830   if (SanArgs.needsSafeStackRt())
2831     StaticRuntimes.push_back("safestack");
2832   if (SanArgs.needsCfiRt())
2833     StaticRuntimes.push_back("cfi");
2834   if (SanArgs.needsCfiDiagRt())
2835     StaticRuntimes.push_back("cfi_diag");
2836 }
2837
2838 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2839 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2840 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2841                                  ArgStringList &CmdArgs) {
2842   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2843       HelperStaticRuntimes;
2844   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2845                            HelperStaticRuntimes);
2846   for (auto RT : SharedRuntimes)
2847     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2848   for (auto RT : HelperStaticRuntimes)
2849     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2850   bool AddExportDynamic = false;
2851   for (auto RT : StaticRuntimes) {
2852     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2853     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2854   }
2855   // If there is a static runtime with no dynamic list, force all the symbols
2856   // to be dynamic to be sure we export sanitizer interface functions.
2857   if (AddExportDynamic)
2858     CmdArgs.push_back("-export-dynamic");
2859   return !StaticRuntimes.empty();
2860 }
2861
2862 static bool areOptimizationsEnabled(const ArgList &Args) {
2863   // Find the last -O arg and see if it is non-zero.
2864   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2865     return !A->getOption().matches(options::OPT_O0);
2866   // Defaults to -O0.
2867   return false;
2868 }
2869
2870 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2871                                            const llvm::Triple &Triple) {
2872   switch (Triple.getArch()) {
2873   case llvm::Triple::xcore:
2874   case llvm::Triple::wasm32:
2875   case llvm::Triple::wasm64:
2876     // XCore never wants frame pointers, regardless of OS.
2877     // WebAssembly never wants frame pointers.
2878     return false;
2879   default:
2880     break;
2881   }
2882
2883   if (Triple.isOSLinux()) {
2884     switch (Triple.getArch()) {
2885     // Don't use a frame pointer on linux if optimizing for certain targets.
2886     case llvm::Triple::mips64:
2887     case llvm::Triple::mips64el:
2888     case llvm::Triple::mips:
2889     case llvm::Triple::mipsel:
2890     case llvm::Triple::systemz:
2891     case llvm::Triple::x86:
2892     case llvm::Triple::x86_64:
2893       return !areOptimizationsEnabled(Args);
2894     default:
2895       return true;
2896     }
2897   }
2898
2899   if (Triple.isOSWindows()) {
2900     switch (Triple.getArch()) {
2901     case llvm::Triple::x86:
2902       return !areOptimizationsEnabled(Args);
2903     case llvm::Triple::arm:
2904     case llvm::Triple::thumb:
2905       // Windows on ARM builds with FPO disabled to aid fast stack walking
2906       return true;
2907     default:
2908       // All other supported Windows ISAs use xdata unwind information, so frame
2909       // pointers are not generally useful.
2910       return false;
2911     }
2912   }
2913
2914   return true;
2915 }
2916
2917 static bool shouldUseFramePointer(const ArgList &Args,
2918                                   const llvm::Triple &Triple) {
2919   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2920                                options::OPT_fomit_frame_pointer))
2921     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2922   if (Args.hasArg(options::OPT_pg))
2923     return true;
2924
2925   return shouldUseFramePointerForTarget(Args, Triple);
2926 }
2927
2928 static bool shouldUseLeafFramePointer(const ArgList &Args,
2929                                       const llvm::Triple &Triple) {
2930   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2931                                options::OPT_momit_leaf_frame_pointer))
2932     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2933   if (Args.hasArg(options::OPT_pg))
2934     return true;
2935
2936   if (Triple.isPS4CPU())
2937     return false;
2938
2939   return shouldUseFramePointerForTarget(Args, Triple);
2940 }
2941
2942 /// Add a CC1 option to specify the debug compilation directory.
2943 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2944   SmallString<128> cwd;
2945   if (!llvm::sys::fs::current_path(cwd)) {
2946     CmdArgs.push_back("-fdebug-compilation-dir");
2947     CmdArgs.push_back(Args.MakeArgString(cwd));
2948   }
2949 }
2950
2951 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2952   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2953   if (FinalOutput && Args.hasArg(options::OPT_c)) {
2954     SmallString<128> T(FinalOutput->getValue());
2955     llvm::sys::path::replace_extension(T, "dwo");
2956     return Args.MakeArgString(T);
2957   } else {
2958     // Use the compilation dir.
2959     SmallString<128> T(
2960         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2961     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2962     llvm::sys::path::replace_extension(F, "dwo");
2963     T += F;
2964     return Args.MakeArgString(F);
2965   }
2966 }
2967
2968 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2969                            const JobAction &JA, const ArgList &Args,
2970                            const InputInfo &Output, const char *OutFile) {
2971   ArgStringList ExtractArgs;
2972   ExtractArgs.push_back("--extract-dwo");
2973
2974   ArgStringList StripArgs;
2975   StripArgs.push_back("--strip-dwo");
2976
2977   // Grabbing the output of the earlier compile step.
2978   StripArgs.push_back(Output.getFilename());
2979   ExtractArgs.push_back(Output.getFilename());
2980   ExtractArgs.push_back(OutFile);
2981
2982   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2983   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
2984
2985   // First extract the dwo sections.
2986   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2987
2988   // Then remove them from the original .o file.
2989   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2990 }
2991
2992 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2993 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2994 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2995   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2996     if (A->getOption().matches(options::OPT_O4) ||
2997         A->getOption().matches(options::OPT_Ofast))
2998       return true;
2999
3000     if (A->getOption().matches(options::OPT_O0))
3001       return false;
3002
3003     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3004
3005     // Vectorize -Os.
3006     StringRef S(A->getValue());
3007     if (S == "s")
3008       return true;
3009
3010     // Don't vectorize -Oz, unless it's the slp vectorizer.
3011     if (S == "z")
3012       return isSlpVec;
3013
3014     unsigned OptLevel = 0;
3015     if (S.getAsInteger(10, OptLevel))
3016       return false;
3017
3018     return OptLevel > 1;
3019   }
3020
3021   return false;
3022 }
3023
3024 /// Add -x lang to \p CmdArgs for \p Input.
3025 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3026                              ArgStringList &CmdArgs) {
3027   // When using -verify-pch, we don't want to provide the type
3028   // 'precompiled-header' if it was inferred from the file extension
3029   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3030     return;
3031
3032   CmdArgs.push_back("-x");
3033   if (Args.hasArg(options::OPT_rewrite_objc))
3034     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3035   else
3036     CmdArgs.push_back(types::getTypeName(Input.getType()));
3037 }
3038
3039 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3040   if (Version < 100)
3041     return VersionTuple(Version);
3042
3043   if (Version < 10000)
3044     return VersionTuple(Version / 100, Version % 100);
3045
3046   unsigned Build = 0, Factor = 1;
3047   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3048     Build = Build + (Version % 10) * Factor;
3049   return VersionTuple(Version / 100, Version % 100, Build);
3050 }
3051
3052 // Claim options we don't want to warn if they are unused. We do this for
3053 // options that build systems might add but are unused when assembling or only
3054 // running the preprocessor for example.
3055 static void claimNoWarnArgs(const ArgList &Args) {
3056   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3057   // preprocessing, precompiling or assembling.
3058   Args.ClaimAllArgs(options::OPT_flto_EQ);
3059   Args.ClaimAllArgs(options::OPT_flto);
3060   Args.ClaimAllArgs(options::OPT_fno_lto);
3061 }
3062
3063 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3064 #ifdef LLVM_ON_UNIX
3065   const char *Username = getenv("LOGNAME");
3066 #else
3067   const char *Username = getenv("USERNAME");
3068 #endif
3069   if (Username) {
3070     // Validate that LoginName can be used in a path, and get its length.
3071     size_t Len = 0;
3072     for (const char *P = Username; *P; ++P, ++Len) {
3073       if (!isAlphanumeric(*P) && *P != '_') {
3074         Username = nullptr;
3075         break;
3076       }
3077     }
3078
3079     if (Username && Len > 0) {
3080       Result.append(Username, Username + Len);
3081       return;
3082     }
3083   }
3084
3085 // Fallback to user id.
3086 #ifdef LLVM_ON_UNIX
3087   std::string UID = llvm::utostr(getuid());
3088 #else
3089   // FIXME: Windows seems to have an 'SID' that might work.
3090   std::string UID = "9999";
3091 #endif
3092   Result.append(UID.begin(), UID.end());
3093 }
3094
3095 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3096                                           const llvm::Triple &Triple,
3097                                           const llvm::opt::ArgList &Args,
3098                                           bool IsWindowsMSVC) {
3099   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3100                    IsWindowsMSVC) ||
3101       Args.hasArg(options::OPT_fmsc_version) ||
3102       Args.hasArg(options::OPT_fms_compatibility_version)) {
3103     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3104     const Arg *MSCompatibilityVersion =
3105         Args.getLastArg(options::OPT_fms_compatibility_version);
3106
3107     if (MSCVersion && MSCompatibilityVersion) {
3108       if (D)
3109         D->Diag(diag::err_drv_argument_not_allowed_with)
3110             << MSCVersion->getAsString(Args)
3111             << MSCompatibilityVersion->getAsString(Args);
3112       return VersionTuple();
3113     }
3114
3115     if (MSCompatibilityVersion) {
3116       VersionTuple MSVT;
3117       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3118         D->Diag(diag::err_drv_invalid_value)
3119             << MSCompatibilityVersion->getAsString(Args)
3120             << MSCompatibilityVersion->getValue();
3121       return MSVT;
3122     }
3123
3124     if (MSCVersion) {
3125       unsigned Version = 0;
3126       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3127         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3128                                              << MSCVersion->getValue();
3129       return getMSCompatibilityVersion(Version);
3130     }
3131
3132     unsigned Major, Minor, Micro;
3133     Triple.getEnvironmentVersion(Major, Minor, Micro);
3134     if (Major || Minor || Micro)
3135       return VersionTuple(Major, Minor, Micro);
3136
3137     return VersionTuple(18);
3138   }
3139   return VersionTuple();
3140 }
3141
3142 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3143                                    const InputInfo &Output, const ArgList &Args,
3144                                    ArgStringList &CmdArgs) {
3145   auto *ProfileGenerateArg = Args.getLastArg(
3146       options::OPT_fprofile_instr_generate,
3147       options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3148       options::OPT_fprofile_generate_EQ,
3149       options::OPT_fno_profile_instr_generate);
3150   if (ProfileGenerateArg &&
3151       ProfileGenerateArg->getOption().matches(
3152           options::OPT_fno_profile_instr_generate))
3153     ProfileGenerateArg = nullptr;
3154
3155   auto *ProfileUseArg = Args.getLastArg(
3156       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3157       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3158       options::OPT_fno_profile_instr_use);
3159   if (ProfileUseArg &&
3160       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3161     ProfileUseArg = nullptr;
3162
3163   if (ProfileGenerateArg && ProfileUseArg)
3164     D.Diag(diag::err_drv_argument_not_allowed_with)
3165         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3166
3167   if (ProfileGenerateArg) {
3168     if (ProfileGenerateArg->getOption().matches(
3169             options::OPT_fprofile_instr_generate_EQ))
3170       ProfileGenerateArg->render(Args, CmdArgs);
3171     else if (ProfileGenerateArg->getOption().matches(
3172                  options::OPT_fprofile_generate_EQ)) {
3173       SmallString<128> Path(ProfileGenerateArg->getValue());
3174       llvm::sys::path::append(Path, "default.profraw");
3175       CmdArgs.push_back(
3176           Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3177     } else
3178       Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3179   }
3180
3181   if (ProfileUseArg) {
3182     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3183       ProfileUseArg->render(Args, CmdArgs);
3184     else if ((ProfileUseArg->getOption().matches(
3185                   options::OPT_fprofile_use_EQ) ||
3186               ProfileUseArg->getOption().matches(
3187                   options::OPT_fprofile_instr_use))) {
3188       SmallString<128> Path(
3189           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3190       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3191         llvm::sys::path::append(Path, "default.profdata");
3192       CmdArgs.push_back(
3193           Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3194     }
3195   }
3196
3197   if (Args.hasArg(options::OPT_ftest_coverage) ||
3198       Args.hasArg(options::OPT_coverage))
3199     CmdArgs.push_back("-femit-coverage-notes");
3200   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3201                    false) ||
3202       Args.hasArg(options::OPT_coverage))
3203     CmdArgs.push_back("-femit-coverage-data");
3204
3205   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3206                    options::OPT_fno_coverage_mapping, false) &&
3207       !ProfileGenerateArg)
3208     D.Diag(diag::err_drv_argument_only_allowed_with)
3209         << "-fcoverage-mapping"
3210         << "-fprofile-instr-generate";
3211
3212   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3213                    options::OPT_fno_coverage_mapping, false))
3214     CmdArgs.push_back("-fcoverage-mapping");
3215
3216   if (C.getArgs().hasArg(options::OPT_c) ||
3217       C.getArgs().hasArg(options::OPT_S)) {
3218     if (Output.isFilename()) {
3219       CmdArgs.push_back("-coverage-file");
3220       SmallString<128> CoverageFilename;
3221       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3222         CoverageFilename = FinalOutput->getValue();
3223       } else {
3224         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3225       }
3226       if (llvm::sys::path::is_relative(CoverageFilename)) {
3227         SmallString<128> Pwd;
3228         if (!llvm::sys::fs::current_path(Pwd)) {
3229           llvm::sys::path::append(Pwd, CoverageFilename);
3230           CoverageFilename.swap(Pwd);
3231         }
3232       }
3233       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3234     }
3235   }
3236 }
3237
3238 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3239                                 ArgStringList &CmdArgs) {
3240   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3241                     false) ||
3242        Args.hasFlag(options::OPT_fprofile_generate,
3243                     options::OPT_fno_profile_instr_generate, false) ||
3244        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3245                     options::OPT_fno_profile_instr_generate, false) ||
3246        Args.hasFlag(options::OPT_fprofile_instr_generate,
3247                     options::OPT_fno_profile_instr_generate, false) ||
3248        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3249                     options::OPT_fno_profile_instr_generate, false) ||
3250        Args.hasArg(options::OPT_fcreate_profile) ||
3251        Args.hasArg(options::OPT_coverage)))
3252     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3253 }
3254
3255 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3256 /// smooshes them together with platform defaults, to decide whether
3257 /// this compile should be using PIC mode or not. Returns a tuple of
3258 /// (RelocationModel, PICLevel, IsPIE).
3259 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3260 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3261              const ArgList &Args) {
3262   // FIXME: why does this code...and so much everywhere else, use both
3263   // ToolChain.getTriple() and Triple?
3264   bool PIE = ToolChain.isPIEDefault();
3265   bool PIC = PIE || ToolChain.isPICDefault();
3266   // The Darwin/MachO default to use PIC does not apply when using -static.
3267   if (ToolChain.getTriple().isOSBinFormatMachO() &&
3268       Args.hasArg(options::OPT_static))
3269     PIE = PIC = false;
3270   bool IsPICLevelTwo = PIC;
3271
3272   bool KernelOrKext =
3273       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3274
3275   // Android-specific defaults for PIC/PIE
3276   if (ToolChain.getTriple().isAndroid()) {
3277     switch (ToolChain.getArch()) {
3278     case llvm::Triple::arm:
3279     case llvm::Triple::armeb:
3280     case llvm::Triple::thumb:
3281     case llvm::Triple::thumbeb:
3282     case llvm::Triple::aarch64:
3283     case llvm::Triple::mips:
3284     case llvm::Triple::mipsel:
3285     case llvm::Triple::mips64:
3286     case llvm::Triple::mips64el:
3287       PIC = true; // "-fpic"
3288       break;
3289
3290     case llvm::Triple::x86:
3291     case llvm::Triple::x86_64:
3292       PIC = true; // "-fPIC"
3293       IsPICLevelTwo = true;
3294       break;
3295
3296     default:
3297       break;
3298     }
3299   }
3300
3301   // OpenBSD-specific defaults for PIE
3302   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3303     switch (ToolChain.getArch()) {
3304     case llvm::Triple::mips64:
3305     case llvm::Triple::mips64el:
3306     case llvm::Triple::sparcel:
3307     case llvm::Triple::x86:
3308     case llvm::Triple::x86_64:
3309       IsPICLevelTwo = false; // "-fpie"
3310       break;
3311
3312     case llvm::Triple::ppc:
3313     case llvm::Triple::sparc:
3314     case llvm::Triple::sparcv9:
3315       IsPICLevelTwo = true; // "-fPIE"
3316       break;
3317
3318     default:
3319       break;
3320     }
3321   }
3322
3323   // The last argument relating to either PIC or PIE wins, and no
3324   // other argument is used. If the last argument is any flavor of the
3325   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3326   // option implicitly enables PIC at the same level.
3327   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3328                                     options::OPT_fpic, options::OPT_fno_pic,
3329                                     options::OPT_fPIE, options::OPT_fno_PIE,
3330                                     options::OPT_fpie, options::OPT_fno_pie);
3331   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3332   // is forced, then neither PIC nor PIE flags will have no effect.
3333   if (!ToolChain.isPICDefaultForced()) {
3334     if (LastPICArg) {
3335       Option O = LastPICArg->getOption();
3336       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3337           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3338         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3339         PIC =
3340             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3341         IsPICLevelTwo =
3342             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3343       } else {
3344         PIE = PIC = false;
3345         if (Triple.isPS4CPU()) {
3346           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3347           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3348           if (Model != "kernel") {
3349             PIC = true;
3350             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3351                 << LastPICArg->getSpelling();
3352           }
3353         }
3354       }
3355     }
3356   }
3357
3358   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3359   // PIC level would've been set to level 1, force it back to level 2 PIC
3360   // instead.
3361   if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3362     IsPICLevelTwo |= ToolChain.isPICDefault();
3363
3364   // This kernel flags are a trump-card: they will disable PIC/PIE
3365   // generation, independent of the argument order.
3366   if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3367                        !Triple.isWatchOS()))
3368     PIC = PIE = false;
3369
3370   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3371     // This is a very special mode. It trumps the other modes, almost no one
3372     // uses it, and it isn't even valid on any OS but Darwin.
3373     if (!ToolChain.getTriple().isOSDarwin())
3374       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3375           << A->getSpelling() << ToolChain.getTriple().str();
3376
3377     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3378
3379     // Only a forced PIC mode can cause the actual compile to have PIC defines
3380     // etc., no flags are sufficient. This behavior was selected to closely
3381     // match that of llvm-gcc and Apple GCC before that.
3382     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3383
3384     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3385   }
3386
3387   if (PIC)
3388     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3389
3390   return std::make_tuple(llvm::Reloc::Static, 0, false);
3391 }
3392
3393 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3394   switch (Model) {
3395   case llvm::Reloc::Default:
3396     return nullptr;
3397   case llvm::Reloc::Static:
3398     return "static";
3399   case llvm::Reloc::PIC_:
3400     return "pic";
3401   case llvm::Reloc::DynamicNoPIC:
3402     return "dynamic-no-pic";
3403   }
3404   llvm_unreachable("Unknown Reloc::Model kind");
3405 }
3406
3407 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3408                              ArgStringList &CmdArgs) {
3409   llvm::Reloc::Model RelocationModel;
3410   unsigned PICLevel;
3411   bool IsPIE;
3412   std::tie(RelocationModel, PICLevel, IsPIE) =
3413       ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3414
3415   if (RelocationModel != llvm::Reloc::Static)
3416     CmdArgs.push_back("-KPIC");
3417 }
3418
3419 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3420                          const InputInfo &Output, const InputInfoList &Inputs,
3421                          const ArgList &Args, const char *LinkingOutput) const {
3422   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3423   const llvm::Triple Triple(TripleStr);
3424
3425   bool KernelOrKext =
3426       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3427   const Driver &D = getToolChain().getDriver();
3428   ArgStringList CmdArgs;
3429
3430   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3431   bool IsWindowsCygnus =
3432       getToolChain().getTriple().isWindowsCygwinEnvironment();
3433   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3434   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3435
3436   // Check number of inputs for sanity. We need at least one input.
3437   assert(Inputs.size() >= 1 && "Must have at least one input.");
3438   const InputInfo &Input = Inputs[0];
3439   // CUDA compilation may have multiple inputs (source file + results of
3440   // device-side compilations). All other jobs are expected to have exactly one
3441   // input.
3442   bool IsCuda = types::isCuda(Input.getType());
3443   assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3444
3445   // Invoke ourselves in -cc1 mode.
3446   //
3447   // FIXME: Implement custom jobs for internal actions.
3448   CmdArgs.push_back("-cc1");
3449
3450   // Add the "effective" target triple.
3451   CmdArgs.push_back("-triple");
3452   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3453
3454   const ToolChain *AuxToolChain = nullptr;
3455   if (IsCuda) {
3456     // FIXME: We need a (better) way to pass information about
3457     // particular compilation pass we're constructing here. For now we
3458     // can check which toolchain we're using and pick the other one to
3459     // extract the triple.
3460     if (&getToolChain() == C.getCudaDeviceToolChain())
3461       AuxToolChain = C.getCudaHostToolChain();
3462     else if (&getToolChain() == C.getCudaHostToolChain())
3463       AuxToolChain = C.getCudaDeviceToolChain();
3464     else
3465       llvm_unreachable("Can't figure out CUDA compilation mode.");
3466     assert(AuxToolChain != nullptr && "No aux toolchain.");
3467     CmdArgs.push_back("-aux-triple");
3468     CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3469     CmdArgs.push_back("-fcuda-target-overloads");
3470     CmdArgs.push_back("-fcuda-disable-target-call-checks");
3471   }
3472
3473   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3474                                Triple.getArch() == llvm::Triple::thumb)) {
3475     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3476     unsigned Version;
3477     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3478     if (Version < 7)
3479       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3480                                                 << TripleStr;
3481   }
3482
3483   // Push all default warning arguments that are specific to
3484   // the given target.  These come before user provided warning options
3485   // are provided.
3486   getToolChain().addClangWarningOptions(CmdArgs);
3487
3488   // Select the appropriate action.
3489   RewriteKind rewriteKind = RK_None;
3490
3491   if (isa<AnalyzeJobAction>(JA)) {
3492     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3493     CmdArgs.push_back("-analyze");
3494   } else if (isa<MigrateJobAction>(JA)) {
3495     CmdArgs.push_back("-migrate");
3496   } else if (isa<PreprocessJobAction>(JA)) {
3497     if (Output.getType() == types::TY_Dependencies)
3498       CmdArgs.push_back("-Eonly");
3499     else {
3500       CmdArgs.push_back("-E");
3501       if (Args.hasArg(options::OPT_rewrite_objc) &&
3502           !Args.hasArg(options::OPT_g_Group))
3503         CmdArgs.push_back("-P");
3504     }
3505   } else if (isa<AssembleJobAction>(JA)) {
3506     CmdArgs.push_back("-emit-obj");
3507
3508     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3509
3510     // Also ignore explicit -force_cpusubtype_ALL option.
3511     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3512   } else if (isa<PrecompileJobAction>(JA)) {
3513     // Use PCH if the user requested it.
3514     bool UsePCH = D.CCCUsePCH;
3515
3516     if (JA.getType() == types::TY_Nothing)
3517       CmdArgs.push_back("-fsyntax-only");
3518     else if (UsePCH)
3519       CmdArgs.push_back("-emit-pch");
3520     else
3521       CmdArgs.push_back("-emit-pth");
3522   } else if (isa<VerifyPCHJobAction>(JA)) {
3523     CmdArgs.push_back("-verify-pch");
3524   } else {
3525     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3526            "Invalid action for clang tool.");
3527     if (JA.getType() == types::TY_Nothing) {
3528       CmdArgs.push_back("-fsyntax-only");
3529     } else if (JA.getType() == types::TY_LLVM_IR ||
3530                JA.getType() == types::TY_LTO_IR) {
3531       CmdArgs.push_back("-emit-llvm");
3532     } else if (JA.getType() == types::TY_LLVM_BC ||
3533                JA.getType() == types::TY_LTO_BC) {
3534       CmdArgs.push_back("-emit-llvm-bc");
3535     } else if (JA.getType() == types::TY_PP_Asm) {
3536       CmdArgs.push_back("-S");
3537     } else if (JA.getType() == types::TY_AST) {
3538       CmdArgs.push_back("-emit-pch");
3539     } else if (JA.getType() == types::TY_ModuleFile) {
3540       CmdArgs.push_back("-module-file-info");
3541     } else if (JA.getType() == types::TY_RewrittenObjC) {
3542       CmdArgs.push_back("-rewrite-objc");
3543       rewriteKind = RK_NonFragile;
3544     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3545       CmdArgs.push_back("-rewrite-objc");
3546       rewriteKind = RK_Fragile;
3547     } else {
3548       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3549     }
3550
3551     // Preserve use-list order by default when emitting bitcode, so that
3552     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3553     // same result as running passes here.  For LTO, we don't need to preserve
3554     // the use-list order, since serialization to bitcode is part of the flow.
3555     if (JA.getType() == types::TY_LLVM_BC)
3556       CmdArgs.push_back("-emit-llvm-uselists");
3557
3558     if (D.isUsingLTO())
3559       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3560   }
3561
3562   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3563     if (!types::isLLVMIR(Input.getType()))
3564       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3565                                                        << "-x ir";
3566     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3567   }
3568
3569   // We normally speed up the clang process a bit by skipping destructors at
3570   // exit, but when we're generating diagnostics we can rely on some of the
3571   // cleanup.
3572   if (!C.isForDiagnostics())
3573     CmdArgs.push_back("-disable-free");
3574
3575 // Disable the verification pass in -asserts builds.
3576 #ifdef NDEBUG
3577   CmdArgs.push_back("-disable-llvm-verifier");
3578 #endif
3579
3580   // Set the main file name, so that debug info works even with
3581   // -save-temps.
3582   CmdArgs.push_back("-main-file-name");
3583   CmdArgs.push_back(getBaseInputName(Args, Input));
3584
3585   // Some flags which affect the language (via preprocessor
3586   // defines).
3587   if (Args.hasArg(options::OPT_static))
3588     CmdArgs.push_back("-static-define");
3589
3590   if (isa<AnalyzeJobAction>(JA)) {
3591     // Enable region store model by default.
3592     CmdArgs.push_back("-analyzer-store=region");
3593
3594     // Treat blocks as analysis entry points.
3595     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3596
3597     CmdArgs.push_back("-analyzer-eagerly-assume");
3598
3599     // Add default argument set.
3600     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3601       CmdArgs.push_back("-analyzer-checker=core");
3602
3603       if (!IsWindowsMSVC)
3604         CmdArgs.push_back("-analyzer-checker=unix");
3605
3606       // Disable some unix checkers for PS4.
3607       if (IsPS4CPU) {
3608         CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3609         CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3610       }
3611
3612       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3613         CmdArgs.push_back("-analyzer-checker=osx");
3614
3615       CmdArgs.push_back("-analyzer-checker=deadcode");
3616
3617       if (types::isCXX(Input.getType()))
3618         CmdArgs.push_back("-analyzer-checker=cplusplus");
3619
3620       if (!IsPS4CPU) {
3621         CmdArgs.push_back(
3622             "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3623         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3624         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3625         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3626         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3627         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3628       }
3629
3630       // Default nullability checks.
3631       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3632       CmdArgs.push_back(
3633           "-analyzer-checker=nullability.NullReturnedFromNonnull");
3634     }
3635
3636     // Set the output format. The default is plist, for (lame) historical
3637     // reasons.
3638     CmdArgs.push_back("-analyzer-output");
3639     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3640       CmdArgs.push_back(A->getValue());
3641     else
3642       CmdArgs.push_back("plist");
3643
3644     // Disable the presentation of standard compiler warnings when
3645     // using --analyze.  We only want to show static analyzer diagnostics
3646     // or frontend errors.
3647     CmdArgs.push_back("-w");
3648
3649     // Add -Xanalyzer arguments when running as analyzer.
3650     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3651   }
3652
3653   CheckCodeGenerationOptions(D, Args);
3654
3655   llvm::Reloc::Model RelocationModel;
3656   unsigned PICLevel;
3657   bool IsPIE;
3658   std::tie(RelocationModel, PICLevel, IsPIE) =
3659       ParsePICArgs(getToolChain(), Triple, Args);
3660
3661   const char *RMName = RelocationModelName(RelocationModel);
3662   if (RMName) {
3663     CmdArgs.push_back("-mrelocation-model");
3664     CmdArgs.push_back(RMName);
3665   }
3666   if (PICLevel > 0) {
3667     CmdArgs.push_back("-pic-level");
3668     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3669     if (IsPIE) {
3670       CmdArgs.push_back("-pie-level");
3671       CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3672     }
3673   }
3674
3675   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3676     CmdArgs.push_back("-meabi");
3677     CmdArgs.push_back(A->getValue());
3678   }
3679
3680   CmdArgs.push_back("-mthread-model");
3681   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3682     CmdArgs.push_back(A->getValue());
3683   else
3684     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3685
3686   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3687
3688   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3689                     options::OPT_fno_merge_all_constants))
3690     CmdArgs.push_back("-fno-merge-all-constants");
3691
3692   // LLVM Code Generator Options.
3693
3694   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3695       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3696     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3697                                       options::OPT_frewrite_map_file_EQ)) {
3698       CmdArgs.push_back("-frewrite-map-file");
3699       CmdArgs.push_back(A->getValue());
3700       A->claim();
3701     }
3702   }
3703
3704   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3705     StringRef v = A->getValue();
3706     CmdArgs.push_back("-mllvm");
3707     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3708     A->claim();
3709   }
3710
3711   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3712     CmdArgs.push_back("-mregparm");
3713     CmdArgs.push_back(A->getValue());
3714   }
3715
3716   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3717                                options::OPT_freg_struct_return)) {
3718     if (getToolChain().getArch() != llvm::Triple::x86) {
3719       D.Diag(diag::err_drv_unsupported_opt_for_target)
3720           << A->getSpelling() << getToolChain().getTriple().str();
3721     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3722       CmdArgs.push_back("-fpcc-struct-return");
3723     } else {
3724       assert(A->getOption().matches(options::OPT_freg_struct_return));
3725       CmdArgs.push_back("-freg-struct-return");
3726     }
3727   }
3728
3729   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3730     CmdArgs.push_back("-mrtd");
3731
3732   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3733     CmdArgs.push_back("-mdisable-fp-elim");
3734   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3735                     options::OPT_fno_zero_initialized_in_bss))
3736     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3737
3738   bool OFastEnabled = isOptimizationLevelFast(Args);
3739   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3740   // enabled.  This alias option is being used to simplify the hasFlag logic.
3741   OptSpecifier StrictAliasingAliasOption =
3742       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3743   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3744   // doesn't do any TBAA.
3745   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3746   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3747                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3748     CmdArgs.push_back("-relaxed-aliasing");
3749   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3750                     options::OPT_fno_struct_path_tbaa))
3751     CmdArgs.push_back("-no-struct-path-tbaa");
3752   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3753                    false))
3754     CmdArgs.push_back("-fstrict-enums");
3755   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3756                    options::OPT_fno_strict_vtable_pointers,
3757                    false))
3758     CmdArgs.push_back("-fstrict-vtable-pointers");
3759   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3760                     options::OPT_fno_optimize_sibling_calls))
3761     CmdArgs.push_back("-mdisable-tail-calls");
3762
3763   // Handle segmented stacks.
3764   if (Args.hasArg(options::OPT_fsplit_stack))
3765     CmdArgs.push_back("-split-stacks");
3766
3767   // If -Ofast is the optimization level, then -ffast-math should be enabled.
3768   // This alias option is being used to simplify the getLastArg logic.
3769   OptSpecifier FastMathAliasOption =
3770       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3771
3772   // Handle various floating point optimization flags, mapping them to the
3773   // appropriate LLVM code generation flags. The pattern for all of these is to
3774   // default off the codegen optimizations, and if any flag enables them and no
3775   // flag disables them after the flag enabling them, enable the codegen
3776   // optimization. This is complicated by several "umbrella" flags.
3777   if (Arg *A = Args.getLastArg(
3778           options::OPT_ffast_math, FastMathAliasOption,
3779           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3780           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3781           options::OPT_fno_honor_infinities))
3782     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3783         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3784         A->getOption().getID() != options::OPT_fhonor_infinities)
3785       CmdArgs.push_back("-menable-no-infs");
3786   if (Arg *A = Args.getLastArg(
3787           options::OPT_ffast_math, FastMathAliasOption,
3788           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3789           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3790           options::OPT_fno_honor_nans))
3791     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3792         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3793         A->getOption().getID() != options::OPT_fhonor_nans)
3794       CmdArgs.push_back("-menable-no-nans");
3795
3796   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3797   bool MathErrno = getToolChain().IsMathErrnoDefault();
3798   if (Arg *A =
3799           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3800                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
3801                           options::OPT_fno_math_errno)) {
3802     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3803     // However, turning *off* -ffast_math merely restores the toolchain default
3804     // (which may be false).
3805     if (A->getOption().getID() == options::OPT_fno_math_errno ||
3806         A->getOption().getID() == options::OPT_ffast_math ||
3807         A->getOption().getID() == options::OPT_Ofast)
3808       MathErrno = false;
3809     else if (A->getOption().getID() == options::OPT_fmath_errno)
3810       MathErrno = true;
3811   }
3812   if (MathErrno)
3813     CmdArgs.push_back("-fmath-errno");
3814
3815   // There are several flags which require disabling very specific
3816   // optimizations. Any of these being disabled forces us to turn off the
3817   // entire set of LLVM optimizations, so collect them through all the flag
3818   // madness.
3819   bool AssociativeMath = false;
3820   if (Arg *A = Args.getLastArg(
3821           options::OPT_ffast_math, FastMathAliasOption,
3822           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3823           options::OPT_fno_unsafe_math_optimizations,
3824           options::OPT_fassociative_math, options::OPT_fno_associative_math))
3825     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3826         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3827         A->getOption().getID() != options::OPT_fno_associative_math)
3828       AssociativeMath = true;
3829   bool ReciprocalMath = false;
3830   if (Arg *A = Args.getLastArg(
3831           options::OPT_ffast_math, FastMathAliasOption,
3832           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3833           options::OPT_fno_unsafe_math_optimizations,
3834           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3835     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3836         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3837         A->getOption().getID() != options::OPT_fno_reciprocal_math)
3838       ReciprocalMath = true;
3839   bool SignedZeros = true;
3840   if (Arg *A = Args.getLastArg(
3841           options::OPT_ffast_math, FastMathAliasOption,
3842           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3843           options::OPT_fno_unsafe_math_optimizations,
3844           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3845     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3846         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3847         A->getOption().getID() != options::OPT_fsigned_zeros)
3848       SignedZeros = false;
3849   bool TrappingMath = true;
3850   if (Arg *A = Args.getLastArg(
3851           options::OPT_ffast_math, FastMathAliasOption,
3852           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3853           options::OPT_fno_unsafe_math_optimizations,
3854           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3855     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3856         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3857         A->getOption().getID() != options::OPT_ftrapping_math)
3858       TrappingMath = false;
3859   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3860       !TrappingMath)
3861     CmdArgs.push_back("-menable-unsafe-fp-math");
3862
3863   if (!SignedZeros)
3864     CmdArgs.push_back("-fno-signed-zeros");
3865
3866   if (ReciprocalMath)
3867     CmdArgs.push_back("-freciprocal-math");
3868
3869   // Validate and pass through -fp-contract option.
3870   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3871                                options::OPT_fno_fast_math,
3872                                options::OPT_ffp_contract)) {
3873     if (A->getOption().getID() == options::OPT_ffp_contract) {
3874       StringRef Val = A->getValue();
3875       if (Val == "fast" || Val == "on" || Val == "off") {
3876         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3877       } else {
3878         D.Diag(diag::err_drv_unsupported_option_argument)
3879             << A->getOption().getName() << Val;
3880       }
3881     } else if (A->getOption().matches(options::OPT_ffast_math) ||
3882                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3883       // If fast-math is set then set the fp-contract mode to fast.
3884       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3885     }
3886   }
3887
3888   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3889
3890   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3891   // and if we find them, tell the frontend to provide the appropriate
3892   // preprocessor macros. This is distinct from enabling any optimizations as
3893   // these options induce language changes which must survive serialization
3894   // and deserialization, etc.
3895   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3896                                options::OPT_fno_fast_math))
3897     if (!A->getOption().matches(options::OPT_fno_fast_math))
3898       CmdArgs.push_back("-ffast-math");
3899   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3900                                options::OPT_fno_fast_math))
3901     if (A->getOption().matches(options::OPT_ffinite_math_only))
3902       CmdArgs.push_back("-ffinite-math-only");
3903
3904   // Decide whether to use verbose asm. Verbose assembly is the default on
3905   // toolchains which have the integrated assembler on by default.
3906   bool IsIntegratedAssemblerDefault =
3907       getToolChain().IsIntegratedAssemblerDefault();
3908   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3909                    IsIntegratedAssemblerDefault) ||
3910       Args.hasArg(options::OPT_dA))
3911     CmdArgs.push_back("-masm-verbose");
3912
3913   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3914                     IsIntegratedAssemblerDefault))
3915     CmdArgs.push_back("-no-integrated-as");
3916
3917   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3918     CmdArgs.push_back("-mdebug-pass");
3919     CmdArgs.push_back("Structure");
3920   }
3921   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3922     CmdArgs.push_back("-mdebug-pass");
3923     CmdArgs.push_back("Arguments");
3924   }
3925
3926   // Enable -mconstructor-aliases except on darwin, where we have to
3927   // work around a linker bug;  see <rdar://problem/7651567>.
3928   if (!getToolChain().getTriple().isOSDarwin())
3929     CmdArgs.push_back("-mconstructor-aliases");
3930
3931   // Darwin's kernel doesn't support guard variables; just die if we
3932   // try to use them.
3933   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3934     CmdArgs.push_back("-fforbid-guard-variables");
3935
3936   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3937                    false)) {
3938     CmdArgs.push_back("-mms-bitfields");
3939   }
3940
3941   // This is a coarse approximation of what llvm-gcc actually does, both
3942   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3943   // complicated ways.
3944   bool AsynchronousUnwindTables =
3945       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3946                    options::OPT_fno_asynchronous_unwind_tables,
3947                    (getToolChain().IsUnwindTablesDefault() ||
3948                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3949                        !KernelOrKext);
3950   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3951                    AsynchronousUnwindTables))
3952     CmdArgs.push_back("-munwind-tables");
3953
3954   getToolChain().addClangTargetOptions(Args, CmdArgs);
3955
3956   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3957     CmdArgs.push_back("-mlimit-float-precision");
3958     CmdArgs.push_back(A->getValue());
3959   }
3960
3961   // FIXME: Handle -mtune=.
3962   (void)Args.hasArg(options::OPT_mtune_EQ);
3963
3964   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3965     CmdArgs.push_back("-mcode-model");
3966     CmdArgs.push_back(A->getValue());
3967   }
3968
3969   // Add the target cpu
3970   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3971   if (!CPU.empty()) {
3972     CmdArgs.push_back("-target-cpu");
3973     CmdArgs.push_back(Args.MakeArgString(CPU));
3974   }
3975
3976   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3977     CmdArgs.push_back("-mfpmath");
3978     CmdArgs.push_back(A->getValue());
3979   }
3980
3981   // Add the target features
3982   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3983
3984   // Add target specific flags.
3985   switch (getToolChain().getArch()) {
3986   default:
3987     break;
3988
3989   case llvm::Triple::arm:
3990   case llvm::Triple::armeb:
3991   case llvm::Triple::thumb:
3992   case llvm::Triple::thumbeb:
3993     // Use the effective triple, which takes into account the deployment target.
3994     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3995     break;
3996
3997   case llvm::Triple::aarch64:
3998   case llvm::Triple::aarch64_be:
3999     AddAArch64TargetArgs(Args, CmdArgs);
4000     break;
4001
4002   case llvm::Triple::mips:
4003   case llvm::Triple::mipsel:
4004   case llvm::Triple::mips64:
4005   case llvm::Triple::mips64el:
4006     AddMIPSTargetArgs(Args, CmdArgs);
4007     break;
4008
4009   case llvm::Triple::ppc:
4010   case llvm::Triple::ppc64:
4011   case llvm::Triple::ppc64le:
4012     AddPPCTargetArgs(Args, CmdArgs);
4013     break;
4014
4015   case llvm::Triple::sparc:
4016   case llvm::Triple::sparcel:
4017   case llvm::Triple::sparcv9:
4018     AddSparcTargetArgs(Args, CmdArgs);
4019     break;
4020
4021   case llvm::Triple::x86:
4022   case llvm::Triple::x86_64:
4023     AddX86TargetArgs(Args, CmdArgs);
4024     break;
4025
4026   case llvm::Triple::hexagon:
4027     AddHexagonTargetArgs(Args, CmdArgs);
4028     break;
4029
4030   case llvm::Triple::wasm32:
4031   case llvm::Triple::wasm64:
4032     AddWebAssemblyTargetArgs(Args, CmdArgs);
4033     break;
4034   }
4035
4036   // The 'g' groups options involve a somewhat intricate sequence of decisions
4037   // about what to pass from the driver to the frontend, but by the time they
4038   // reach cc1 they've been factored into three well-defined orthogonal choices:
4039   //  * what level of debug info to generate
4040   //  * what dwarf version to write
4041   //  * what debugger tuning to use
4042   // This avoids having to monkey around further in cc1 other than to disable
4043   // codeview if not running in a Windows environment. Perhaps even that
4044   // decision should be made in the driver as well though.
4045   unsigned DwarfVersion = 0;
4046   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4047   // These two are potentially updated by AddClangCLArgs.
4048   enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4049       CodeGenOptions::NoDebugInfo;
4050   bool EmitCodeView = false;
4051
4052   // Add clang-cl arguments.
4053   if (getToolChain().getDriver().IsCLMode())
4054     AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4055
4056   // Pass the linker version in use.
4057   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4058     CmdArgs.push_back("-target-linker-version");
4059     CmdArgs.push_back(A->getValue());
4060   }
4061
4062   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4063     CmdArgs.push_back("-momit-leaf-frame-pointer");
4064
4065   // Explicitly error on some things we know we don't support and can't just
4066   // ignore.
4067   types::ID InputType = Input.getType();
4068   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4069     Arg *Unsupported;
4070     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4071         getToolChain().getArch() == llvm::Triple::x86) {
4072       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4073           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4074         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4075             << Unsupported->getOption().getName();
4076     }
4077   }
4078
4079   Args.AddAllArgs(CmdArgs, options::OPT_v);
4080   Args.AddLastArg(CmdArgs, options::OPT_H);
4081   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4082     CmdArgs.push_back("-header-include-file");
4083     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4084                                                : "-");
4085   }
4086   Args.AddLastArg(CmdArgs, options::OPT_P);
4087   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4088
4089   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4090     CmdArgs.push_back("-diagnostic-log-file");
4091     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4092                                                  : "-");
4093   }
4094
4095   Args.ClaimAllArgs(options::OPT_g_Group);
4096   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4097   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4098     // If the last option explicitly specified a debug-info level, use it.
4099     if (A->getOption().matches(options::OPT_gN_Group)) {
4100       DebugInfoKind = DebugLevelToInfoKind(*A);
4101       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4102       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4103       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4104       if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4105           A->getIndex() > SplitDwarfArg->getIndex())
4106         SplitDwarfArg = nullptr;
4107     } else
4108       // For any other 'g' option, use Limited.
4109       DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4110   }
4111
4112   // If a debugger tuning argument appeared, remember it.
4113   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4114                                options::OPT_ggdbN_Group)) {
4115     if (A->getOption().matches(options::OPT_glldb))
4116       DebuggerTuning = llvm::DebuggerKind::LLDB;
4117     else if (A->getOption().matches(options::OPT_gsce))
4118       DebuggerTuning = llvm::DebuggerKind::SCE;
4119     else
4120       DebuggerTuning = llvm::DebuggerKind::GDB;
4121   }
4122
4123   // If a -gdwarf argument appeared, remember it.
4124   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4125                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4126     DwarfVersion = DwarfVersionNum(A->getSpelling());
4127
4128   // Forward -gcodeview.
4129   // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4130   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4131     // DwarfVersion remains at 0 if no explicit choice was made.
4132     CmdArgs.push_back("-gcodeview");
4133   } else if (DwarfVersion == 0 &&
4134              DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4135     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4136   }
4137
4138   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4139   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4140
4141   // PS4 defaults to no column info
4142   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4143                    /*Default=*/ !IsPS4CPU))
4144     CmdArgs.push_back("-dwarf-column-info");
4145
4146   // FIXME: Move backend command line options to the module.
4147   if (Args.hasArg(options::OPT_gmodules)) {
4148     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4149     CmdArgs.push_back("-dwarf-ext-refs");
4150     CmdArgs.push_back("-fmodule-format=obj");
4151   }
4152
4153   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4154   // splitting and extraction.
4155   // FIXME: Currently only works on Linux.
4156   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4157     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4158     CmdArgs.push_back("-backend-option");
4159     CmdArgs.push_back("-split-dwarf=Enable");
4160   }
4161
4162   // After we've dealt with all combinations of things that could
4163   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4164   // figure out if we need to "upgrade" it to standalone debug info.
4165   // We parse these two '-f' options whether or not they will be used,
4166   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4167   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4168                                     options::OPT_fno_standalone_debug,
4169                                     getToolChain().GetDefaultStandaloneDebug());
4170   if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4171     DebugInfoKind = CodeGenOptions::FullDebugInfo;
4172   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4173                           DebuggerTuning);
4174
4175   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4176   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4177     CmdArgs.push_back("-backend-option");
4178     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4179   }
4180
4181   // -gdwarf-aranges turns on the emission of the aranges section in the
4182   // backend.
4183   // Always enabled on the PS4.
4184   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4185     CmdArgs.push_back("-backend-option");
4186     CmdArgs.push_back("-generate-arange-section");
4187   }
4188
4189   if (Args.hasFlag(options::OPT_fdebug_types_section,
4190                    options::OPT_fno_debug_types_section, false)) {
4191     CmdArgs.push_back("-backend-option");
4192     CmdArgs.push_back("-generate-type-units");
4193   }
4194
4195   // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4196   // default.
4197   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4198                              Triple.getArch() == llvm::Triple::wasm32 ||
4199                              Triple.getArch() == llvm::Triple::wasm64;
4200
4201   if (Args.hasFlag(options::OPT_ffunction_sections,
4202                    options::OPT_fno_function_sections, UseSeparateSections)) {
4203     CmdArgs.push_back("-ffunction-sections");
4204   }
4205
4206   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4207                    UseSeparateSections)) {
4208     CmdArgs.push_back("-fdata-sections");
4209   }
4210
4211   if (!Args.hasFlag(options::OPT_funique_section_names,
4212                     options::OPT_fno_unique_section_names, true))
4213     CmdArgs.push_back("-fno-unique-section-names");
4214
4215   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4216
4217   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4218
4219   // Add runtime flag for PS4 when PGO or Coverage are enabled.
4220   if (getToolChain().getTriple().isPS4CPU())
4221     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4222
4223   // Pass options for controlling the default header search paths.
4224   if (Args.hasArg(options::OPT_nostdinc)) {
4225     CmdArgs.push_back("-nostdsysteminc");
4226     CmdArgs.push_back("-nobuiltininc");
4227   } else {
4228     if (Args.hasArg(options::OPT_nostdlibinc))
4229       CmdArgs.push_back("-nostdsysteminc");
4230     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4231     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4232   }
4233
4234   // Pass the path to compiler resource files.
4235   CmdArgs.push_back("-resource-dir");
4236   CmdArgs.push_back(D.ResourceDir.c_str());
4237
4238   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4239
4240   bool ARCMTEnabled = false;
4241   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4242     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4243                                        options::OPT_ccc_arcmt_modify,
4244                                        options::OPT_ccc_arcmt_migrate)) {
4245       ARCMTEnabled = true;
4246       switch (A->getOption().getID()) {
4247       default:
4248         llvm_unreachable("missed a case");
4249       case options::OPT_ccc_arcmt_check:
4250         CmdArgs.push_back("-arcmt-check");
4251         break;
4252       case options::OPT_ccc_arcmt_modify:
4253         CmdArgs.push_back("-arcmt-modify");
4254         break;
4255       case options::OPT_ccc_arcmt_migrate:
4256         CmdArgs.push_back("-arcmt-migrate");
4257         CmdArgs.push_back("-mt-migrate-directory");
4258         CmdArgs.push_back(A->getValue());
4259
4260         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4261         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4262         break;
4263       }
4264     }
4265   } else {
4266     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4267     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4268     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4269   }
4270
4271   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4272     if (ARCMTEnabled) {
4273       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4274                                                       << "-ccc-arcmt-migrate";
4275     }
4276     CmdArgs.push_back("-mt-migrate-directory");
4277     CmdArgs.push_back(A->getValue());
4278
4279     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4280                      options::OPT_objcmt_migrate_subscripting,
4281                      options::OPT_objcmt_migrate_property)) {
4282       // None specified, means enable them all.
4283       CmdArgs.push_back("-objcmt-migrate-literals");
4284       CmdArgs.push_back("-objcmt-migrate-subscripting");
4285       CmdArgs.push_back("-objcmt-migrate-property");
4286     } else {
4287       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4288       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4289       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4290     }
4291   } else {
4292     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4293     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4294     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4295     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4296     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4297     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4298     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4299     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4300     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4301     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4302     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4303     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4304     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4305     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4306     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4307     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4308   }
4309
4310   // Add preprocessing options like -I, -D, etc. if we are using the
4311   // preprocessor.
4312   //
4313   // FIXME: Support -fpreprocessed
4314   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4315     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4316                             AuxToolChain);
4317
4318   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4319   // that "The compiler can only warn and ignore the option if not recognized".
4320   // When building with ccache, it will pass -D options to clang even on
4321   // preprocessed inputs and configure concludes that -fPIC is not supported.
4322   Args.ClaimAllArgs(options::OPT_D);
4323
4324   // Manually translate -O4 to -O3; let clang reject others.
4325   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4326     if (A->getOption().matches(options::OPT_O4)) {
4327       CmdArgs.push_back("-O3");
4328       D.Diag(diag::warn_O4_is_O3);
4329     } else {
4330       A->render(Args, CmdArgs);
4331     }
4332   }
4333
4334   // Warn about ignored options to clang.
4335   for (const Arg *A :
4336        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4337     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4338     A->claim();
4339   }
4340
4341   claimNoWarnArgs(Args);
4342
4343   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4344   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4345   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4346     CmdArgs.push_back("-pedantic");
4347   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4348   Args.AddLastArg(CmdArgs, options::OPT_w);
4349
4350   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4351   // (-ansi is equivalent to -std=c89 or -std=c++98).
4352   //
4353   // If a std is supplied, only add -trigraphs if it follows the
4354   // option.
4355   bool ImplyVCPPCXXVer = false;
4356   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4357     if (Std->getOption().matches(options::OPT_ansi))
4358       if (types::isCXX(InputType))
4359         CmdArgs.push_back("-std=c++98");
4360       else
4361         CmdArgs.push_back("-std=c89");
4362     else
4363       Std->render(Args, CmdArgs);
4364
4365     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4366     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4367                                  options::OPT_ftrigraphs,
4368                                  options::OPT_fno_trigraphs))
4369       if (A != Std)
4370         A->render(Args, CmdArgs);
4371   } else {
4372     // Honor -std-default.
4373     //
4374     // FIXME: Clang doesn't correctly handle -std= when the input language
4375     // doesn't match. For the time being just ignore this for C++ inputs;
4376     // eventually we want to do all the standard defaulting here instead of
4377     // splitting it between the driver and clang -cc1.
4378     if (!types::isCXX(InputType))
4379       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4380                                 /*Joined=*/true);
4381     else if (IsWindowsMSVC)
4382       ImplyVCPPCXXVer = true;
4383
4384     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4385                     options::OPT_fno_trigraphs);
4386   }
4387
4388   // GCC's behavior for -Wwrite-strings is a bit strange:
4389   //  * In C, this "warning flag" changes the types of string literals from
4390   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4391   //    for the discarded qualifier.
4392   //  * In C++, this is just a normal warning flag.
4393   //
4394   // Implementing this warning correctly in C is hard, so we follow GCC's
4395   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4396   // a non-const char* in C, rather than using this crude hack.
4397   if (!types::isCXX(InputType)) {
4398     // FIXME: This should behave just like a warning flag, and thus should also
4399     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4400     Arg *WriteStrings =
4401         Args.getLastArg(options::OPT_Wwrite_strings,
4402                         options::OPT_Wno_write_strings, options::OPT_w);
4403     if (WriteStrings &&
4404         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4405       CmdArgs.push_back("-fconst-strings");
4406   }
4407
4408   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4409   // during C++ compilation, which it is by default. GCC keeps this define even
4410   // in the presence of '-w', match this behavior bug-for-bug.
4411   if (types::isCXX(InputType) &&
4412       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4413                    true)) {
4414     CmdArgs.push_back("-fdeprecated-macro");
4415   }
4416
4417   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4418   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4419     if (Asm->getOption().matches(options::OPT_fasm))
4420       CmdArgs.push_back("-fgnu-keywords");
4421     else
4422       CmdArgs.push_back("-fno-gnu-keywords");
4423   }
4424
4425   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4426     CmdArgs.push_back("-fno-dwarf-directory-asm");
4427
4428   if (ShouldDisableAutolink(Args, getToolChain()))
4429     CmdArgs.push_back("-fno-autolink");
4430
4431   // Add in -fdebug-compilation-dir if necessary.
4432   addDebugCompDirArg(Args, CmdArgs);
4433
4434   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4435     StringRef Map = A->getValue();
4436     if (Map.find('=') == StringRef::npos)
4437       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4438     else
4439       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4440     A->claim();
4441   }
4442
4443   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4444                                options::OPT_ftemplate_depth_EQ)) {
4445     CmdArgs.push_back("-ftemplate-depth");
4446     CmdArgs.push_back(A->getValue());
4447   }
4448
4449   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4450     CmdArgs.push_back("-foperator-arrow-depth");
4451     CmdArgs.push_back(A->getValue());
4452   }
4453
4454   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4455     CmdArgs.push_back("-fconstexpr-depth");
4456     CmdArgs.push_back(A->getValue());
4457   }
4458
4459   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4460     CmdArgs.push_back("-fconstexpr-steps");
4461     CmdArgs.push_back(A->getValue());
4462   }
4463
4464   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4465     CmdArgs.push_back("-fbracket-depth");
4466     CmdArgs.push_back(A->getValue());
4467   }
4468
4469   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4470                                options::OPT_Wlarge_by_value_copy_def)) {
4471     if (A->getNumValues()) {
4472       StringRef bytes = A->getValue();
4473       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4474     } else
4475       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4476   }
4477
4478   if (Args.hasArg(options::OPT_relocatable_pch))
4479     CmdArgs.push_back("-relocatable-pch");
4480
4481   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4482     CmdArgs.push_back("-fconstant-string-class");
4483     CmdArgs.push_back(A->getValue());
4484   }
4485
4486   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4487     CmdArgs.push_back("-ftabstop");
4488     CmdArgs.push_back(A->getValue());
4489   }
4490
4491   CmdArgs.push_back("-ferror-limit");
4492   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4493     CmdArgs.push_back(A->getValue());
4494   else
4495     CmdArgs.push_back("19");
4496
4497   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4498     CmdArgs.push_back("-fmacro-backtrace-limit");
4499     CmdArgs.push_back(A->getValue());
4500   }
4501
4502   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4503     CmdArgs.push_back("-ftemplate-backtrace-limit");
4504     CmdArgs.push_back(A->getValue());
4505   }
4506
4507   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4508     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4509     CmdArgs.push_back(A->getValue());
4510   }
4511
4512   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4513     CmdArgs.push_back("-fspell-checking-limit");
4514     CmdArgs.push_back(A->getValue());
4515   }
4516
4517   // Pass -fmessage-length=.
4518   CmdArgs.push_back("-fmessage-length");
4519   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4520     CmdArgs.push_back(A->getValue());
4521   } else {
4522     // If -fmessage-length=N was not specified, determine whether this is a
4523     // terminal and, if so, implicitly define -fmessage-length appropriately.
4524     unsigned N = llvm::sys::Process::StandardErrColumns();
4525     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4526   }
4527
4528   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4529   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4530                                      options::OPT_fvisibility_ms_compat)) {
4531     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4532       CmdArgs.push_back("-fvisibility");
4533       CmdArgs.push_back(A->getValue());
4534     } else {
4535       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4536       CmdArgs.push_back("-fvisibility");
4537       CmdArgs.push_back("hidden");
4538       CmdArgs.push_back("-ftype-visibility");
4539       CmdArgs.push_back("default");
4540     }
4541   }
4542
4543   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4544
4545   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4546
4547   // -fhosted is default.
4548   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4549       KernelOrKext)
4550     CmdArgs.push_back("-ffreestanding");
4551
4552   // Forward -f (flag) options which we can pass directly.
4553   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4554   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4555   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4556   // Emulated TLS is enabled by default on Android, and can be enabled manually
4557   // with -femulated-tls.
4558   bool EmulatedTLSDefault = Triple.isAndroid();
4559   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4560                    EmulatedTLSDefault))
4561     CmdArgs.push_back("-femulated-tls");
4562   // AltiVec-like language extensions aren't relevant for assembling.
4563   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4564     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4565     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4566   }
4567   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4568   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4569
4570   // Forward flags for OpenMP
4571   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4572                    options::OPT_fno_openmp, false))
4573     switch (getOpenMPRuntime(getToolChain(), Args)) {
4574     case OMPRT_OMP:
4575     case OMPRT_IOMP5:
4576       // Clang can generate useful OpenMP code for these two runtime libraries.
4577       CmdArgs.push_back("-fopenmp");
4578
4579       // If no option regarding the use of TLS in OpenMP codegeneration is
4580       // given, decide a default based on the target. Otherwise rely on the
4581       // options and pass the right information to the frontend.
4582       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4583                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4584         CmdArgs.push_back("-fnoopenmp-use-tls");
4585       break;
4586     default:
4587       // By default, if Clang doesn't know how to generate useful OpenMP code
4588       // for a specific runtime library, we just don't pass the '-fopenmp' flag
4589       // down to the actual compilation.
4590       // FIXME: It would be better to have a mode which *only* omits IR
4591       // generation based on the OpenMP support so that we get consistent
4592       // semantic analysis, etc.
4593       break;
4594     }
4595
4596   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4597   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4598
4599   // Report an error for -faltivec on anything other than PowerPC.
4600   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4601     const llvm::Triple::ArchType Arch = getToolChain().getArch();
4602     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4603           Arch == llvm::Triple::ppc64le))
4604       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4605                                                        << "ppc/ppc64/ppc64le";
4606   }
4607
4608   // -fzvector is incompatible with -faltivec.
4609   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4610     if (Args.hasArg(options::OPT_faltivec))
4611       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4612                                                       << "-faltivec";
4613
4614   if (getToolChain().SupportsProfiling())
4615     Args.AddLastArg(CmdArgs, options::OPT_pg);
4616
4617   // -flax-vector-conversions is default.
4618   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4619                     options::OPT_fno_lax_vector_conversions))
4620     CmdArgs.push_back("-fno-lax-vector-conversions");
4621
4622   if (Args.getLastArg(options::OPT_fapple_kext) ||
4623       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4624     CmdArgs.push_back("-fapple-kext");
4625
4626   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4627   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4628   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4629   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4630   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4631
4632   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4633     CmdArgs.push_back("-ftrapv-handler");
4634     CmdArgs.push_back(A->getValue());
4635   }
4636
4637   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4638
4639   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4640   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4641   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4642     if (A->getOption().matches(options::OPT_fwrapv))
4643       CmdArgs.push_back("-fwrapv");
4644   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4645                                       options::OPT_fno_strict_overflow)) {
4646     if (A->getOption().matches(options::OPT_fno_strict_overflow))
4647       CmdArgs.push_back("-fwrapv");
4648   }
4649
4650   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4651                                options::OPT_fno_reroll_loops))
4652     if (A->getOption().matches(options::OPT_freroll_loops))
4653       CmdArgs.push_back("-freroll-loops");
4654
4655   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4656   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4657                   options::OPT_fno_unroll_loops);
4658
4659   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4660
4661   // -stack-protector=0 is default.
4662   unsigned StackProtectorLevel = 0;
4663   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4664     Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4665     Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4666     Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4667     Args.ClaimAllArgs(options::OPT_fstack_protector);
4668   } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4669                                       options::OPT_fstack_protector_all,
4670                                       options::OPT_fstack_protector_strong,
4671                                       options::OPT_fstack_protector)) {
4672     if (A->getOption().matches(options::OPT_fstack_protector)) {
4673       StackProtectorLevel = std::max<unsigned>(
4674           LangOptions::SSPOn,
4675           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4676     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4677       StackProtectorLevel = LangOptions::SSPStrong;
4678     else if (A->getOption().matches(options::OPT_fstack_protector_all))
4679       StackProtectorLevel = LangOptions::SSPReq;
4680   } else {
4681     StackProtectorLevel =
4682         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4683   }
4684   if (StackProtectorLevel) {
4685     CmdArgs.push_back("-stack-protector");
4686     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4687   }
4688
4689   // --param ssp-buffer-size=
4690   for (const Arg *A : Args.filtered(options::OPT__param)) {
4691     StringRef Str(A->getValue());
4692     if (Str.startswith("ssp-buffer-size=")) {
4693       if (StackProtectorLevel) {
4694         CmdArgs.push_back("-stack-protector-buffer-size");
4695         // FIXME: Verify the argument is a valid integer.
4696         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4697       }
4698       A->claim();
4699     }
4700   }
4701
4702   // Translate -mstackrealign
4703   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4704                    false))
4705     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4706
4707   if (Args.hasArg(options::OPT_mstack_alignment)) {
4708     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4709     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4710   }
4711
4712   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4713     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4714
4715     if (!Size.empty())
4716       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4717     else
4718       CmdArgs.push_back("-mstack-probe-size=0");
4719   }
4720
4721   switch (getToolChain().getArch()) {
4722   case llvm::Triple::aarch64:
4723   case llvm::Triple::aarch64_be:
4724   case llvm::Triple::arm:
4725   case llvm::Triple::armeb:
4726   case llvm::Triple::thumb:
4727   case llvm::Triple::thumbeb:
4728     CmdArgs.push_back("-fallow-half-arguments-and-returns");
4729     break;
4730
4731   default:
4732     break;
4733   }
4734
4735   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4736                                options::OPT_mno_restrict_it)) {
4737     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4738       CmdArgs.push_back("-backend-option");
4739       CmdArgs.push_back("-arm-restrict-it");
4740     } else {
4741       CmdArgs.push_back("-backend-option");
4742       CmdArgs.push_back("-arm-no-restrict-it");
4743     }
4744   } else if (Triple.isOSWindows() &&
4745              (Triple.getArch() == llvm::Triple::arm ||
4746               Triple.getArch() == llvm::Triple::thumb)) {
4747     // Windows on ARM expects restricted IT blocks
4748     CmdArgs.push_back("-backend-option");
4749     CmdArgs.push_back("-arm-restrict-it");
4750   }
4751
4752   // Forward -f options with positive and negative forms; we translate
4753   // these by hand.
4754   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4755     StringRef fname = A->getValue();
4756     if (!llvm::sys::fs::exists(fname))
4757       D.Diag(diag::err_drv_no_such_file) << fname;
4758     else
4759       A->render(Args, CmdArgs);
4760   }
4761
4762   // -fbuiltin is default unless -mkernel is used.
4763   bool UseBuiltins =
4764       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4765                    !Args.hasArg(options::OPT_mkernel));
4766   if (!UseBuiltins)
4767     CmdArgs.push_back("-fno-builtin");
4768
4769   // -ffreestanding implies -fno-builtin.
4770   if (Args.hasArg(options::OPT_ffreestanding))
4771     UseBuiltins = false;
4772
4773   // Process the -fno-builtin-* options.
4774   for (const auto &Arg : Args) {
4775     const Option &O = Arg->getOption();
4776     if (!O.matches(options::OPT_fno_builtin_))
4777       continue;
4778
4779     Arg->claim();
4780     // If -fno-builtin is specified, then there's no need to pass the option to
4781     // the frontend.
4782     if (!UseBuiltins)
4783       continue;
4784
4785     StringRef FuncName = Arg->getValue();
4786     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
4787   }
4788
4789   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4790                     options::OPT_fno_assume_sane_operator_new))
4791     CmdArgs.push_back("-fno-assume-sane-operator-new");
4792
4793   // -fblocks=0 is default.
4794   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4795                    getToolChain().IsBlocksDefault()) ||
4796       (Args.hasArg(options::OPT_fgnu_runtime) &&
4797        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4798        !Args.hasArg(options::OPT_fno_blocks))) {
4799     CmdArgs.push_back("-fblocks");
4800
4801     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4802         !getToolChain().hasBlocksRuntime())
4803       CmdArgs.push_back("-fblocks-runtime-optional");
4804   }
4805
4806   // -fmodules enables the use of precompiled modules (off by default).
4807   // Users can pass -fno-cxx-modules to turn off modules support for
4808   // C++/Objective-C++ programs.
4809   bool HaveModules = false;
4810   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4811     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4812                                      options::OPT_fno_cxx_modules, true);
4813     if (AllowedInCXX || !types::isCXX(InputType)) {
4814       CmdArgs.push_back("-fmodules");
4815       HaveModules = true;
4816     }
4817   }
4818
4819   // -fmodule-maps enables implicit reading of module map files. By default,
4820   // this is enabled if we are using precompiled modules.
4821   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4822                    options::OPT_fno_implicit_module_maps, HaveModules)) {
4823     CmdArgs.push_back("-fimplicit-module-maps");
4824   }
4825
4826   // -fmodules-decluse checks that modules used are declared so (off by
4827   // default).
4828   if (Args.hasFlag(options::OPT_fmodules_decluse,
4829                    options::OPT_fno_modules_decluse, false)) {
4830     CmdArgs.push_back("-fmodules-decluse");
4831   }
4832
4833   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4834   // all #included headers are part of modules.
4835   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4836                    options::OPT_fno_modules_strict_decluse, false)) {
4837     CmdArgs.push_back("-fmodules-strict-decluse");
4838   }
4839
4840   // -fno-implicit-modules turns off implicitly compiling modules on demand.
4841   if (!Args.hasFlag(options::OPT_fimplicit_modules,
4842                     options::OPT_fno_implicit_modules)) {
4843     CmdArgs.push_back("-fno-implicit-modules");
4844   }
4845
4846   // -fmodule-name specifies the module that is currently being built (or
4847   // used for header checking by -fmodule-maps).
4848   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4849
4850   // -fmodule-map-file can be used to specify files containing module
4851   // definitions.
4852   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4853
4854   // -fmodule-file can be used to specify files containing precompiled modules.
4855   if (HaveModules)
4856     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4857   else
4858     Args.ClaimAllArgs(options::OPT_fmodule_file);
4859
4860   // -fmodule-cache-path specifies where our implicitly-built module files
4861   // should be written.
4862   SmallString<128> Path;
4863   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4864     Path = A->getValue();
4865   if (HaveModules) {
4866     if (C.isForDiagnostics()) {
4867       // When generating crash reports, we want to emit the modules along with
4868       // the reproduction sources, so we ignore any provided module path.
4869       Path = Output.getFilename();
4870       llvm::sys::path::replace_extension(Path, ".cache");
4871       llvm::sys::path::append(Path, "modules");
4872     } else if (Path.empty()) {
4873       // No module path was provided: use the default.
4874       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4875       llvm::sys::path::append(Path, "org.llvm.clang.");
4876       appendUserToPath(Path);
4877       llvm::sys::path::append(Path, "ModuleCache");
4878     }
4879     const char Arg[] = "-fmodules-cache-path=";
4880     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4881     CmdArgs.push_back(Args.MakeArgString(Path));
4882   }
4883
4884   // When building modules and generating crashdumps, we need to dump a module
4885   // dependency VFS alongside the output.
4886   if (HaveModules && C.isForDiagnostics()) {
4887     SmallString<128> VFSDir(Output.getFilename());
4888     llvm::sys::path::replace_extension(VFSDir, ".cache");
4889     // Add the cache directory as a temp so the crash diagnostics pick it up.
4890     C.addTempFile(Args.MakeArgString(VFSDir));
4891
4892     llvm::sys::path::append(VFSDir, "vfs");
4893     CmdArgs.push_back("-module-dependency-dir");
4894     CmdArgs.push_back(Args.MakeArgString(VFSDir));
4895   }
4896
4897   if (HaveModules)
4898     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4899
4900   // Pass through all -fmodules-ignore-macro arguments.
4901   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4902   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4903   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4904
4905   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4906
4907   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4908     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4909       D.Diag(diag::err_drv_argument_not_allowed_with)
4910           << A->getAsString(Args) << "-fbuild-session-timestamp";
4911
4912     llvm::sys::fs::file_status Status;
4913     if (llvm::sys::fs::status(A->getValue(), Status))
4914       D.Diag(diag::err_drv_no_such_file) << A->getValue();
4915     CmdArgs.push_back(Args.MakeArgString(
4916         "-fbuild-session-timestamp=" +
4917         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4918   }
4919
4920   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4921     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4922                          options::OPT_fbuild_session_file))
4923       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4924
4925     Args.AddLastArg(CmdArgs,
4926                     options::OPT_fmodules_validate_once_per_build_session);
4927   }
4928
4929   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4930
4931   // -faccess-control is default.
4932   if (Args.hasFlag(options::OPT_fno_access_control,
4933                    options::OPT_faccess_control, false))
4934     CmdArgs.push_back("-fno-access-control");
4935
4936   // -felide-constructors is the default.
4937   if (Args.hasFlag(options::OPT_fno_elide_constructors,
4938                    options::OPT_felide_constructors, false))
4939     CmdArgs.push_back("-fno-elide-constructors");
4940
4941   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4942
4943   if (KernelOrKext || (types::isCXX(InputType) &&
4944                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4945                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
4946     CmdArgs.push_back("-fno-rtti");
4947
4948   // -fshort-enums=0 is default for all architectures except Hexagon.
4949   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4950                    getToolChain().getArch() == llvm::Triple::hexagon))
4951     CmdArgs.push_back("-fshort-enums");
4952
4953   // -fsigned-char is default.
4954   if (Arg *A = Args.getLastArg(
4955           options::OPT_fsigned_char, options::OPT_fno_signed_char,
4956           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4957     if (A->getOption().matches(options::OPT_funsigned_char) ||
4958         A->getOption().matches(options::OPT_fno_signed_char)) {
4959       CmdArgs.push_back("-fno-signed-char");
4960     }
4961   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4962     CmdArgs.push_back("-fno-signed-char");
4963   }
4964
4965   // -fuse-cxa-atexit is default.
4966   if (!Args.hasFlag(
4967           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4968           !IsWindowsCygnus && !IsWindowsGNU &&
4969               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4970               getToolChain().getArch() != llvm::Triple::hexagon &&
4971               getToolChain().getArch() != llvm::Triple::xcore &&
4972               ((getToolChain().getTriple().getVendor() !=
4973                 llvm::Triple::MipsTechnologies) ||
4974                getToolChain().getTriple().hasEnvironment())) ||
4975       KernelOrKext)
4976     CmdArgs.push_back("-fno-use-cxa-atexit");
4977
4978   // -fms-extensions=0 is default.
4979   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4980                    IsWindowsMSVC))
4981     CmdArgs.push_back("-fms-extensions");
4982
4983   // -fno-use-line-directives is default.
4984   if (Args.hasFlag(options::OPT_fuse_line_directives,
4985                    options::OPT_fno_use_line_directives, false))
4986     CmdArgs.push_back("-fuse-line-directives");
4987
4988   // -fms-compatibility=0 is default.
4989   if (Args.hasFlag(options::OPT_fms_compatibility,
4990                    options::OPT_fno_ms_compatibility,
4991                    (IsWindowsMSVC &&
4992                     Args.hasFlag(options::OPT_fms_extensions,
4993                                  options::OPT_fno_ms_extensions, true))))
4994     CmdArgs.push_back("-fms-compatibility");
4995
4996   // -fms-compatibility-version=18.00 is default.
4997   VersionTuple MSVT = visualstudio::getMSVCVersion(
4998       &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4999   if (!MSVT.empty())
5000     CmdArgs.push_back(
5001         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5002
5003   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5004   if (ImplyVCPPCXXVer) {
5005     if (IsMSVC2015Compatible)
5006       CmdArgs.push_back("-std=c++14");
5007     else
5008       CmdArgs.push_back("-std=c++11");
5009   }
5010
5011   // -fno-borland-extensions is default.
5012   if (Args.hasFlag(options::OPT_fborland_extensions,
5013                    options::OPT_fno_borland_extensions, false))
5014     CmdArgs.push_back("-fborland-extensions");
5015
5016   // -fno-declspec is default, except for PS4.
5017   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5018                    getToolChain().getTriple().isPS4()))
5019     CmdArgs.push_back("-fdeclspec");
5020   else if (Args.hasArg(options::OPT_fno_declspec))
5021     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5022
5023   // -fthreadsafe-static is default, except for MSVC compatibility versions less
5024   // than 19.
5025   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5026                     options::OPT_fno_threadsafe_statics,
5027                     !IsWindowsMSVC || IsMSVC2015Compatible))
5028     CmdArgs.push_back("-fno-threadsafe-statics");
5029
5030   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5031   // needs it.
5032   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5033                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5034     CmdArgs.push_back("-fdelayed-template-parsing");
5035
5036   // -fgnu-keywords default varies depending on language; only pass if
5037   // specified.
5038   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5039                                options::OPT_fno_gnu_keywords))
5040     A->render(Args, CmdArgs);
5041
5042   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5043                    false))
5044     CmdArgs.push_back("-fgnu89-inline");
5045
5046   if (Args.hasArg(options::OPT_fno_inline))
5047     CmdArgs.push_back("-fno-inline");
5048
5049   if (Args.hasArg(options::OPT_fno_inline_functions))
5050     CmdArgs.push_back("-fno-inline-functions");
5051
5052   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5053
5054   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5055   // legacy is the default. Except for deployment taget of 10.5,
5056   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5057   // gets ignored silently.
5058   if (objcRuntime.isNonFragile()) {
5059     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5060                       options::OPT_fno_objc_legacy_dispatch,
5061                       objcRuntime.isLegacyDispatchDefaultForArch(
5062                           getToolChain().getArch()))) {
5063       if (getToolChain().UseObjCMixedDispatch())
5064         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5065       else
5066         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5067     }
5068   }
5069
5070   // When ObjectiveC legacy runtime is in effect on MacOSX,
5071   // turn on the option to do Array/Dictionary subscripting
5072   // by default.
5073   if (getToolChain().getArch() == llvm::Triple::x86 &&
5074       getToolChain().getTriple().isMacOSX() &&
5075       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5076       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5077       objcRuntime.isNeXTFamily())
5078     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5079
5080   // -fencode-extended-block-signature=1 is default.
5081   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5082     CmdArgs.push_back("-fencode-extended-block-signature");
5083   }
5084
5085   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5086   // NOTE: This logic is duplicated in ToolChains.cpp.
5087   bool ARC = isObjCAutoRefCount(Args);
5088   if (ARC) {
5089     getToolChain().CheckObjCARC();
5090
5091     CmdArgs.push_back("-fobjc-arc");
5092
5093     // FIXME: It seems like this entire block, and several around it should be
5094     // wrapped in isObjC, but for now we just use it here as this is where it
5095     // was being used previously.
5096     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5097       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5098         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5099       else
5100         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5101     }
5102
5103     // Allow the user to enable full exceptions code emission.
5104     // We define off for Objective-CC, on for Objective-C++.
5105     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5106                      options::OPT_fno_objc_arc_exceptions,
5107                      /*default*/ types::isCXX(InputType)))
5108       CmdArgs.push_back("-fobjc-arc-exceptions");
5109
5110   }
5111
5112   // -fobjc-infer-related-result-type is the default, except in the Objective-C
5113   // rewriter.
5114   if (rewriteKind != RK_None)
5115     CmdArgs.push_back("-fno-objc-infer-related-result-type");
5116
5117   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5118   // takes precedence.
5119   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5120   if (!GCArg)
5121     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5122   if (GCArg) {
5123     if (ARC) {
5124       D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5125     } else if (getToolChain().SupportsObjCGC()) {
5126       GCArg->render(Args, CmdArgs);
5127     } else {
5128       // FIXME: We should move this to a hard error.
5129       D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5130     }
5131   }
5132
5133   // Pass down -fobjc-weak or -fno-objc-weak if present.
5134   if (types::isObjC(InputType)) {
5135     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5136                                    options::OPT_fno_objc_weak);
5137     if (!WeakArg) {
5138       // nothing to do
5139     } else if (GCArg) {
5140       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5141         D.Diag(diag::err_objc_weak_with_gc);
5142     } else if (!objcRuntime.allowsWeak()) {
5143       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5144         D.Diag(diag::err_objc_weak_unsupported);
5145     } else {
5146       WeakArg->render(Args, CmdArgs);
5147     }
5148   }
5149
5150   if (Args.hasFlag(options::OPT_fapplication_extension,
5151                    options::OPT_fno_application_extension, false))
5152     CmdArgs.push_back("-fapplication-extension");
5153
5154   // Handle GCC-style exception args.
5155   if (!C.getDriver().IsCLMode())
5156     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5157                      CmdArgs);
5158
5159   if (getToolChain().UseSjLjExceptions(Args))
5160     CmdArgs.push_back("-fsjlj-exceptions");
5161
5162   // C++ "sane" operator new.
5163   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5164                     options::OPT_fno_assume_sane_operator_new))
5165     CmdArgs.push_back("-fno-assume-sane-operator-new");
5166
5167   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5168   // most platforms.
5169   if (Args.hasFlag(options::OPT_fsized_deallocation,
5170                    options::OPT_fno_sized_deallocation, false))
5171     CmdArgs.push_back("-fsized-deallocation");
5172
5173   // -fconstant-cfstrings is default, and may be subject to argument translation
5174   // on Darwin.
5175   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5176                     options::OPT_fno_constant_cfstrings) ||
5177       !Args.hasFlag(options::OPT_mconstant_cfstrings,
5178                     options::OPT_mno_constant_cfstrings))
5179     CmdArgs.push_back("-fno-constant-cfstrings");
5180
5181   // -fshort-wchar default varies depending on platform; only
5182   // pass if specified.
5183   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5184                                options::OPT_fno_short_wchar))
5185     A->render(Args, CmdArgs);
5186
5187   // -fno-pascal-strings is default, only pass non-default.
5188   if (Args.hasFlag(options::OPT_fpascal_strings,
5189                    options::OPT_fno_pascal_strings, false))
5190     CmdArgs.push_back("-fpascal-strings");
5191
5192   // Honor -fpack-struct= and -fpack-struct, if given. Note that
5193   // -fno-pack-struct doesn't apply to -fpack-struct=.
5194   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5195     std::string PackStructStr = "-fpack-struct=";
5196     PackStructStr += A->getValue();
5197     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5198   } else if (Args.hasFlag(options::OPT_fpack_struct,
5199                           options::OPT_fno_pack_struct, false)) {
5200     CmdArgs.push_back("-fpack-struct=1");
5201   }
5202
5203   // Handle -fmax-type-align=N and -fno-type-align
5204   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5205   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5206     if (!SkipMaxTypeAlign) {
5207       std::string MaxTypeAlignStr = "-fmax-type-align=";
5208       MaxTypeAlignStr += A->getValue();
5209       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5210     }
5211   } else if (getToolChain().getTriple().isOSDarwin()) {
5212     if (!SkipMaxTypeAlign) {
5213       std::string MaxTypeAlignStr = "-fmax-type-align=16";
5214       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5215     }
5216   }
5217
5218   // -fcommon is the default unless compiling kernel code or the target says so
5219   bool NoCommonDefault =
5220       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5221   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5222                     !NoCommonDefault))
5223     CmdArgs.push_back("-fno-common");
5224
5225   // -fsigned-bitfields is default, and clang doesn't yet support
5226   // -funsigned-bitfields.
5227   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5228                     options::OPT_funsigned_bitfields))
5229     D.Diag(diag::warn_drv_clang_unsupported)
5230         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5231
5232   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5233   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5234     D.Diag(diag::err_drv_clang_unsupported)
5235         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5236
5237   // -finput_charset=UTF-8 is default. Reject others
5238   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5239     StringRef value = inputCharset->getValue();
5240     if (value != "UTF-8")
5241       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5242                                           << value;
5243   }
5244
5245   // -fexec_charset=UTF-8 is default. Reject others
5246   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5247     StringRef value = execCharset->getValue();
5248     if (value != "UTF-8")
5249       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5250                                           << value;
5251   }
5252
5253   // -fcaret-diagnostics is default.
5254   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5255                     options::OPT_fno_caret_diagnostics, true))
5256     CmdArgs.push_back("-fno-caret-diagnostics");
5257
5258   // -fdiagnostics-fixit-info is default, only pass non-default.
5259   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5260                     options::OPT_fno_diagnostics_fixit_info))
5261     CmdArgs.push_back("-fno-diagnostics-fixit-info");
5262
5263   // Enable -fdiagnostics-show-option by default.
5264   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5265                    options::OPT_fno_diagnostics_show_option))
5266     CmdArgs.push_back("-fdiagnostics-show-option");
5267
5268   if (const Arg *A =
5269           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5270     CmdArgs.push_back("-fdiagnostics-show-category");
5271     CmdArgs.push_back(A->getValue());
5272   }
5273
5274   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5275     CmdArgs.push_back("-fdiagnostics-format");
5276     CmdArgs.push_back(A->getValue());
5277   }
5278
5279   if (Arg *A = Args.getLastArg(
5280           options::OPT_fdiagnostics_show_note_include_stack,
5281           options::OPT_fno_diagnostics_show_note_include_stack)) {
5282     if (A->getOption().matches(
5283             options::OPT_fdiagnostics_show_note_include_stack))
5284       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5285     else
5286       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5287   }
5288
5289   // Color diagnostics are the default, unless the terminal doesn't support
5290   // them.
5291   // Support both clang's -f[no-]color-diagnostics and gcc's
5292   // -f[no-]diagnostics-colors[=never|always|auto].
5293   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5294   for (const auto &Arg : Args) {
5295     const Option &O = Arg->getOption();
5296     if (!O.matches(options::OPT_fcolor_diagnostics) &&
5297         !O.matches(options::OPT_fdiagnostics_color) &&
5298         !O.matches(options::OPT_fno_color_diagnostics) &&
5299         !O.matches(options::OPT_fno_diagnostics_color) &&
5300         !O.matches(options::OPT_fdiagnostics_color_EQ))
5301       continue;
5302
5303     Arg->claim();
5304     if (O.matches(options::OPT_fcolor_diagnostics) ||
5305         O.matches(options::OPT_fdiagnostics_color)) {
5306       ShowColors = Colors_On;
5307     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5308                O.matches(options::OPT_fno_diagnostics_color)) {
5309       ShowColors = Colors_Off;
5310     } else {
5311       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5312       StringRef value(Arg->getValue());
5313       if (value == "always")
5314         ShowColors = Colors_On;
5315       else if (value == "never")
5316         ShowColors = Colors_Off;
5317       else if (value == "auto")
5318         ShowColors = Colors_Auto;
5319       else
5320         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5321             << ("-fdiagnostics-color=" + value).str();
5322     }
5323   }
5324   if (ShowColors == Colors_On ||
5325       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5326     CmdArgs.push_back("-fcolor-diagnostics");
5327
5328   if (Args.hasArg(options::OPT_fansi_escape_codes))
5329     CmdArgs.push_back("-fansi-escape-codes");
5330
5331   if (!Args.hasFlag(options::OPT_fshow_source_location,
5332                     options::OPT_fno_show_source_location))
5333     CmdArgs.push_back("-fno-show-source-location");
5334
5335   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5336                     true))
5337     CmdArgs.push_back("-fno-show-column");
5338
5339   if (!Args.hasFlag(options::OPT_fspell_checking,
5340                     options::OPT_fno_spell_checking))
5341     CmdArgs.push_back("-fno-spell-checking");
5342
5343   // -fno-asm-blocks is default.
5344   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5345                    false))
5346     CmdArgs.push_back("-fasm-blocks");
5347
5348   // -fgnu-inline-asm is default.
5349   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5350                     options::OPT_fno_gnu_inline_asm, true))
5351     CmdArgs.push_back("-fno-gnu-inline-asm");
5352
5353   // Enable vectorization per default according to the optimization level
5354   // selected. For optimization levels that want vectorization we use the alias
5355   // option to simplify the hasFlag logic.
5356   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5357   OptSpecifier VectorizeAliasOption =
5358       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5359   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5360                    options::OPT_fno_vectorize, EnableVec))
5361     CmdArgs.push_back("-vectorize-loops");
5362
5363   // -fslp-vectorize is enabled based on the optimization level selected.
5364   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5365   OptSpecifier SLPVectAliasOption =
5366       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5367   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5368                    options::OPT_fno_slp_vectorize, EnableSLPVec))
5369     CmdArgs.push_back("-vectorize-slp");
5370
5371   // -fno-slp-vectorize-aggressive is default.
5372   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5373                    options::OPT_fno_slp_vectorize_aggressive, false))
5374     CmdArgs.push_back("-vectorize-slp-aggressive");
5375
5376   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5377     A->render(Args, CmdArgs);
5378
5379   // -fdollars-in-identifiers default varies depending on platform and
5380   // language; only pass if specified.
5381   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5382                                options::OPT_fno_dollars_in_identifiers)) {
5383     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5384       CmdArgs.push_back("-fdollars-in-identifiers");
5385     else
5386       CmdArgs.push_back("-fno-dollars-in-identifiers");
5387   }
5388
5389   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5390   // practical purposes.
5391   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5392                                options::OPT_fno_unit_at_a_time)) {
5393     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5394       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5395   }
5396
5397   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5398                    options::OPT_fno_apple_pragma_pack, false))
5399     CmdArgs.push_back("-fapple-pragma-pack");
5400
5401   // le32-specific flags:
5402   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
5403   //                     by default.
5404   if (getToolChain().getArch() == llvm::Triple::le32) {
5405     CmdArgs.push_back("-fno-math-builtin");
5406   }
5407
5408 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5409 //
5410 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5411 #if 0
5412   if (getToolChain().getTriple().isOSDarwin() &&
5413       (getToolChain().getArch() == llvm::Triple::arm ||
5414        getToolChain().getArch() == llvm::Triple::thumb)) {
5415     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5416       CmdArgs.push_back("-fno-builtin-strcat");
5417     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5418       CmdArgs.push_back("-fno-builtin-strcpy");
5419   }
5420 #endif
5421
5422   // Enable rewrite includes if the user's asked for it or if we're generating
5423   // diagnostics.
5424   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5425   // nice to enable this when doing a crashdump for modules as well.
5426   if (Args.hasFlag(options::OPT_frewrite_includes,
5427                    options::OPT_fno_rewrite_includes, false) ||
5428       (C.isForDiagnostics() && !HaveModules))
5429     CmdArgs.push_back("-frewrite-includes");
5430
5431   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5432   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5433                                options::OPT_traditional_cpp)) {
5434     if (isa<PreprocessJobAction>(JA))
5435       CmdArgs.push_back("-traditional-cpp");
5436     else
5437       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5438   }
5439
5440   Args.AddLastArg(CmdArgs, options::OPT_dM);
5441   Args.AddLastArg(CmdArgs, options::OPT_dD);
5442
5443   // Handle serialized diagnostics.
5444   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5445     CmdArgs.push_back("-serialize-diagnostic-file");
5446     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5447   }
5448
5449   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5450     CmdArgs.push_back("-fretain-comments-from-system-headers");
5451
5452   // Forward -fcomment-block-commands to -cc1.
5453   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5454   // Forward -fparse-all-comments to -cc1.
5455   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5456
5457   // Turn -fplugin=name.so into -load name.so
5458   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5459     CmdArgs.push_back("-load");
5460     CmdArgs.push_back(A->getValue());
5461     A->claim();
5462   }
5463
5464   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5465   // parser.
5466   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5467   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5468     A->claim();
5469
5470     // We translate this by hand to the -cc1 argument, since nightly test uses
5471     // it and developers have been trained to spell it with -mllvm.
5472     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5473       CmdArgs.push_back("-disable-llvm-optzns");
5474     } else
5475       A->render(Args, CmdArgs);
5476   }
5477
5478   // With -save-temps, we want to save the unoptimized bitcode output from the
5479   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5480   // by the frontend.
5481   if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5482     CmdArgs.push_back("-disable-llvm-passes");
5483
5484   if (Output.getType() == types::TY_Dependencies) {
5485     // Handled with other dependency code.
5486   } else if (Output.isFilename()) {
5487     CmdArgs.push_back("-o");
5488     CmdArgs.push_back(Output.getFilename());
5489   } else {
5490     assert(Output.isNothing() && "Invalid output.");
5491   }
5492
5493   addDashXForInput(Args, Input, CmdArgs);
5494
5495   if (Input.isFilename())
5496     CmdArgs.push_back(Input.getFilename());
5497   else
5498     Input.getInputArg().renderAsInput(Args, CmdArgs);
5499
5500   Args.AddAllArgs(CmdArgs, options::OPT_undef);
5501
5502   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5503
5504   // Optionally embed the -cc1 level arguments into the debug info, for build
5505   // analysis.
5506   if (getToolChain().UseDwarfDebugFlags()) {
5507     ArgStringList OriginalArgs;
5508     for (const auto &Arg : Args)
5509       Arg->render(Args, OriginalArgs);
5510
5511     SmallString<256> Flags;
5512     Flags += Exec;
5513     for (const char *OriginalArg : OriginalArgs) {
5514       SmallString<128> EscapedArg;
5515       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5516       Flags += " ";
5517       Flags += EscapedArg;
5518     }
5519     CmdArgs.push_back("-dwarf-debug-flags");
5520     CmdArgs.push_back(Args.MakeArgString(Flags));
5521   }
5522
5523   // Add the split debug info name to the command lines here so we
5524   // can propagate it to the backend.
5525   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5526                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5527                      isa<BackendJobAction>(JA));
5528   const char *SplitDwarfOut;
5529   if (SplitDwarf) {
5530     CmdArgs.push_back("-split-dwarf-file");
5531     SplitDwarfOut = SplitDebugName(Args, Input);
5532     CmdArgs.push_back(SplitDwarfOut);
5533   }
5534
5535   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5536   // Include them with -fcuda-include-gpubinary.
5537   if (IsCuda && Inputs.size() > 1)
5538     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5539       CmdArgs.push_back("-fcuda-include-gpubinary");
5540       CmdArgs.push_back(I->getFilename());
5541     }
5542
5543   // Finally add the compile command to the compilation.
5544   if (Args.hasArg(options::OPT__SLASH_fallback) &&
5545       Output.getType() == types::TY_Object &&
5546       (InputType == types::TY_C || InputType == types::TY_CXX)) {
5547     auto CLCommand =
5548         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5549     C.addCommand(llvm::make_unique<FallbackCommand>(
5550         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5551   } else {
5552     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5553   }
5554
5555   // Handle the debug info splitting at object creation time if we're
5556   // creating an object.
5557   // TODO: Currently only works on linux with newer objcopy.
5558   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5559     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5560
5561   if (Arg *A = Args.getLastArg(options::OPT_pg))
5562     if (Args.hasArg(options::OPT_fomit_frame_pointer))
5563       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5564                                                       << A->getAsString(Args);
5565
5566   // Claim some arguments which clang supports automatically.
5567
5568   // -fpch-preprocess is used with gcc to add a special marker in the output to
5569   // include the PCH file. Clang's PTH solution is completely transparent, so we
5570   // do not need to deal with it at all.
5571   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5572
5573   // Claim some arguments which clang doesn't support, but we don't
5574   // care to warn the user about.
5575   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5576   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5577
5578   // Disable warnings for clang -E -emit-llvm foo.c
5579   Args.ClaimAllArgs(options::OPT_emit_llvm);
5580 }
5581
5582 /// Add options related to the Objective-C runtime/ABI.
5583 ///
5584 /// Returns true if the runtime is non-fragile.
5585 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5586                                       ArgStringList &cmdArgs,
5587                                       RewriteKind rewriteKind) const {
5588   // Look for the controlling runtime option.
5589   Arg *runtimeArg =
5590       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5591                       options::OPT_fobjc_runtime_EQ);
5592
5593   // Just forward -fobjc-runtime= to the frontend.  This supercedes
5594   // options about fragility.
5595   if (runtimeArg &&
5596       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5597     ObjCRuntime runtime;
5598     StringRef value = runtimeArg->getValue();
5599     if (runtime.tryParse(value)) {
5600       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5601           << value;
5602     }
5603
5604     runtimeArg->render(args, cmdArgs);
5605     return runtime;
5606   }
5607
5608   // Otherwise, we'll need the ABI "version".  Version numbers are
5609   // slightly confusing for historical reasons:
5610   //   1 - Traditional "fragile" ABI
5611   //   2 - Non-fragile ABI, version 1
5612   //   3 - Non-fragile ABI, version 2
5613   unsigned objcABIVersion = 1;
5614   // If -fobjc-abi-version= is present, use that to set the version.
5615   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5616     StringRef value = abiArg->getValue();
5617     if (value == "1")
5618       objcABIVersion = 1;
5619     else if (value == "2")
5620       objcABIVersion = 2;
5621     else if (value == "3")
5622       objcABIVersion = 3;
5623     else
5624       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5625   } else {
5626     // Otherwise, determine if we are using the non-fragile ABI.
5627     bool nonFragileABIIsDefault =
5628         (rewriteKind == RK_NonFragile ||
5629          (rewriteKind == RK_None &&
5630           getToolChain().IsObjCNonFragileABIDefault()));
5631     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5632                      options::OPT_fno_objc_nonfragile_abi,
5633                      nonFragileABIIsDefault)) {
5634 // Determine the non-fragile ABI version to use.
5635 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5636       unsigned nonFragileABIVersion = 1;
5637 #else
5638       unsigned nonFragileABIVersion = 2;
5639 #endif
5640
5641       if (Arg *abiArg =
5642               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5643         StringRef value = abiArg->getValue();
5644         if (value == "1")
5645           nonFragileABIVersion = 1;
5646         else if (value == "2")
5647           nonFragileABIVersion = 2;
5648         else
5649           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5650               << value;
5651       }
5652
5653       objcABIVersion = 1 + nonFragileABIVersion;
5654     } else {
5655       objcABIVersion = 1;
5656     }
5657   }
5658
5659   // We don't actually care about the ABI version other than whether
5660   // it's non-fragile.
5661   bool isNonFragile = objcABIVersion != 1;
5662
5663   // If we have no runtime argument, ask the toolchain for its default runtime.
5664   // However, the rewriter only really supports the Mac runtime, so assume that.
5665   ObjCRuntime runtime;
5666   if (!runtimeArg) {
5667     switch (rewriteKind) {
5668     case RK_None:
5669       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5670       break;
5671     case RK_Fragile:
5672       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5673       break;
5674     case RK_NonFragile:
5675       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5676       break;
5677     }
5678
5679     // -fnext-runtime
5680   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5681     // On Darwin, make this use the default behavior for the toolchain.
5682     if (getToolChain().getTriple().isOSDarwin()) {
5683       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5684
5685       // Otherwise, build for a generic macosx port.
5686     } else {
5687       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5688     }
5689
5690     // -fgnu-runtime
5691   } else {
5692     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5693     // Legacy behaviour is to target the gnustep runtime if we are in
5694     // non-fragile mode or the GCC runtime in fragile mode.
5695     if (isNonFragile)
5696       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5697     else
5698       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5699   }
5700
5701   cmdArgs.push_back(
5702       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5703   return runtime;
5704 }
5705
5706 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5707   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5708   I += HaveDash;
5709   return !HaveDash;
5710 }
5711
5712 namespace {
5713 struct EHFlags {
5714   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5715   bool Synch;
5716   bool Asynch;
5717   bool NoExceptC;
5718 };
5719 } // end anonymous namespace
5720
5721 /// /EH controls whether to run destructor cleanups when exceptions are
5722 /// thrown.  There are three modifiers:
5723 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5724 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5725 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5726 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
5727 ///      modifier is an optimization, so we ignore it for now.
5728 /// The default is /EHs-c-, meaning cleanups are disabled.
5729 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5730   EHFlags EH;
5731
5732   std::vector<std::string> EHArgs =
5733       Args.getAllArgValues(options::OPT__SLASH_EH);
5734   for (auto EHVal : EHArgs) {
5735     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5736       switch (EHVal[I]) {
5737       case 'a':
5738         EH.Asynch = maybeConsumeDash(EHVal, I);
5739         continue;
5740       case 'c':
5741         EH.NoExceptC = maybeConsumeDash(EHVal, I);
5742         continue;
5743       case 's':
5744         EH.Synch = maybeConsumeDash(EHVal, I);
5745         continue;
5746       default:
5747         break;
5748       }
5749       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5750       break;
5751     }
5752   }
5753
5754   return EH;
5755 }
5756
5757 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5758                            enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5759                            bool *EmitCodeView) const {
5760   unsigned RTOptionID = options::OPT__SLASH_MT;
5761
5762   if (Args.hasArg(options::OPT__SLASH_LDd))
5763     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5764     // but defining _DEBUG is sticky.
5765     RTOptionID = options::OPT__SLASH_MTd;
5766
5767   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5768     RTOptionID = A->getOption().getID();
5769
5770   StringRef FlagForCRT;
5771   switch (RTOptionID) {
5772   case options::OPT__SLASH_MD:
5773     if (Args.hasArg(options::OPT__SLASH_LDd))
5774       CmdArgs.push_back("-D_DEBUG");
5775     CmdArgs.push_back("-D_MT");
5776     CmdArgs.push_back("-D_DLL");
5777     FlagForCRT = "--dependent-lib=msvcrt";
5778     break;
5779   case options::OPT__SLASH_MDd:
5780     CmdArgs.push_back("-D_DEBUG");
5781     CmdArgs.push_back("-D_MT");
5782     CmdArgs.push_back("-D_DLL");
5783     FlagForCRT = "--dependent-lib=msvcrtd";
5784     break;
5785   case options::OPT__SLASH_MT:
5786     if (Args.hasArg(options::OPT__SLASH_LDd))
5787       CmdArgs.push_back("-D_DEBUG");
5788     CmdArgs.push_back("-D_MT");
5789     FlagForCRT = "--dependent-lib=libcmt";
5790     break;
5791   case options::OPT__SLASH_MTd:
5792     CmdArgs.push_back("-D_DEBUG");
5793     CmdArgs.push_back("-D_MT");
5794     FlagForCRT = "--dependent-lib=libcmtd";
5795     break;
5796   default:
5797     llvm_unreachable("Unexpected option ID.");
5798   }
5799
5800   if (Args.hasArg(options::OPT__SLASH_Zl)) {
5801     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5802   } else {
5803     CmdArgs.push_back(FlagForCRT.data());
5804
5805     // This provides POSIX compatibility (maps 'open' to '_open'), which most
5806     // users want.  The /Za flag to cl.exe turns this off, but it's not
5807     // implemented in clang.
5808     CmdArgs.push_back("--dependent-lib=oldnames");
5809   }
5810
5811   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5812   // would produce interleaved output, so ignore /showIncludes in such cases.
5813   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5814     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5815       A->render(Args, CmdArgs);
5816
5817   // This controls whether or not we emit RTTI data for polymorphic types.
5818   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5819                    /*default=*/false))
5820     CmdArgs.push_back("-fno-rtti-data");
5821
5822   // Emit CodeView if -Z7 is present.
5823   *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5824   bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5825   // If we are emitting CV but not DWARF, don't build information that LLVM
5826   // can't yet process.
5827   if (*EmitCodeView && !EmitDwarf)
5828     *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5829   if (*EmitCodeView)
5830     CmdArgs.push_back("-gcodeview");
5831
5832   const Driver &D = getToolChain().getDriver();
5833   EHFlags EH = parseClangCLEHFlags(D, Args);
5834   // FIXME: Do something with NoExceptC.
5835   if (EH.Synch || EH.Asynch) {
5836     CmdArgs.push_back("-fcxx-exceptions");
5837     CmdArgs.push_back("-fexceptions");
5838   }
5839
5840   // /EP should expand to -E -P.
5841   if (Args.hasArg(options::OPT__SLASH_EP)) {
5842     CmdArgs.push_back("-E");
5843     CmdArgs.push_back("-P");
5844   }
5845
5846   unsigned VolatileOptionID;
5847   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5848       getToolChain().getArch() == llvm::Triple::x86)
5849     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5850   else
5851     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5852
5853   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5854     VolatileOptionID = A->getOption().getID();
5855
5856   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5857     CmdArgs.push_back("-fms-volatile");
5858
5859   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5860   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5861   if (MostGeneralArg && BestCaseArg)
5862     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5863         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5864
5865   if (MostGeneralArg) {
5866     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5867     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5868     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5869
5870     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5871     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5872     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5873       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5874           << FirstConflict->getAsString(Args)
5875           << SecondConflict->getAsString(Args);
5876
5877     if (SingleArg)
5878       CmdArgs.push_back("-fms-memptr-rep=single");
5879     else if (MultipleArg)
5880       CmdArgs.push_back("-fms-memptr-rep=multiple");
5881     else
5882       CmdArgs.push_back("-fms-memptr-rep=virtual");
5883   }
5884
5885   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5886     A->render(Args, CmdArgs);
5887
5888   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5889     CmdArgs.push_back("-fdiagnostics-format");
5890     if (Args.hasArg(options::OPT__SLASH_fallback))
5891       CmdArgs.push_back("msvc-fallback");
5892     else
5893       CmdArgs.push_back("msvc");
5894   }
5895 }
5896
5897 visualstudio::Compiler *Clang::getCLFallback() const {
5898   if (!CLFallback)
5899     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5900   return CLFallback.get();
5901 }
5902
5903 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5904                                 ArgStringList &CmdArgs) const {
5905   StringRef CPUName;
5906   StringRef ABIName;
5907   const llvm::Triple &Triple = getToolChain().getTriple();
5908   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5909
5910   CmdArgs.push_back("-target-abi");
5911   CmdArgs.push_back(ABIName.data());
5912 }
5913
5914 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5915                            const InputInfo &Output, const InputInfoList &Inputs,
5916                            const ArgList &Args,
5917                            const char *LinkingOutput) const {
5918   ArgStringList CmdArgs;
5919
5920   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5921   const InputInfo &Input = Inputs[0];
5922
5923   std::string TripleStr =
5924       getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5925   const llvm::Triple Triple(TripleStr);
5926
5927   // Don't warn about "clang -w -c foo.s"
5928   Args.ClaimAllArgs(options::OPT_w);
5929   // and "clang -emit-llvm -c foo.s"
5930   Args.ClaimAllArgs(options::OPT_emit_llvm);
5931
5932   claimNoWarnArgs(Args);
5933
5934   // Invoke ourselves in -cc1as mode.
5935   //
5936   // FIXME: Implement custom jobs for internal actions.
5937   CmdArgs.push_back("-cc1as");
5938
5939   // Add the "effective" target triple.
5940   CmdArgs.push_back("-triple");
5941   CmdArgs.push_back(Args.MakeArgString(TripleStr));
5942
5943   // Set the output mode, we currently only expect to be used as a real
5944   // assembler.
5945   CmdArgs.push_back("-filetype");
5946   CmdArgs.push_back("obj");
5947
5948   // Set the main file name, so that debug info works even with
5949   // -save-temps or preprocessed assembly.
5950   CmdArgs.push_back("-main-file-name");
5951   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5952
5953   // Add the target cpu
5954   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5955   if (!CPU.empty()) {
5956     CmdArgs.push_back("-target-cpu");
5957     CmdArgs.push_back(Args.MakeArgString(CPU));
5958   }
5959
5960   // Add the target features
5961   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5962
5963   // Ignore explicit -force_cpusubtype_ALL option.
5964   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5965
5966   // Pass along any -I options so we get proper .include search paths.
5967   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5968
5969   // Determine the original source input.
5970   const Action *SourceAction = &JA;
5971   while (SourceAction->getKind() != Action::InputClass) {
5972     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5973     SourceAction = SourceAction->getInputs()[0];
5974   }
5975
5976   // Forward -g and handle debug info related flags, assuming we are dealing
5977   // with an actual assembly file.
5978   if (SourceAction->getType() == types::TY_Asm ||
5979       SourceAction->getType() == types::TY_PP_Asm) {
5980     bool WantDebug = false;
5981     unsigned DwarfVersion = 0;
5982     Args.ClaimAllArgs(options::OPT_g_Group);
5983     if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5984       WantDebug = !A->getOption().matches(options::OPT_g0) &&
5985         !A->getOption().matches(options::OPT_ggdb0);
5986       if (WantDebug)
5987         DwarfVersion = DwarfVersionNum(A->getSpelling());
5988     }
5989     if (DwarfVersion == 0)
5990       DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5991     RenderDebugEnablingArgs(Args, CmdArgs,
5992                             (WantDebug ? CodeGenOptions::LimitedDebugInfo
5993                                        : CodeGenOptions::NoDebugInfo),
5994                             DwarfVersion, llvm::DebuggerKind::Default);
5995
5996     // Add the -fdebug-compilation-dir flag if needed.
5997     addDebugCompDirArg(Args, CmdArgs);
5998
5999     // Set the AT_producer to the clang version when using the integrated
6000     // assembler on assembly source files.
6001     CmdArgs.push_back("-dwarf-debug-producer");
6002     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6003
6004     // And pass along -I options
6005     Args.AddAllArgs(CmdArgs, options::OPT_I);
6006   }
6007
6008   // Handle -fPIC et al -- the relocation-model affects the assembler
6009   // for some targets.
6010   llvm::Reloc::Model RelocationModel;
6011   unsigned PICLevel;
6012   bool IsPIE;
6013   std::tie(RelocationModel, PICLevel, IsPIE) =
6014       ParsePICArgs(getToolChain(), Triple, Args);
6015
6016   const char *RMName = RelocationModelName(RelocationModel);
6017   if (RMName) {
6018     CmdArgs.push_back("-mrelocation-model");
6019     CmdArgs.push_back(RMName);
6020   }
6021
6022   // Optionally embed the -cc1as level arguments into the debug info, for build
6023   // analysis.
6024   if (getToolChain().UseDwarfDebugFlags()) {
6025     ArgStringList OriginalArgs;
6026     for (const auto &Arg : Args)
6027       Arg->render(Args, OriginalArgs);
6028
6029     SmallString<256> Flags;
6030     const char *Exec = getToolChain().getDriver().getClangProgramPath();
6031     Flags += Exec;
6032     for (const char *OriginalArg : OriginalArgs) {
6033       SmallString<128> EscapedArg;
6034       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6035       Flags += " ";
6036       Flags += EscapedArg;
6037     }
6038     CmdArgs.push_back("-dwarf-debug-flags");
6039     CmdArgs.push_back(Args.MakeArgString(Flags));
6040   }
6041
6042   // FIXME: Add -static support, once we have it.
6043
6044   // Add target specific flags.
6045   switch (getToolChain().getArch()) {
6046   default:
6047     break;
6048
6049   case llvm::Triple::mips:
6050   case llvm::Triple::mipsel:
6051   case llvm::Triple::mips64:
6052   case llvm::Triple::mips64el:
6053     AddMIPSTargetArgs(Args, CmdArgs);
6054     break;
6055   }
6056
6057   // Consume all the warning flags. Usually this would be handled more
6058   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6059   // doesn't handle that so rather than warning about unused flags that are
6060   // actually used, we'll lie by omission instead.
6061   // FIXME: Stop lying and consume only the appropriate driver flags
6062   Args.ClaimAllArgs(options::OPT_W_Group);
6063
6064   // Assemblers that want to know the dwarf version can't assume a value,
6065   // since the defaulting logic resides in the driver. Put in something
6066   // reasonable now, in case a subsequent "-Wa,-g" changes it.
6067   RenderDebugEnablingArgs(Args, CmdArgs, CodeGenOptions::NoDebugInfo,
6068                           getToolChain().GetDefaultDwarfVersion(),
6069                           llvm::DebuggerKind::Default);
6070   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6071                                     getToolChain().getDriver());
6072
6073   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6074
6075   assert(Output.isFilename() && "Unexpected lipo output.");
6076   CmdArgs.push_back("-o");
6077   CmdArgs.push_back(Output.getFilename());
6078
6079   assert(Input.isFilename() && "Invalid input.");
6080   CmdArgs.push_back(Input.getFilename());
6081
6082   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6083   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6084
6085   // Handle the debug info splitting at object creation time if we're
6086   // creating an object.
6087   // TODO: Currently only works on linux with newer objcopy.
6088   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6089       getToolChain().getTriple().isOSLinux())
6090     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6091                    SplitDebugName(Args, Input));
6092 }
6093
6094 void GnuTool::anchor() {}
6095
6096 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6097                                const InputInfo &Output,
6098                                const InputInfoList &Inputs, const ArgList &Args,
6099                                const char *LinkingOutput) const {
6100   const Driver &D = getToolChain().getDriver();
6101   ArgStringList CmdArgs;
6102
6103   for (const auto &A : Args) {
6104     if (forwardToGCC(A->getOption())) {
6105       // It is unfortunate that we have to claim here, as this means
6106       // we will basically never report anything interesting for
6107       // platforms using a generic gcc, even if we are just using gcc
6108       // to get to the assembler.
6109       A->claim();
6110
6111       // Don't forward any -g arguments to assembly steps.
6112       if (isa<AssembleJobAction>(JA) &&
6113           A->getOption().matches(options::OPT_g_Group))
6114         continue;
6115
6116       // Don't forward any -W arguments to assembly and link steps.
6117       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6118           A->getOption().matches(options::OPT_W_Group))
6119         continue;
6120
6121       A->render(Args, CmdArgs);
6122     }
6123   }
6124
6125   RenderExtraToolArgs(JA, CmdArgs);
6126
6127   // If using a driver driver, force the arch.
6128   if (getToolChain().getTriple().isOSDarwin()) {
6129     CmdArgs.push_back("-arch");
6130     CmdArgs.push_back(
6131         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6132   }
6133
6134   // Try to force gcc to match the tool chain we want, if we recognize
6135   // the arch.
6136   //
6137   // FIXME: The triple class should directly provide the information we want
6138   // here.
6139   switch (getToolChain().getArch()) {
6140   default:
6141     break;
6142   case llvm::Triple::x86:
6143   case llvm::Triple::ppc:
6144     CmdArgs.push_back("-m32");
6145     break;
6146   case llvm::Triple::x86_64:
6147   case llvm::Triple::ppc64:
6148   case llvm::Triple::ppc64le:
6149     CmdArgs.push_back("-m64");
6150     break;
6151   case llvm::Triple::sparcel:
6152     CmdArgs.push_back("-EL");
6153     break;
6154   }
6155
6156   if (Output.isFilename()) {
6157     CmdArgs.push_back("-o");
6158     CmdArgs.push_back(Output.getFilename());
6159   } else {
6160     assert(Output.isNothing() && "Unexpected output");
6161     CmdArgs.push_back("-fsyntax-only");
6162   }
6163
6164   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6165
6166   // Only pass -x if gcc will understand it; otherwise hope gcc
6167   // understands the suffix correctly. The main use case this would go
6168   // wrong in is for linker inputs if they happened to have an odd
6169   // suffix; really the only way to get this to happen is a command
6170   // like '-x foobar a.c' which will treat a.c like a linker input.
6171   //
6172   // FIXME: For the linker case specifically, can we safely convert
6173   // inputs into '-Wl,' options?
6174   for (const auto &II : Inputs) {
6175     // Don't try to pass LLVM or AST inputs to a generic gcc.
6176     if (types::isLLVMIR(II.getType()))
6177       D.Diag(diag::err_drv_no_linker_llvm_support)
6178           << getToolChain().getTripleString();
6179     else if (II.getType() == types::TY_AST)
6180       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6181     else if (II.getType() == types::TY_ModuleFile)
6182       D.Diag(diag::err_drv_no_module_support)
6183           << getToolChain().getTripleString();
6184
6185     if (types::canTypeBeUserSpecified(II.getType())) {
6186       CmdArgs.push_back("-x");
6187       CmdArgs.push_back(types::getTypeName(II.getType()));
6188     }
6189
6190     if (II.isFilename())
6191       CmdArgs.push_back(II.getFilename());
6192     else {
6193       const Arg &A = II.getInputArg();
6194
6195       // Reverse translate some rewritten options.
6196       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6197         CmdArgs.push_back("-lstdc++");
6198         continue;
6199       }
6200
6201       // Don't render as input, we need gcc to do the translations.
6202       A.render(Args, CmdArgs);
6203     }
6204   }
6205
6206   const std::string customGCCName = D.getCCCGenericGCCName();
6207   const char *GCCName;
6208   if (!customGCCName.empty())
6209     GCCName = customGCCName.c_str();
6210   else if (D.CCCIsCXX()) {
6211     GCCName = "g++";
6212   } else
6213     GCCName = "gcc";
6214
6215   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6216   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6217 }
6218
6219 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6220                                             ArgStringList &CmdArgs) const {
6221   CmdArgs.push_back("-E");
6222 }
6223
6224 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6225                                         ArgStringList &CmdArgs) const {
6226   const Driver &D = getToolChain().getDriver();
6227
6228   switch (JA.getType()) {
6229   // If -flto, etc. are present then make sure not to force assembly output.
6230   case types::TY_LLVM_IR:
6231   case types::TY_LTO_IR:
6232   case types::TY_LLVM_BC:
6233   case types::TY_LTO_BC:
6234     CmdArgs.push_back("-c");
6235     break;
6236   // We assume we've got an "integrated" assembler in that gcc will produce an
6237   // object file itself.
6238   case types::TY_Object:
6239     CmdArgs.push_back("-c");
6240     break;
6241   case types::TY_PP_Asm:
6242     CmdArgs.push_back("-S");
6243     break;
6244   case types::TY_Nothing:
6245     CmdArgs.push_back("-fsyntax-only");
6246     break;
6247   default:
6248     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6249   }
6250 }
6251
6252 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6253                                       ArgStringList &CmdArgs) const {
6254   // The types are (hopefully) good enough.
6255 }
6256
6257 // Hexagon tools start.
6258 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6259                                              ArgStringList &CmdArgs) const {
6260 }
6261
6262 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6263                                       const InputInfo &Output,
6264                                       const InputInfoList &Inputs,
6265                                       const ArgList &Args,
6266                                       const char *LinkingOutput) const {
6267   claimNoWarnArgs(Args);
6268
6269   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6270   const Driver &D = HTC.getDriver();
6271   ArgStringList CmdArgs;
6272
6273   std::string MArchString = "-march=hexagon";
6274   CmdArgs.push_back(Args.MakeArgString(MArchString));
6275
6276   RenderExtraToolArgs(JA, CmdArgs);
6277
6278   std::string AsName = "hexagon-llvm-mc";
6279   std::string MCpuString = "-mcpu=hexagon" +
6280         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6281   CmdArgs.push_back("-filetype=obj");
6282   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6283
6284   if (Output.isFilename()) {
6285     CmdArgs.push_back("-o");
6286     CmdArgs.push_back(Output.getFilename());
6287   } else {
6288     assert(Output.isNothing() && "Unexpected output");
6289     CmdArgs.push_back("-fsyntax-only");
6290   }
6291
6292   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6293     std::string N = llvm::utostr(G.getValue());
6294     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6295   }
6296
6297   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6298
6299   // Only pass -x if gcc will understand it; otherwise hope gcc
6300   // understands the suffix correctly. The main use case this would go
6301   // wrong in is for linker inputs if they happened to have an odd
6302   // suffix; really the only way to get this to happen is a command
6303   // like '-x foobar a.c' which will treat a.c like a linker input.
6304   //
6305   // FIXME: For the linker case specifically, can we safely convert
6306   // inputs into '-Wl,' options?
6307   for (const auto &II : Inputs) {
6308     // Don't try to pass LLVM or AST inputs to a generic gcc.
6309     if (types::isLLVMIR(II.getType()))
6310       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6311           << HTC.getTripleString();
6312     else if (II.getType() == types::TY_AST)
6313       D.Diag(clang::diag::err_drv_no_ast_support)
6314           << HTC.getTripleString();
6315     else if (II.getType() == types::TY_ModuleFile)
6316       D.Diag(diag::err_drv_no_module_support)
6317           << HTC.getTripleString();
6318
6319     if (II.isFilename())
6320       CmdArgs.push_back(II.getFilename());
6321     else
6322       // Don't render as input, we need gcc to do the translations.
6323       // FIXME: What is this?
6324       II.getInputArg().render(Args, CmdArgs);
6325   }
6326
6327   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6328   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6329 }
6330
6331 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6332                                           ArgStringList &CmdArgs) const {
6333 }
6334
6335 static void
6336 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6337                          const toolchains::HexagonToolChain &HTC,
6338                          const InputInfo &Output, const InputInfoList &Inputs,
6339                          const ArgList &Args, ArgStringList &CmdArgs,
6340                          const char *LinkingOutput) {
6341
6342   const Driver &D = HTC.getDriver();
6343
6344   //----------------------------------------------------------------------------
6345   //
6346   //----------------------------------------------------------------------------
6347   bool IsStatic = Args.hasArg(options::OPT_static);
6348   bool IsShared = Args.hasArg(options::OPT_shared);
6349   bool IsPIE = Args.hasArg(options::OPT_pie);
6350   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6351   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6352   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6353   bool UseG0 = false;
6354   bool UseShared = IsShared && !IsStatic;
6355
6356   //----------------------------------------------------------------------------
6357   // Silence warnings for various options
6358   //----------------------------------------------------------------------------
6359   Args.ClaimAllArgs(options::OPT_g_Group);
6360   Args.ClaimAllArgs(options::OPT_emit_llvm);
6361   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6362                                      // handled somewhere else.
6363   Args.ClaimAllArgs(options::OPT_static_libgcc);
6364
6365   //----------------------------------------------------------------------------
6366   //
6367   //----------------------------------------------------------------------------
6368   if (Args.hasArg(options::OPT_s))
6369     CmdArgs.push_back("-s");
6370
6371   if (Args.hasArg(options::OPT_r))
6372     CmdArgs.push_back("-r");
6373
6374   for (const auto &Opt : HTC.ExtraOpts)
6375     CmdArgs.push_back(Opt.c_str());
6376
6377   CmdArgs.push_back("-march=hexagon");
6378   std::string CpuVer =
6379         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6380   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6381   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6382
6383   if (IsShared) {
6384     CmdArgs.push_back("-shared");
6385     // The following should be the default, but doing as hexagon-gcc does.
6386     CmdArgs.push_back("-call_shared");
6387   }
6388
6389   if (IsStatic)
6390     CmdArgs.push_back("-static");
6391
6392   if (IsPIE && !IsShared)
6393     CmdArgs.push_back("-pie");
6394
6395   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6396     std::string N = llvm::utostr(G.getValue());
6397     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6398     UseG0 = G.getValue() == 0;
6399   }
6400
6401   //----------------------------------------------------------------------------
6402   //
6403   //----------------------------------------------------------------------------
6404   CmdArgs.push_back("-o");
6405   CmdArgs.push_back(Output.getFilename());
6406
6407   //----------------------------------------------------------------------------
6408   // moslib
6409   //----------------------------------------------------------------------------
6410   std::vector<std::string> OsLibs;
6411   bool HasStandalone = false;
6412
6413   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6414     A->claim();
6415     OsLibs.emplace_back(A->getValue());
6416     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6417   }
6418   if (OsLibs.empty()) {
6419     OsLibs.push_back("standalone");
6420     HasStandalone = true;
6421   }
6422
6423   //----------------------------------------------------------------------------
6424   // Start Files
6425   //----------------------------------------------------------------------------
6426   const std::string MCpuSuffix = "/" + CpuVer;
6427   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6428   const std::string RootDir =
6429       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6430   const std::string StartSubDir =
6431       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6432
6433   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6434                       const char *Name) -> std::string {
6435     std::string RelName = SubDir + Name;
6436     std::string P = HTC.GetFilePath(RelName.c_str());
6437     if (llvm::sys::fs::exists(P))
6438       return P;
6439     return RootDir + RelName;
6440   };
6441
6442   if (IncStdLib && IncStartFiles) {
6443     if (!IsShared) {
6444       if (HasStandalone) {
6445         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6446         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6447       }
6448       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6449       CmdArgs.push_back(Args.MakeArgString(Crt0));
6450     }
6451     std::string Init = UseShared
6452           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6453           : Find(RootDir, StartSubDir, "/init.o");
6454     CmdArgs.push_back(Args.MakeArgString(Init));
6455   }
6456
6457   //----------------------------------------------------------------------------
6458   // Library Search Paths
6459   //----------------------------------------------------------------------------
6460   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6461   for (const auto &LibPath : LibPaths)
6462     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6463
6464   //----------------------------------------------------------------------------
6465   //
6466   //----------------------------------------------------------------------------
6467   Args.AddAllArgs(CmdArgs,
6468                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6469                    options::OPT_t, options::OPT_u_Group});
6470
6471   AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6472
6473   //----------------------------------------------------------------------------
6474   // Libraries
6475   //----------------------------------------------------------------------------
6476   if (IncStdLib && IncDefLibs) {
6477     if (D.CCCIsCXX()) {
6478       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6479       CmdArgs.push_back("-lm");
6480     }
6481
6482     CmdArgs.push_back("--start-group");
6483
6484     if (!IsShared) {
6485       for (const std::string &Lib : OsLibs)
6486         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6487       CmdArgs.push_back("-lc");
6488     }
6489     CmdArgs.push_back("-lgcc");
6490
6491     CmdArgs.push_back("--end-group");
6492   }
6493
6494   //----------------------------------------------------------------------------
6495   // End files
6496   //----------------------------------------------------------------------------
6497   if (IncStdLib && IncStartFiles) {
6498     std::string Fini = UseShared
6499           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6500           : Find(RootDir, StartSubDir, "/fini.o");
6501     CmdArgs.push_back(Args.MakeArgString(Fini));
6502   }
6503 }
6504
6505 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6506                                    const InputInfo &Output,
6507                                    const InputInfoList &Inputs,
6508                                    const ArgList &Args,
6509                                    const char *LinkingOutput) const {
6510   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6511
6512   ArgStringList CmdArgs;
6513   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6514                            LinkingOutput);
6515
6516   std::string Linker = HTC.GetProgramPath("hexagon-link");
6517   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6518                                           CmdArgs, Inputs));
6519 }
6520 // Hexagon tools end.
6521
6522 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6523                                   const InputInfo &Output,
6524                                   const InputInfoList &Inputs,
6525                                   const ArgList &Args,
6526                                   const char *LinkingOutput) const {
6527
6528   std::string Linker = getToolChain().GetProgramPath(getShortName());
6529   ArgStringList CmdArgs;
6530   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6531   CmdArgs.push_back("-o");
6532   CmdArgs.push_back(Output.getFilename());
6533   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6534                                           CmdArgs, Inputs));
6535 }
6536 // AMDGPU tools end.
6537
6538 wasm::Linker::Linker(const ToolChain &TC)
6539   : GnuTool("wasm::Linker", "lld", TC) {}
6540
6541 bool wasm::Linker::isLinkJob() const {
6542   return true;
6543 }
6544
6545 bool wasm::Linker::hasIntegratedCPP() const {
6546   return false;
6547 }
6548
6549 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6550                                 const InputInfo &Output,
6551                                 const InputInfoList &Inputs,
6552                                 const ArgList &Args,
6553                                 const char *LinkingOutput) const {
6554   const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6555   ArgStringList CmdArgs;
6556   CmdArgs.push_back("-flavor");
6557   CmdArgs.push_back("ld");
6558
6559   // Enable garbage collection of unused input sections by default, since code
6560   // size is of particular importance. This is significantly facilitated by
6561   // the enabling of -ffunction-sections and -fdata-sections in
6562   // Clang::ConstructJob.
6563   if (areOptimizationsEnabled(Args))
6564     CmdArgs.push_back("--gc-sections");
6565
6566   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6567   CmdArgs.push_back("-o");
6568   CmdArgs.push_back(Output.getFilename());
6569   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6570 }
6571
6572 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6573   std::string MArch;
6574   if (!Arch.empty())
6575     MArch = Arch;
6576   else
6577     MArch = Triple.getArchName();
6578   MArch = StringRef(MArch).split("+").first.lower();
6579
6580   // Handle -march=native.
6581   if (MArch == "native") {
6582     std::string CPU = llvm::sys::getHostCPUName();
6583     if (CPU != "generic") {
6584       // Translate the native cpu into the architecture suffix for that CPU.
6585       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6586       // If there is no valid architecture suffix for this CPU we don't know how
6587       // to handle it, so return no architecture.
6588       if (Suffix.empty())
6589         MArch = "";
6590       else
6591         MArch = std::string("arm") + Suffix.str();
6592     }
6593   }
6594
6595   return MArch;
6596 }
6597
6598 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6599 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6600   std::string MArch = getARMArch(Arch, Triple);
6601   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6602   // here means an -march=native that we can't handle, so instead return no CPU.
6603   if (MArch.empty())
6604     return StringRef();
6605
6606   // We need to return an empty string here on invalid MArch values as the
6607   // various places that call this function can't cope with a null result.
6608   return Triple.getARMCPUForArch(MArch);
6609 }
6610
6611 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6612 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6613                                  const llvm::Triple &Triple) {
6614   // FIXME: Warn on inconsistent use of -mcpu and -march.
6615   // If we have -mcpu=, use that.
6616   if (!CPU.empty()) {
6617     std::string MCPU = StringRef(CPU).split("+").first.lower();
6618     // Handle -mcpu=native.
6619     if (MCPU == "native")
6620       return llvm::sys::getHostCPUName();
6621     else
6622       return MCPU;
6623   }
6624
6625   return getARMCPUForMArch(Arch, Triple);
6626 }
6627
6628 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6629 /// CPU  (or Arch, if CPU is generic).
6630 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6631 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6632                                        const llvm::Triple &Triple) {
6633   unsigned ArchKind;
6634   if (CPU == "generic") {
6635     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6636     ArchKind = llvm::ARM::parseArch(ARMArch);
6637     if (ArchKind == llvm::ARM::AK_INVALID)
6638       // In case of generic Arch, i.e. "arm",
6639       // extract arch from default cpu of the Triple
6640       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6641   } else {
6642     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6643     // armv7k triple if it's actually been specified via "-arch armv7k".
6644     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6645                           ? (unsigned)llvm::ARM::AK_ARMV7K
6646                           : llvm::ARM::parseCPUArch(CPU);
6647   }
6648   if (ArchKind == llvm::ARM::AK_INVALID)
6649     return "";
6650   return llvm::ARM::getSubArch(ArchKind);
6651 }
6652
6653 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6654                             const llvm::Triple &Triple) {
6655   if (Args.hasArg(options::OPT_r))
6656     return;
6657
6658   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6659   // to generate BE-8 executables.
6660   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6661     CmdArgs.push_back("--be8");
6662 }
6663
6664 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6665   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6666   // was first introduced in Release 3. However, other compilers have
6667   // traditionally allowed it for Release 2 so we should do the same.
6668   return (NanEncoding)llvm::StringSwitch<int>(CPU)
6669       .Case("mips1", NanLegacy)
6670       .Case("mips2", NanLegacy)
6671       .Case("mips3", NanLegacy)
6672       .Case("mips4", NanLegacy)
6673       .Case("mips5", NanLegacy)
6674       .Case("mips32", NanLegacy)
6675       .Case("mips32r2", NanLegacy | Nan2008)
6676       .Case("mips32r3", NanLegacy | Nan2008)
6677       .Case("mips32r5", NanLegacy | Nan2008)
6678       .Case("mips32r6", Nan2008)
6679       .Case("mips64", NanLegacy)
6680       .Case("mips64r2", NanLegacy | Nan2008)
6681       .Case("mips64r3", NanLegacy | Nan2008)
6682       .Case("mips64r5", NanLegacy | Nan2008)
6683       .Case("mips64r6", Nan2008)
6684       .Default(NanLegacy);
6685 }
6686
6687 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6688   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6689   return A && (A->getValue() == StringRef(Value));
6690 }
6691
6692 bool mips::isUCLibc(const ArgList &Args) {
6693   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6694   return A && A->getOption().matches(options::OPT_muclibc);
6695 }
6696
6697 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6698   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6699     return llvm::StringSwitch<bool>(NaNArg->getValue())
6700         .Case("2008", true)
6701         .Case("legacy", false)
6702         .Default(false);
6703
6704   // NaN2008 is the default for MIPS32r6/MIPS64r6.
6705   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6706       .Cases("mips32r6", "mips64r6", true)
6707       .Default(false);
6708
6709   return false;
6710 }
6711
6712 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6713                          StringRef ABIName, mips::FloatABI FloatABI) {
6714   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6715       Triple.getVendor() != llvm::Triple::MipsTechnologies)
6716     return false;
6717
6718   if (ABIName != "32")
6719     return false;
6720
6721   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6722   // present.
6723   if (FloatABI == mips::FloatABI::Soft)
6724     return false;
6725
6726   return llvm::StringSwitch<bool>(CPUName)
6727       .Cases("mips2", "mips3", "mips4", "mips5", true)
6728       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6729       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6730       .Default(false);
6731 }
6732
6733 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6734                          StringRef CPUName, StringRef ABIName,
6735                          mips::FloatABI FloatABI) {
6736   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6737
6738   // FPXX shouldn't be used if -msingle-float is present.
6739   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6740                                options::OPT_mdouble_float))
6741     if (A->getOption().matches(options::OPT_msingle_float))
6742       UseFPXX = false;
6743
6744   return UseFPXX;
6745 }
6746
6747 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6748   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6749   // archs which Darwin doesn't use.
6750
6751   // The matching this routine does is fairly pointless, since it is neither the
6752   // complete architecture list, nor a reasonable subset. The problem is that
6753   // historically the driver driver accepts this and also ties its -march=
6754   // handling to the architecture name, so we need to be careful before removing
6755   // support for it.
6756
6757   // This code must be kept in sync with Clang's Darwin specific argument
6758   // translation.
6759
6760   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6761       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6762       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6763       .Case("ppc64", llvm::Triple::ppc64)
6764       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6765       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6766              llvm::Triple::x86)
6767       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6768       // This is derived from the driver driver.
6769       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6770       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6771       .Cases("armv7s", "xscale", llvm::Triple::arm)
6772       .Case("arm64", llvm::Triple::aarch64)
6773       .Case("r600", llvm::Triple::r600)
6774       .Case("amdgcn", llvm::Triple::amdgcn)
6775       .Case("nvptx", llvm::Triple::nvptx)
6776       .Case("nvptx64", llvm::Triple::nvptx64)
6777       .Case("amdil", llvm::Triple::amdil)
6778       .Case("spir", llvm::Triple::spir)
6779       .Default(llvm::Triple::UnknownArch);
6780 }
6781
6782 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6783   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6784   T.setArch(Arch);
6785
6786   if (Str == "x86_64h")
6787     T.setArchName(Str);
6788   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6789     T.setOS(llvm::Triple::UnknownOS);
6790     T.setObjectFormat(llvm::Triple::MachO);
6791   }
6792 }
6793
6794 const char *Clang::getBaseInputName(const ArgList &Args,
6795                                     const InputInfo &Input) {
6796   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6797 }
6798
6799 const char *Clang::getBaseInputStem(const ArgList &Args,
6800                                     const InputInfoList &Inputs) {
6801   const char *Str = getBaseInputName(Args, Inputs[0]);
6802
6803   if (const char *End = strrchr(Str, '.'))
6804     return Args.MakeArgString(std::string(Str, End));
6805
6806   return Str;
6807 }
6808
6809 const char *Clang::getDependencyFileName(const ArgList &Args,
6810                                          const InputInfoList &Inputs) {
6811   // FIXME: Think about this more.
6812   std::string Res;
6813
6814   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6815     std::string Str(OutputOpt->getValue());
6816     Res = Str.substr(0, Str.rfind('.'));
6817   } else {
6818     Res = getBaseInputStem(Args, Inputs);
6819   }
6820   return Args.MakeArgString(Res + ".d");
6821 }
6822
6823 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6824                                     const InputInfo &Output,
6825                                     const InputInfoList &Inputs,
6826                                     const ArgList &Args,
6827                                     const char *LinkingOutput) const {
6828   const ToolChain &ToolChain = getToolChain();
6829   const Driver &D = ToolChain.getDriver();
6830   ArgStringList CmdArgs;
6831
6832   // Silence warning for "clang -g foo.o -o foo"
6833   Args.ClaimAllArgs(options::OPT_g_Group);
6834   // and "clang -emit-llvm foo.o -o foo"
6835   Args.ClaimAllArgs(options::OPT_emit_llvm);
6836   // and for "clang -w foo.o -o foo". Other warning options are already
6837   // handled somewhere else.
6838   Args.ClaimAllArgs(options::OPT_w);
6839
6840   if (!D.SysRoot.empty())
6841     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6842
6843   // CloudABI only supports static linkage.
6844   CmdArgs.push_back("-Bstatic");
6845   CmdArgs.push_back("--eh-frame-hdr");
6846   CmdArgs.push_back("--gc-sections");
6847
6848   if (Output.isFilename()) {
6849     CmdArgs.push_back("-o");
6850     CmdArgs.push_back(Output.getFilename());
6851   } else {
6852     assert(Output.isNothing() && "Invalid output.");
6853   }
6854
6855   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6856     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6857     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6858   }
6859
6860   Args.AddAllArgs(CmdArgs, options::OPT_L);
6861   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6862   Args.AddAllArgs(CmdArgs,
6863                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6864                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6865
6866   if (D.isUsingLTO())
6867     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6868
6869   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6870
6871   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6872     if (D.CCCIsCXX())
6873       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6874     CmdArgs.push_back("-lc");
6875     CmdArgs.push_back("-lcompiler_rt");
6876   }
6877
6878   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6879     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6880
6881   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6882   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6883 }
6884
6885 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6886                                      const InputInfo &Output,
6887                                      const InputInfoList &Inputs,
6888                                      const ArgList &Args,
6889                                      const char *LinkingOutput) const {
6890   ArgStringList CmdArgs;
6891
6892   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6893   const InputInfo &Input = Inputs[0];
6894
6895   // Determine the original source input.
6896   const Action *SourceAction = &JA;
6897   while (SourceAction->getKind() != Action::InputClass) {
6898     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6899     SourceAction = SourceAction->getInputs()[0];
6900   }
6901
6902   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6903   // sure it runs its system assembler not clang's integrated assembler.
6904   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
6905   // FIXME: at run-time detect assembler capabilities or rely on version
6906   // information forwarded by -target-assembler-version.
6907   if (Args.hasArg(options::OPT_fno_integrated_as)) {
6908     const llvm::Triple &T(getToolChain().getTriple());
6909     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6910       CmdArgs.push_back("-Q");
6911   }
6912
6913   // Forward -g, assuming we are dealing with an actual assembly file.
6914   if (SourceAction->getType() == types::TY_Asm ||
6915       SourceAction->getType() == types::TY_PP_Asm) {
6916     if (Args.hasArg(options::OPT_gstabs))
6917       CmdArgs.push_back("--gstabs");
6918     else if (Args.hasArg(options::OPT_g_Group))
6919       CmdArgs.push_back("-g");
6920   }
6921
6922   // Derived from asm spec.
6923   AddMachOArch(Args, CmdArgs);
6924
6925   // Use -force_cpusubtype_ALL on x86 by default.
6926   if (getToolChain().getArch() == llvm::Triple::x86 ||
6927       getToolChain().getArch() == llvm::Triple::x86_64 ||
6928       Args.hasArg(options::OPT_force__cpusubtype__ALL))
6929     CmdArgs.push_back("-force_cpusubtype_ALL");
6930
6931   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6932       (((Args.hasArg(options::OPT_mkernel) ||
6933          Args.hasArg(options::OPT_fapple_kext)) &&
6934         getMachOToolChain().isKernelStatic()) ||
6935        Args.hasArg(options::OPT_static)))
6936     CmdArgs.push_back("-static");
6937
6938   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6939
6940   assert(Output.isFilename() && "Unexpected lipo output.");
6941   CmdArgs.push_back("-o");
6942   CmdArgs.push_back(Output.getFilename());
6943
6944   assert(Input.isFilename() && "Invalid input.");
6945   CmdArgs.push_back(Input.getFilename());
6946
6947   // asm_final spec is empty.
6948
6949   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6950   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6951 }
6952
6953 void darwin::MachOTool::anchor() {}
6954
6955 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6956                                      ArgStringList &CmdArgs) const {
6957   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6958
6959   // Derived from darwin_arch spec.
6960   CmdArgs.push_back("-arch");
6961   CmdArgs.push_back(Args.MakeArgString(ArchName));
6962
6963   // FIXME: Is this needed anymore?
6964   if (ArchName == "arm")
6965     CmdArgs.push_back("-force_cpusubtype_ALL");
6966 }
6967
6968 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6969   // We only need to generate a temp path for LTO if we aren't compiling object
6970   // files. When compiling source files, we run 'dsymutil' after linking. We
6971   // don't run 'dsymutil' when compiling object files.
6972   for (const auto &Input : Inputs)
6973     if (Input.getType() != types::TY_Object)
6974       return true;
6975
6976   return false;
6977 }
6978
6979 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6980                                  ArgStringList &CmdArgs,
6981                                  const InputInfoList &Inputs) const {
6982   const Driver &D = getToolChain().getDriver();
6983   const toolchains::MachO &MachOTC = getMachOToolChain();
6984
6985   unsigned Version[3] = {0, 0, 0};
6986   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6987     bool HadExtra;
6988     if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6989                                    Version[2], HadExtra) ||
6990         HadExtra)
6991       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6992   }
6993
6994   // Newer linkers support -demangle. Pass it if supported and not disabled by
6995   // the user.
6996   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6997     CmdArgs.push_back("-demangle");
6998
6999   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7000     CmdArgs.push_back("-export_dynamic");
7001
7002   // If we are using App Extension restrictions, pass a flag to the linker
7003   // telling it that the compiled code has been audited.
7004   if (Args.hasFlag(options::OPT_fapplication_extension,
7005                    options::OPT_fno_application_extension, false))
7006     CmdArgs.push_back("-application_extension");
7007
7008   if (D.isUsingLTO()) {
7009     // If we are using LTO, then automatically create a temporary file path for
7010     // the linker to use, so that it's lifetime will extend past a possible
7011     // dsymutil step.
7012     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7013       const char *TmpPath = C.getArgs().MakeArgString(
7014           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7015       C.addTempFile(TmpPath);
7016       CmdArgs.push_back("-object_path_lto");
7017       CmdArgs.push_back(TmpPath);
7018     }
7019
7020     // Use -lto_library option to specify the libLTO.dylib path. Try to find
7021     // it in clang installed libraries. If not found, the option is not used
7022     // and 'ld' will use its default mechanism to search for libLTO.dylib.
7023     if (Version[0] >= 133) {
7024       // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7025       StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7026       SmallString<128> LibLTOPath(P);
7027       llvm::sys::path::append(LibLTOPath, "lib");
7028       llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7029       if (llvm::sys::fs::exists(LibLTOPath)) {
7030         CmdArgs.push_back("-lto_library");
7031         CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7032       } else {
7033         D.Diag(diag::warn_drv_lto_libpath);
7034       }
7035     }
7036   }
7037
7038   // Derived from the "link" spec.
7039   Args.AddAllArgs(CmdArgs, options::OPT_static);
7040   if (!Args.hasArg(options::OPT_static))
7041     CmdArgs.push_back("-dynamic");
7042   if (Args.hasArg(options::OPT_fgnu_runtime)) {
7043     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7044     // here. How do we wish to handle such things?
7045   }
7046
7047   if (!Args.hasArg(options::OPT_dynamiclib)) {
7048     AddMachOArch(Args, CmdArgs);
7049     // FIXME: Why do this only on this path?
7050     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7051
7052     Args.AddLastArg(CmdArgs, options::OPT_bundle);
7053     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7054     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7055
7056     Arg *A;
7057     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7058         (A = Args.getLastArg(options::OPT_current__version)) ||
7059         (A = Args.getLastArg(options::OPT_install__name)))
7060       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7061                                                        << "-dynamiclib";
7062
7063     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7064     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7065     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7066   } else {
7067     CmdArgs.push_back("-dylib");
7068
7069     Arg *A;
7070     if ((A = Args.getLastArg(options::OPT_bundle)) ||
7071         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7072         (A = Args.getLastArg(options::OPT_client__name)) ||
7073         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7074         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7075         (A = Args.getLastArg(options::OPT_private__bundle)))
7076       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7077                                                       << "-dynamiclib";
7078
7079     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7080                               "-dylib_compatibility_version");
7081     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7082                               "-dylib_current_version");
7083
7084     AddMachOArch(Args, CmdArgs);
7085
7086     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7087                               "-dylib_install_name");
7088   }
7089
7090   Args.AddLastArg(CmdArgs, options::OPT_all__load);
7091   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7092   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7093   if (MachOTC.isTargetIOSBased())
7094     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7095   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7096   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7097   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7098   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7099   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7100   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7101   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7102   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7103   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7104   Args.AddAllArgs(CmdArgs, options::OPT_init);
7105
7106   // Add the deployment target.
7107   MachOTC.addMinVersionArgs(Args, CmdArgs);
7108
7109   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7110   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7111   Args.AddLastArg(CmdArgs, options::OPT_single__module);
7112   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7113   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7114
7115   if (const Arg *A =
7116           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7117                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
7118     if (A->getOption().matches(options::OPT_fpie) ||
7119         A->getOption().matches(options::OPT_fPIE))
7120       CmdArgs.push_back("-pie");
7121     else
7122       CmdArgs.push_back("-no_pie");
7123   }
7124
7125   Args.AddLastArg(CmdArgs, options::OPT_prebind);
7126   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7127   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7128   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7129   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7130   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7131   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7132   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7133   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7134   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7135   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7136   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7137   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7138   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7139   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7140   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7141
7142   // Give --sysroot= preference, over the Apple specific behavior to also use
7143   // --isysroot as the syslibroot.
7144   StringRef sysroot = C.getSysRoot();
7145   if (sysroot != "") {
7146     CmdArgs.push_back("-syslibroot");
7147     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7148   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7149     CmdArgs.push_back("-syslibroot");
7150     CmdArgs.push_back(A->getValue());
7151   }
7152
7153   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7154   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7155   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7156   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7157   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7158   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7159   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7160   Args.AddAllArgs(CmdArgs, options::OPT_y);
7161   Args.AddLastArg(CmdArgs, options::OPT_w);
7162   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7163   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7164   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7165   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7166   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7167   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7168   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7169   Args.AddLastArg(CmdArgs, options::OPT_whyload);
7170   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7171   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7172   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7173   Args.AddLastArg(CmdArgs, options::OPT_Mach);
7174 }
7175
7176 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7177                                   const InputInfo &Output,
7178                                   const InputInfoList &Inputs,
7179                                   const ArgList &Args,
7180                                   const char *LinkingOutput) const {
7181   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7182
7183   // If the number of arguments surpasses the system limits, we will encode the
7184   // input files in a separate file, shortening the command line. To this end,
7185   // build a list of input file names that can be passed via a file with the
7186   // -filelist linker option.
7187   llvm::opt::ArgStringList InputFileList;
7188
7189   // The logic here is derived from gcc's behavior; most of which
7190   // comes from specs (starting with link_command). Consult gcc for
7191   // more information.
7192   ArgStringList CmdArgs;
7193
7194   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7195   if (Args.hasArg(options::OPT_ccc_arcmt_check,
7196                   options::OPT_ccc_arcmt_migrate)) {
7197     for (const auto &Arg : Args)
7198       Arg->claim();
7199     const char *Exec =
7200         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7201     CmdArgs.push_back(Output.getFilename());
7202     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7203     return;
7204   }
7205
7206   // I'm not sure why this particular decomposition exists in gcc, but
7207   // we follow suite for ease of comparison.
7208   AddLinkArgs(C, Args, CmdArgs, Inputs);
7209
7210   // It seems that the 'e' option is completely ignored for dynamic executables
7211   // (the default), and with static executables, the last one wins, as expected.
7212   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7213                             options::OPT_Z_Flag, options::OPT_u_Group,
7214                             options::OPT_e, options::OPT_r});
7215
7216   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7217   // members of static archive libraries which implement Objective-C classes or
7218   // categories.
7219   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7220     CmdArgs.push_back("-ObjC");
7221
7222   CmdArgs.push_back("-o");
7223   CmdArgs.push_back(Output.getFilename());
7224
7225   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7226     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7227
7228   // SafeStack requires its own runtime libraries
7229   // These libraries should be linked first, to make sure the
7230   // __safestack_init constructor executes before everything else
7231   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7232     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7233                                           "libclang_rt.safestack_osx.a",
7234                                           /*AlwaysLink=*/true);
7235   }
7236
7237   Args.AddAllArgs(CmdArgs, options::OPT_L);
7238
7239   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7240   // Build the input file for -filelist (list of linker input files) in case we
7241   // need it later
7242   for (const auto &II : Inputs) {
7243     if (!II.isFilename()) {
7244       // This is a linker input argument.
7245       // We cannot mix input arguments and file names in a -filelist input, thus
7246       // we prematurely stop our list (remaining files shall be passed as
7247       // arguments).
7248       if (InputFileList.size() > 0)
7249         break;
7250
7251       continue;
7252     }
7253
7254     InputFileList.push_back(II.getFilename());
7255   }
7256
7257   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7258     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7259
7260   if (isObjCRuntimeLinked(Args) &&
7261       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7262     // We use arclite library for both ARC and subscripting support.
7263     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7264
7265     CmdArgs.push_back("-framework");
7266     CmdArgs.push_back("Foundation");
7267     // Link libobj.
7268     CmdArgs.push_back("-lobjc");
7269   }
7270
7271   if (LinkingOutput) {
7272     CmdArgs.push_back("-arch_multiple");
7273     CmdArgs.push_back("-final_output");
7274     CmdArgs.push_back(LinkingOutput);
7275   }
7276
7277   if (Args.hasArg(options::OPT_fnested_functions))
7278     CmdArgs.push_back("-allow_stack_execute");
7279
7280   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7281
7282   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7283     if (getToolChain().getDriver().CCCIsCXX())
7284       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7285
7286     // link_ssp spec is empty.
7287
7288     // Let the tool chain choose which runtime library to link.
7289     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7290   }
7291
7292   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7293     // endfile_spec is empty.
7294   }
7295
7296   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7297   Args.AddAllArgs(CmdArgs, options::OPT_F);
7298
7299   // -iframework should be forwarded as -F.
7300   for (const Arg *A : Args.filtered(options::OPT_iframework))
7301     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7302
7303   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7304     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7305       if (A->getValue() == StringRef("Accelerate")) {
7306         CmdArgs.push_back("-framework");
7307         CmdArgs.push_back("Accelerate");
7308       }
7309     }
7310   }
7311
7312   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7313   std::unique_ptr<Command> Cmd =
7314       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7315   Cmd->setInputFileList(std::move(InputFileList));
7316   C.addCommand(std::move(Cmd));
7317 }
7318
7319 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7320                                 const InputInfo &Output,
7321                                 const InputInfoList &Inputs,
7322                                 const ArgList &Args,
7323                                 const char *LinkingOutput) const {
7324   ArgStringList CmdArgs;
7325
7326   CmdArgs.push_back("-create");
7327   assert(Output.isFilename() && "Unexpected lipo output.");
7328
7329   CmdArgs.push_back("-output");
7330   CmdArgs.push_back(Output.getFilename());
7331
7332   for (const auto &II : Inputs) {
7333     assert(II.isFilename() && "Unexpected lipo input.");
7334     CmdArgs.push_back(II.getFilename());
7335   }
7336
7337   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7338   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7339 }
7340
7341 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7342                                     const InputInfo &Output,
7343                                     const InputInfoList &Inputs,
7344                                     const ArgList &Args,
7345                                     const char *LinkingOutput) const {
7346   ArgStringList CmdArgs;
7347
7348   CmdArgs.push_back("-o");
7349   CmdArgs.push_back(Output.getFilename());
7350
7351   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7352   const InputInfo &Input = Inputs[0];
7353   assert(Input.isFilename() && "Unexpected dsymutil input.");
7354   CmdArgs.push_back(Input.getFilename());
7355
7356   const char *Exec =
7357       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7358   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7359 }
7360
7361 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7362                                        const InputInfo &Output,
7363                                        const InputInfoList &Inputs,
7364                                        const ArgList &Args,
7365                                        const char *LinkingOutput) const {
7366   ArgStringList CmdArgs;
7367   CmdArgs.push_back("--verify");
7368   CmdArgs.push_back("--debug-info");
7369   CmdArgs.push_back("--eh-frame");
7370   CmdArgs.push_back("--quiet");
7371
7372   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7373   const InputInfo &Input = Inputs[0];
7374   assert(Input.isFilename() && "Unexpected verify input");
7375
7376   // Grabbing the output of the earlier dsymutil run.
7377   CmdArgs.push_back(Input.getFilename());
7378
7379   const char *Exec =
7380       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7381   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7382 }
7383
7384 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7385                                       const InputInfo &Output,
7386                                       const InputInfoList &Inputs,
7387                                       const ArgList &Args,
7388                                       const char *LinkingOutput) const {
7389   claimNoWarnArgs(Args);
7390   ArgStringList CmdArgs;
7391
7392   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7393
7394   CmdArgs.push_back("-o");
7395   CmdArgs.push_back(Output.getFilename());
7396
7397   for (const auto &II : Inputs)
7398     CmdArgs.push_back(II.getFilename());
7399
7400   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7401   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7402 }
7403
7404 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7405                                    const InputInfo &Output,
7406                                    const InputInfoList &Inputs,
7407                                    const ArgList &Args,
7408                                    const char *LinkingOutput) const {
7409   ArgStringList CmdArgs;
7410
7411   // Demangle C++ names in errors
7412   CmdArgs.push_back("-C");
7413
7414   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7415     CmdArgs.push_back("-e");
7416     CmdArgs.push_back("_start");
7417   }
7418
7419   if (Args.hasArg(options::OPT_static)) {
7420     CmdArgs.push_back("-Bstatic");
7421     CmdArgs.push_back("-dn");
7422   } else {
7423     CmdArgs.push_back("-Bdynamic");
7424     if (Args.hasArg(options::OPT_shared)) {
7425       CmdArgs.push_back("-shared");
7426     } else {
7427       CmdArgs.push_back("--dynamic-linker");
7428       CmdArgs.push_back(
7429           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7430     }
7431   }
7432
7433   if (Output.isFilename()) {
7434     CmdArgs.push_back("-o");
7435     CmdArgs.push_back(Output.getFilename());
7436   } else {
7437     assert(Output.isNothing() && "Invalid output.");
7438   }
7439
7440   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7441     if (!Args.hasArg(options::OPT_shared))
7442       CmdArgs.push_back(
7443           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7444
7445     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7446     CmdArgs.push_back(
7447         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7448     CmdArgs.push_back(
7449         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7450   }
7451
7452   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7453
7454   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7455                             options::OPT_e, options::OPT_r});
7456
7457   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7458
7459   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7460     if (getToolChain().getDriver().CCCIsCXX())
7461       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7462     CmdArgs.push_back("-lgcc_s");
7463     CmdArgs.push_back("-lc");
7464     if (!Args.hasArg(options::OPT_shared)) {
7465       CmdArgs.push_back("-lgcc");
7466       CmdArgs.push_back("-lm");
7467     }
7468   }
7469
7470   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7471     CmdArgs.push_back(
7472         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7473   }
7474   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7475
7476   getToolChain().addProfileRTLibs(Args, CmdArgs);
7477
7478   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7479   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7480 }
7481
7482 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7483                                       const InputInfo &Output,
7484                                       const InputInfoList &Inputs,
7485                                       const ArgList &Args,
7486                                       const char *LinkingOutput) const {
7487   claimNoWarnArgs(Args);
7488   ArgStringList CmdArgs;
7489
7490   switch (getToolChain().getArch()) {
7491   case llvm::Triple::x86:
7492     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7493     // instruct as in the base system to assemble 32-bit code.
7494     CmdArgs.push_back("--32");
7495     break;
7496
7497   case llvm::Triple::ppc:
7498     CmdArgs.push_back("-mppc");
7499     CmdArgs.push_back("-many");
7500     break;
7501
7502   case llvm::Triple::sparc:
7503   case llvm::Triple::sparcel: {
7504     CmdArgs.push_back("-32");
7505     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7506     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7507     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7508     break;
7509   }
7510
7511   case llvm::Triple::sparcv9: {
7512     CmdArgs.push_back("-64");
7513     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7514     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7515     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7516     break;
7517   }
7518
7519   case llvm::Triple::mips64:
7520   case llvm::Triple::mips64el: {
7521     StringRef CPUName;
7522     StringRef ABIName;
7523     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7524
7525     CmdArgs.push_back("-mabi");
7526     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7527
7528     if (getToolChain().getArch() == llvm::Triple::mips64)
7529       CmdArgs.push_back("-EB");
7530     else
7531       CmdArgs.push_back("-EL");
7532
7533     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7534     break;
7535   }
7536
7537   default:
7538     break;
7539   }
7540
7541   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7542
7543   CmdArgs.push_back("-o");
7544   CmdArgs.push_back(Output.getFilename());
7545
7546   for (const auto &II : Inputs)
7547     CmdArgs.push_back(II.getFilename());
7548
7549   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7550   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7551 }
7552
7553 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7554                                    const InputInfo &Output,
7555                                    const InputInfoList &Inputs,
7556                                    const ArgList &Args,
7557                                    const char *LinkingOutput) const {
7558   const Driver &D = getToolChain().getDriver();
7559   ArgStringList CmdArgs;
7560
7561   // Silence warning for "clang -g foo.o -o foo"
7562   Args.ClaimAllArgs(options::OPT_g_Group);
7563   // and "clang -emit-llvm foo.o -o foo"
7564   Args.ClaimAllArgs(options::OPT_emit_llvm);
7565   // and for "clang -w foo.o -o foo". Other warning options are already
7566   // handled somewhere else.
7567   Args.ClaimAllArgs(options::OPT_w);
7568
7569   if (getToolChain().getArch() == llvm::Triple::mips64)
7570     CmdArgs.push_back("-EB");
7571   else if (getToolChain().getArch() == llvm::Triple::mips64el)
7572     CmdArgs.push_back("-EL");
7573
7574   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7575     CmdArgs.push_back("-e");
7576     CmdArgs.push_back("__start");
7577   }
7578
7579   if (Args.hasArg(options::OPT_static)) {
7580     CmdArgs.push_back("-Bstatic");
7581   } else {
7582     if (Args.hasArg(options::OPT_rdynamic))
7583       CmdArgs.push_back("-export-dynamic");
7584     CmdArgs.push_back("--eh-frame-hdr");
7585     CmdArgs.push_back("-Bdynamic");
7586     if (Args.hasArg(options::OPT_shared)) {
7587       CmdArgs.push_back("-shared");
7588     } else {
7589       CmdArgs.push_back("-dynamic-linker");
7590       CmdArgs.push_back("/usr/libexec/ld.so");
7591     }
7592   }
7593
7594   if (Args.hasArg(options::OPT_nopie))
7595     CmdArgs.push_back("-nopie");
7596
7597   if (Output.isFilename()) {
7598     CmdArgs.push_back("-o");
7599     CmdArgs.push_back(Output.getFilename());
7600   } else {
7601     assert(Output.isNothing() && "Invalid output.");
7602   }
7603
7604   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7605     if (!Args.hasArg(options::OPT_shared)) {
7606       if (Args.hasArg(options::OPT_pg))
7607         CmdArgs.push_back(
7608             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7609       else
7610         CmdArgs.push_back(
7611             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7612       CmdArgs.push_back(
7613           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7614     } else {
7615       CmdArgs.push_back(
7616           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7617     }
7618   }
7619
7620   std::string Triple = getToolChain().getTripleString();
7621   if (Triple.substr(0, 6) == "x86_64")
7622     Triple.replace(0, 6, "amd64");
7623   CmdArgs.push_back(
7624       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7625
7626   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7627                             options::OPT_e, options::OPT_s, options::OPT_t,
7628                             options::OPT_Z_Flag, options::OPT_r});
7629
7630   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7631
7632   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7633     if (D.CCCIsCXX()) {
7634       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7635       if (Args.hasArg(options::OPT_pg))
7636         CmdArgs.push_back("-lm_p");
7637       else
7638         CmdArgs.push_back("-lm");
7639     }
7640
7641     // FIXME: For some reason GCC passes -lgcc before adding
7642     // the default system libraries. Just mimic this for now.
7643     CmdArgs.push_back("-lgcc");
7644
7645     if (Args.hasArg(options::OPT_pthread)) {
7646       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7647         CmdArgs.push_back("-lpthread_p");
7648       else
7649         CmdArgs.push_back("-lpthread");
7650     }
7651
7652     if (!Args.hasArg(options::OPT_shared)) {
7653       if (Args.hasArg(options::OPT_pg))
7654         CmdArgs.push_back("-lc_p");
7655       else
7656         CmdArgs.push_back("-lc");
7657     }
7658
7659     CmdArgs.push_back("-lgcc");
7660   }
7661
7662   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7663     if (!Args.hasArg(options::OPT_shared))
7664       CmdArgs.push_back(
7665           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7666     else
7667       CmdArgs.push_back(
7668           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7669   }
7670
7671   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7672   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7673 }
7674
7675 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7676                                      const InputInfo &Output,
7677                                      const InputInfoList &Inputs,
7678                                      const ArgList &Args,
7679                                      const char *LinkingOutput) const {
7680   claimNoWarnArgs(Args);
7681   ArgStringList CmdArgs;
7682
7683   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7684
7685   CmdArgs.push_back("-o");
7686   CmdArgs.push_back(Output.getFilename());
7687
7688   for (const auto &II : Inputs)
7689     CmdArgs.push_back(II.getFilename());
7690
7691   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7692   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7693 }
7694
7695 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7696                                   const InputInfo &Output,
7697                                   const InputInfoList &Inputs,
7698                                   const ArgList &Args,
7699                                   const char *LinkingOutput) const {
7700   const Driver &D = getToolChain().getDriver();
7701   ArgStringList CmdArgs;
7702
7703   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7704     CmdArgs.push_back("-e");
7705     CmdArgs.push_back("__start");
7706   }
7707
7708   if (Args.hasArg(options::OPT_static)) {
7709     CmdArgs.push_back("-Bstatic");
7710   } else {
7711     if (Args.hasArg(options::OPT_rdynamic))
7712       CmdArgs.push_back("-export-dynamic");
7713     CmdArgs.push_back("--eh-frame-hdr");
7714     CmdArgs.push_back("-Bdynamic");
7715     if (Args.hasArg(options::OPT_shared)) {
7716       CmdArgs.push_back("-shared");
7717     } else {
7718       CmdArgs.push_back("-dynamic-linker");
7719       CmdArgs.push_back("/usr/libexec/ld.so");
7720     }
7721   }
7722
7723   if (Output.isFilename()) {
7724     CmdArgs.push_back("-o");
7725     CmdArgs.push_back(Output.getFilename());
7726   } else {
7727     assert(Output.isNothing() && "Invalid output.");
7728   }
7729
7730   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7731     if (!Args.hasArg(options::OPT_shared)) {
7732       if (Args.hasArg(options::OPT_pg))
7733         CmdArgs.push_back(
7734             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7735       else
7736         CmdArgs.push_back(
7737             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7738       CmdArgs.push_back(
7739           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7740     } else {
7741       CmdArgs.push_back(
7742           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7743     }
7744   }
7745
7746   Args.AddAllArgs(CmdArgs,
7747                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7748
7749   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7750
7751   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7752     if (D.CCCIsCXX()) {
7753       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7754       if (Args.hasArg(options::OPT_pg))
7755         CmdArgs.push_back("-lm_p");
7756       else
7757         CmdArgs.push_back("-lm");
7758     }
7759
7760     if (Args.hasArg(options::OPT_pthread)) {
7761       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7762         CmdArgs.push_back("-lpthread_p");
7763       else
7764         CmdArgs.push_back("-lpthread");
7765     }
7766
7767     if (!Args.hasArg(options::OPT_shared)) {
7768       if (Args.hasArg(options::OPT_pg))
7769         CmdArgs.push_back("-lc_p");
7770       else
7771         CmdArgs.push_back("-lc");
7772     }
7773
7774     StringRef MyArch;
7775     switch (getToolChain().getArch()) {
7776     case llvm::Triple::arm:
7777       MyArch = "arm";
7778       break;
7779     case llvm::Triple::x86:
7780       MyArch = "i386";
7781       break;
7782     case llvm::Triple::x86_64:
7783       MyArch = "amd64";
7784       break;
7785     default:
7786       llvm_unreachable("Unsupported architecture");
7787     }
7788     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7789   }
7790
7791   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7792     if (!Args.hasArg(options::OPT_shared))
7793       CmdArgs.push_back(
7794           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7795     else
7796       CmdArgs.push_back(
7797           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7798   }
7799
7800   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7801   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7802 }
7803
7804 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7805                                       const InputInfo &Output,
7806                                       const InputInfoList &Inputs,
7807                                       const ArgList &Args,
7808                                       const char *LinkingOutput) const {
7809   claimNoWarnArgs(Args);
7810   ArgStringList CmdArgs;
7811
7812   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7813   // instruct as in the base system to assemble 32-bit code.
7814   switch (getToolChain().getArch()) {
7815   default:
7816     break;
7817   case llvm::Triple::x86:
7818     CmdArgs.push_back("--32");
7819     break;
7820   case llvm::Triple::ppc:
7821     CmdArgs.push_back("-a32");
7822     break;
7823   case llvm::Triple::mips:
7824   case llvm::Triple::mipsel:
7825   case llvm::Triple::mips64:
7826   case llvm::Triple::mips64el: {
7827     StringRef CPUName;
7828     StringRef ABIName;
7829     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7830
7831     CmdArgs.push_back("-march");
7832     CmdArgs.push_back(CPUName.data());
7833
7834     CmdArgs.push_back("-mabi");
7835     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7836
7837     if (getToolChain().getArch() == llvm::Triple::mips ||
7838         getToolChain().getArch() == llvm::Triple::mips64)
7839       CmdArgs.push_back("-EB");
7840     else
7841       CmdArgs.push_back("-EL");
7842
7843     if (Arg *A = Args.getLastArg(options::OPT_G)) {
7844       StringRef v = A->getValue();
7845       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7846       A->claim();
7847     }
7848
7849     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7850     break;
7851   }
7852   case llvm::Triple::arm:
7853   case llvm::Triple::armeb:
7854   case llvm::Triple::thumb:
7855   case llvm::Triple::thumbeb: {
7856     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7857
7858     if (ABI == arm::FloatABI::Hard)
7859       CmdArgs.push_back("-mfpu=vfp");
7860     else
7861       CmdArgs.push_back("-mfpu=softvfp");
7862
7863     switch (getToolChain().getTriple().getEnvironment()) {
7864     case llvm::Triple::GNUEABIHF:
7865     case llvm::Triple::GNUEABI:
7866     case llvm::Triple::EABI:
7867       CmdArgs.push_back("-meabi=5");
7868       break;
7869
7870     default:
7871       CmdArgs.push_back("-matpcs");
7872     }
7873     break;
7874   }
7875   case llvm::Triple::sparc:
7876   case llvm::Triple::sparcel:
7877   case llvm::Triple::sparcv9: {
7878     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7879     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7880     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7881     break;
7882   }
7883   }
7884
7885   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7886
7887   CmdArgs.push_back("-o");
7888   CmdArgs.push_back(Output.getFilename());
7889
7890   for (const auto &II : Inputs)
7891     CmdArgs.push_back(II.getFilename());
7892
7893   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7894   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7895 }
7896
7897 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7898                                    const InputInfo &Output,
7899                                    const InputInfoList &Inputs,
7900                                    const ArgList &Args,
7901                                    const char *LinkingOutput) const {
7902   const toolchains::FreeBSD &ToolChain =
7903       static_cast<const toolchains::FreeBSD &>(getToolChain());
7904   const Driver &D = ToolChain.getDriver();
7905   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7906   const bool IsPIE =
7907       !Args.hasArg(options::OPT_shared) &&
7908       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7909   ArgStringList CmdArgs;
7910
7911   // Silence warning for "clang -g foo.o -o foo"
7912   Args.ClaimAllArgs(options::OPT_g_Group);
7913   // and "clang -emit-llvm foo.o -o foo"
7914   Args.ClaimAllArgs(options::OPT_emit_llvm);
7915   // and for "clang -w foo.o -o foo". Other warning options are already
7916   // handled somewhere else.
7917   Args.ClaimAllArgs(options::OPT_w);
7918
7919   if (!D.SysRoot.empty())
7920     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7921
7922   if (IsPIE)
7923     CmdArgs.push_back("-pie");
7924
7925   CmdArgs.push_back("--eh-frame-hdr");
7926   if (Args.hasArg(options::OPT_static)) {
7927     CmdArgs.push_back("-Bstatic");
7928   } else {
7929     if (Args.hasArg(options::OPT_rdynamic))
7930       CmdArgs.push_back("-export-dynamic");
7931     if (Args.hasArg(options::OPT_shared)) {
7932       CmdArgs.push_back("-Bshareable");
7933     } else {
7934       CmdArgs.push_back("-dynamic-linker");
7935       CmdArgs.push_back("/libexec/ld-elf.so.1");
7936     }
7937     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7938       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7939           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7940         CmdArgs.push_back("--hash-style=both");
7941       }
7942     }
7943     CmdArgs.push_back("--enable-new-dtags");
7944   }
7945
7946   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7947   // instruct ld in the base system to link 32-bit code.
7948   if (Arch == llvm::Triple::x86) {
7949     CmdArgs.push_back("-m");
7950     CmdArgs.push_back("elf_i386_fbsd");
7951   }
7952
7953   if (Arch == llvm::Triple::ppc) {
7954     CmdArgs.push_back("-m");
7955     CmdArgs.push_back("elf32ppc_fbsd");
7956   }
7957
7958   if (Arg *A = Args.getLastArg(options::OPT_G)) {
7959     if (ToolChain.getArch() == llvm::Triple::mips ||
7960       ToolChain.getArch() == llvm::Triple::mipsel ||
7961       ToolChain.getArch() == llvm::Triple::mips64 ||
7962       ToolChain.getArch() == llvm::Triple::mips64el) {
7963       StringRef v = A->getValue();
7964       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7965       A->claim();
7966     }
7967   }
7968
7969   if (Output.isFilename()) {
7970     CmdArgs.push_back("-o");
7971     CmdArgs.push_back(Output.getFilename());
7972   } else {
7973     assert(Output.isNothing() && "Invalid output.");
7974   }
7975
7976   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7977     const char *crt1 = nullptr;
7978     if (!Args.hasArg(options::OPT_shared)) {
7979       if (Args.hasArg(options::OPT_pg))
7980         crt1 = "gcrt1.o";
7981       else if (IsPIE)
7982         crt1 = "Scrt1.o";
7983       else
7984         crt1 = "crt1.o";
7985     }
7986     if (crt1)
7987       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7988
7989     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7990
7991     const char *crtbegin = nullptr;
7992     if (Args.hasArg(options::OPT_static))
7993       crtbegin = "crtbeginT.o";
7994     else if (Args.hasArg(options::OPT_shared) || IsPIE)
7995       crtbegin = "crtbeginS.o";
7996     else
7997       crtbegin = "crtbegin.o";
7998
7999     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8000   }
8001
8002   Args.AddAllArgs(CmdArgs, options::OPT_L);
8003   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8004   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8005   Args.AddAllArgs(CmdArgs, options::OPT_e);
8006   Args.AddAllArgs(CmdArgs, options::OPT_s);
8007   Args.AddAllArgs(CmdArgs, options::OPT_t);
8008   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8009   Args.AddAllArgs(CmdArgs, options::OPT_r);
8010
8011   if (D.isUsingLTO())
8012     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8013
8014   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8015   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8016
8017   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8018     addOpenMPRuntime(CmdArgs, ToolChain, Args);
8019     if (D.CCCIsCXX()) {
8020       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8021       if (Args.hasArg(options::OPT_pg))
8022         CmdArgs.push_back("-lm_p");
8023       else
8024         CmdArgs.push_back("-lm");
8025     }
8026     if (NeedsSanitizerDeps)
8027       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8028     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8029     // the default system libraries. Just mimic this for now.
8030     if (Args.hasArg(options::OPT_pg))
8031       CmdArgs.push_back("-lgcc_p");
8032     else
8033       CmdArgs.push_back("-lgcc");
8034     if (Args.hasArg(options::OPT_static)) {
8035       CmdArgs.push_back("-lgcc_eh");
8036     } else if (Args.hasArg(options::OPT_pg)) {
8037       CmdArgs.push_back("-lgcc_eh_p");
8038     } else {
8039       CmdArgs.push_back("--as-needed");
8040       CmdArgs.push_back("-lgcc_s");
8041       CmdArgs.push_back("--no-as-needed");
8042     }
8043
8044     if (Args.hasArg(options::OPT_pthread)) {
8045       if (Args.hasArg(options::OPT_pg))
8046         CmdArgs.push_back("-lpthread_p");
8047       else
8048         CmdArgs.push_back("-lpthread");
8049     }
8050
8051     if (Args.hasArg(options::OPT_pg)) {
8052       if (Args.hasArg(options::OPT_shared))
8053         CmdArgs.push_back("-lc");
8054       else
8055         CmdArgs.push_back("-lc_p");
8056       CmdArgs.push_back("-lgcc_p");
8057     } else {
8058       CmdArgs.push_back("-lc");
8059       CmdArgs.push_back("-lgcc");
8060     }
8061
8062     if (Args.hasArg(options::OPT_static)) {
8063       CmdArgs.push_back("-lgcc_eh");
8064     } else if (Args.hasArg(options::OPT_pg)) {
8065       CmdArgs.push_back("-lgcc_eh_p");
8066     } else {
8067       CmdArgs.push_back("--as-needed");
8068       CmdArgs.push_back("-lgcc_s");
8069       CmdArgs.push_back("--no-as-needed");
8070     }
8071   }
8072
8073   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8074     if (Args.hasArg(options::OPT_shared) || IsPIE)
8075       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8076     else
8077       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8078     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8079   }
8080
8081   ToolChain.addProfileRTLibs(Args, CmdArgs);
8082
8083   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8084   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8085 }
8086
8087 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8088                                      const InputInfo &Output,
8089                                      const InputInfoList &Inputs,
8090                                      const ArgList &Args,
8091                                      const char *LinkingOutput) const {
8092   claimNoWarnArgs(Args);
8093   ArgStringList CmdArgs;
8094
8095   // GNU as needs different flags for creating the correct output format
8096   // on architectures with different ABIs or optional feature sets.
8097   switch (getToolChain().getArch()) {
8098   case llvm::Triple::x86:
8099     CmdArgs.push_back("--32");
8100     break;
8101   case llvm::Triple::arm:
8102   case llvm::Triple::armeb:
8103   case llvm::Triple::thumb:
8104   case llvm::Triple::thumbeb: {
8105     StringRef MArch, MCPU;
8106     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8107     std::string Arch =
8108         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8109     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8110     break;
8111   }
8112
8113   case llvm::Triple::mips:
8114   case llvm::Triple::mipsel:
8115   case llvm::Triple::mips64:
8116   case llvm::Triple::mips64el: {
8117     StringRef CPUName;
8118     StringRef ABIName;
8119     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8120
8121     CmdArgs.push_back("-march");
8122     CmdArgs.push_back(CPUName.data());
8123
8124     CmdArgs.push_back("-mabi");
8125     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8126
8127     if (getToolChain().getArch() == llvm::Triple::mips ||
8128         getToolChain().getArch() == llvm::Triple::mips64)
8129       CmdArgs.push_back("-EB");
8130     else
8131       CmdArgs.push_back("-EL");
8132
8133     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8134     break;
8135   }
8136
8137   case llvm::Triple::sparc:
8138   case llvm::Triple::sparcel: {
8139     CmdArgs.push_back("-32");
8140     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8141     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8142     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8143     break;
8144   }
8145
8146   case llvm::Triple::sparcv9: {
8147     CmdArgs.push_back("-64");
8148     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8149     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8150     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8151     break;
8152   }
8153
8154   default:
8155     break;
8156   }
8157
8158   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8159
8160   CmdArgs.push_back("-o");
8161   CmdArgs.push_back(Output.getFilename());
8162
8163   for (const auto &II : Inputs)
8164     CmdArgs.push_back(II.getFilename());
8165
8166   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8167   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8168 }
8169
8170 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8171                                   const InputInfo &Output,
8172                                   const InputInfoList &Inputs,
8173                                   const ArgList &Args,
8174                                   const char *LinkingOutput) const {
8175   const Driver &D = getToolChain().getDriver();
8176   ArgStringList CmdArgs;
8177
8178   if (!D.SysRoot.empty())
8179     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8180
8181   CmdArgs.push_back("--eh-frame-hdr");
8182   if (Args.hasArg(options::OPT_static)) {
8183     CmdArgs.push_back("-Bstatic");
8184   } else {
8185     if (Args.hasArg(options::OPT_rdynamic))
8186       CmdArgs.push_back("-export-dynamic");
8187     if (Args.hasArg(options::OPT_shared)) {
8188       CmdArgs.push_back("-Bshareable");
8189     } else {
8190       CmdArgs.push_back("-dynamic-linker");
8191       CmdArgs.push_back("/libexec/ld.elf_so");
8192     }
8193   }
8194
8195   // Many NetBSD architectures support more than one ABI.
8196   // Determine the correct emulation for ld.
8197   switch (getToolChain().getArch()) {
8198   case llvm::Triple::x86:
8199     CmdArgs.push_back("-m");
8200     CmdArgs.push_back("elf_i386");
8201     break;
8202   case llvm::Triple::arm:
8203   case llvm::Triple::thumb:
8204     CmdArgs.push_back("-m");
8205     switch (getToolChain().getTriple().getEnvironment()) {
8206     case llvm::Triple::EABI:
8207     case llvm::Triple::GNUEABI:
8208       CmdArgs.push_back("armelf_nbsd_eabi");
8209       break;
8210     case llvm::Triple::EABIHF:
8211     case llvm::Triple::GNUEABIHF:
8212       CmdArgs.push_back("armelf_nbsd_eabihf");
8213       break;
8214     default:
8215       CmdArgs.push_back("armelf_nbsd");
8216       break;
8217     }
8218     break;
8219   case llvm::Triple::armeb:
8220   case llvm::Triple::thumbeb:
8221     arm::appendEBLinkFlags(
8222         Args, CmdArgs,
8223         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8224     CmdArgs.push_back("-m");
8225     switch (getToolChain().getTriple().getEnvironment()) {
8226     case llvm::Triple::EABI:
8227     case llvm::Triple::GNUEABI:
8228       CmdArgs.push_back("armelfb_nbsd_eabi");
8229       break;
8230     case llvm::Triple::EABIHF:
8231     case llvm::Triple::GNUEABIHF:
8232       CmdArgs.push_back("armelfb_nbsd_eabihf");
8233       break;
8234     default:
8235       CmdArgs.push_back("armelfb_nbsd");
8236       break;
8237     }
8238     break;
8239   case llvm::Triple::mips64:
8240   case llvm::Triple::mips64el:
8241     if (mips::hasMipsAbiArg(Args, "32")) {
8242       CmdArgs.push_back("-m");
8243       if (getToolChain().getArch() == llvm::Triple::mips64)
8244         CmdArgs.push_back("elf32btsmip");
8245       else
8246         CmdArgs.push_back("elf32ltsmip");
8247     } else if (mips::hasMipsAbiArg(Args, "64")) {
8248       CmdArgs.push_back("-m");
8249       if (getToolChain().getArch() == llvm::Triple::mips64)
8250         CmdArgs.push_back("elf64btsmip");
8251       else
8252         CmdArgs.push_back("elf64ltsmip");
8253     }
8254     break;
8255   case llvm::Triple::ppc:
8256     CmdArgs.push_back("-m");
8257     CmdArgs.push_back("elf32ppc_nbsd");
8258     break;
8259
8260   case llvm::Triple::ppc64:
8261   case llvm::Triple::ppc64le:
8262     CmdArgs.push_back("-m");
8263     CmdArgs.push_back("elf64ppc");
8264     break;
8265
8266   case llvm::Triple::sparc:
8267     CmdArgs.push_back("-m");
8268     CmdArgs.push_back("elf32_sparc");
8269     break;
8270
8271   case llvm::Triple::sparcv9:
8272     CmdArgs.push_back("-m");
8273     CmdArgs.push_back("elf64_sparc");
8274     break;
8275
8276   default:
8277     break;
8278   }
8279
8280   if (Output.isFilename()) {
8281     CmdArgs.push_back("-o");
8282     CmdArgs.push_back(Output.getFilename());
8283   } else {
8284     assert(Output.isNothing() && "Invalid output.");
8285   }
8286
8287   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8288     if (!Args.hasArg(options::OPT_shared)) {
8289       CmdArgs.push_back(
8290           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8291       CmdArgs.push_back(
8292           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8293       CmdArgs.push_back(
8294           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8295     } else {
8296       CmdArgs.push_back(
8297           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8298       CmdArgs.push_back(
8299           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8300     }
8301   }
8302
8303   Args.AddAllArgs(CmdArgs, options::OPT_L);
8304   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8305   Args.AddAllArgs(CmdArgs, options::OPT_e);
8306   Args.AddAllArgs(CmdArgs, options::OPT_s);
8307   Args.AddAllArgs(CmdArgs, options::OPT_t);
8308   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8309   Args.AddAllArgs(CmdArgs, options::OPT_r);
8310
8311   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8312
8313   unsigned Major, Minor, Micro;
8314   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8315   bool useLibgcc = true;
8316   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8317     switch (getToolChain().getArch()) {
8318     case llvm::Triple::aarch64:
8319     case llvm::Triple::arm:
8320     case llvm::Triple::armeb:
8321     case llvm::Triple::thumb:
8322     case llvm::Triple::thumbeb:
8323     case llvm::Triple::ppc:
8324     case llvm::Triple::ppc64:
8325     case llvm::Triple::ppc64le:
8326     case llvm::Triple::sparc:
8327     case llvm::Triple::sparcv9:
8328     case llvm::Triple::x86:
8329     case llvm::Triple::x86_64:
8330       useLibgcc = false;
8331       break;
8332     default:
8333       break;
8334     }
8335   }
8336
8337   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8338     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8339     if (D.CCCIsCXX()) {
8340       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8341       CmdArgs.push_back("-lm");
8342     }
8343     if (Args.hasArg(options::OPT_pthread))
8344       CmdArgs.push_back("-lpthread");
8345     CmdArgs.push_back("-lc");
8346
8347     if (useLibgcc) {
8348       if (Args.hasArg(options::OPT_static)) {
8349         // libgcc_eh depends on libc, so resolve as much as possible,
8350         // pull in any new requirements from libc and then get the rest
8351         // of libgcc.
8352         CmdArgs.push_back("-lgcc_eh");
8353         CmdArgs.push_back("-lc");
8354         CmdArgs.push_back("-lgcc");
8355       } else {
8356         CmdArgs.push_back("-lgcc");
8357         CmdArgs.push_back("--as-needed");
8358         CmdArgs.push_back("-lgcc_s");
8359         CmdArgs.push_back("--no-as-needed");
8360       }
8361     }
8362   }
8363
8364   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8365     if (!Args.hasArg(options::OPT_shared))
8366       CmdArgs.push_back(
8367           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8368     else
8369       CmdArgs.push_back(
8370           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8371     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8372   }
8373
8374   getToolChain().addProfileRTLibs(Args, CmdArgs);
8375
8376   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8377   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8378 }
8379
8380 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8381                                        const InputInfo &Output,
8382                                        const InputInfoList &Inputs,
8383                                        const ArgList &Args,
8384                                        const char *LinkingOutput) const {
8385   claimNoWarnArgs(Args);
8386
8387   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8388   llvm::Triple Triple = llvm::Triple(TripleStr);
8389
8390   ArgStringList CmdArgs;
8391
8392   llvm::Reloc::Model RelocationModel;
8393   unsigned PICLevel;
8394   bool IsPIE;
8395   std::tie(RelocationModel, PICLevel, IsPIE) =
8396       ParsePICArgs(getToolChain(), Triple, Args);
8397
8398   switch (getToolChain().getArch()) {
8399   default:
8400     break;
8401   // Add --32/--64 to make sure we get the format we want.
8402   // This is incomplete
8403   case llvm::Triple::x86:
8404     CmdArgs.push_back("--32");
8405     break;
8406   case llvm::Triple::x86_64:
8407     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8408       CmdArgs.push_back("--x32");
8409     else
8410       CmdArgs.push_back("--64");
8411     break;
8412   case llvm::Triple::ppc:
8413     CmdArgs.push_back("-a32");
8414     CmdArgs.push_back("-mppc");
8415     CmdArgs.push_back("-many");
8416     break;
8417   case llvm::Triple::ppc64:
8418     CmdArgs.push_back("-a64");
8419     CmdArgs.push_back("-mppc64");
8420     CmdArgs.push_back("-many");
8421     break;
8422   case llvm::Triple::ppc64le:
8423     CmdArgs.push_back("-a64");
8424     CmdArgs.push_back("-mppc64");
8425     CmdArgs.push_back("-many");
8426     CmdArgs.push_back("-mlittle-endian");
8427     break;
8428   case llvm::Triple::sparc:
8429   case llvm::Triple::sparcel: {
8430     CmdArgs.push_back("-32");
8431     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8432     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8433     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8434     break;
8435   }
8436   case llvm::Triple::sparcv9: {
8437     CmdArgs.push_back("-64");
8438     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8439     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8440     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8441     break;
8442   }
8443   case llvm::Triple::arm:
8444   case llvm::Triple::armeb:
8445   case llvm::Triple::thumb:
8446   case llvm::Triple::thumbeb: {
8447     const llvm::Triple &Triple2 = getToolChain().getTriple();
8448     switch (Triple2.getSubArch()) {
8449     case llvm::Triple::ARMSubArch_v7:
8450       CmdArgs.push_back("-mfpu=neon");
8451       break;
8452     case llvm::Triple::ARMSubArch_v8:
8453       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8454       break;
8455     default:
8456       break;
8457     }
8458
8459     switch (arm::getARMFloatABI(getToolChain(), Args)) {
8460     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8461     case arm::FloatABI::Soft:
8462       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8463       break;
8464     case arm::FloatABI::SoftFP:
8465       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8466       break;
8467     case arm::FloatABI::Hard:
8468       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8469       break;
8470     }
8471
8472     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8473
8474     // FIXME: remove krait check when GNU tools support krait cpu
8475     // for now replace it with -march=armv7-a  to avoid a lower
8476     // march from being picked in the absence of a cpu flag.
8477     Arg *A;
8478     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8479         StringRef(A->getValue()).lower() == "krait")
8480       CmdArgs.push_back("-march=armv7-a");
8481     else
8482       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8483     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8484     break;
8485   }
8486   case llvm::Triple::mips:
8487   case llvm::Triple::mipsel:
8488   case llvm::Triple::mips64:
8489   case llvm::Triple::mips64el: {
8490     StringRef CPUName;
8491     StringRef ABIName;
8492     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8493     ABIName = getGnuCompatibleMipsABIName(ABIName);
8494
8495     CmdArgs.push_back("-march");
8496     CmdArgs.push_back(CPUName.data());
8497
8498     CmdArgs.push_back("-mabi");
8499     CmdArgs.push_back(ABIName.data());
8500
8501     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8502     // or -mshared (not implemented) is in effect.
8503     if (RelocationModel == llvm::Reloc::Static)
8504       CmdArgs.push_back("-mno-shared");
8505
8506     // LLVM doesn't support -mplt yet and acts as if it is always given.
8507     // However, -mplt has no effect with the N64 ABI.
8508     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8509
8510     if (getToolChain().getArch() == llvm::Triple::mips ||
8511         getToolChain().getArch() == llvm::Triple::mips64)
8512       CmdArgs.push_back("-EB");
8513     else
8514       CmdArgs.push_back("-EL");
8515
8516     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8517       if (StringRef(A->getValue()) == "2008")
8518         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8519     }
8520
8521     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8522     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8523                                  options::OPT_mfp64)) {
8524       A->claim();
8525       A->render(Args, CmdArgs);
8526     } else if (mips::shouldUseFPXX(
8527                    Args, getToolChain().getTriple(), CPUName, ABIName,
8528                    getMipsFloatABI(getToolChain().getDriver(), Args)))
8529       CmdArgs.push_back("-mfpxx");
8530
8531     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8532     // -mno-mips16 is actually -no-mips16.
8533     if (Arg *A =
8534             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8535       if (A->getOption().matches(options::OPT_mips16)) {
8536         A->claim();
8537         A->render(Args, CmdArgs);
8538       } else {
8539         A->claim();
8540         CmdArgs.push_back("-no-mips16");
8541       }
8542     }
8543
8544     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8545                     options::OPT_mno_micromips);
8546     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8547     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8548
8549     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8550       // Do not use AddLastArg because not all versions of MIPS assembler
8551       // support -mmsa / -mno-msa options.
8552       if (A->getOption().matches(options::OPT_mmsa))
8553         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8554     }
8555
8556     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8557                     options::OPT_msoft_float);
8558
8559     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8560                     options::OPT_msingle_float);
8561
8562     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8563                     options::OPT_mno_odd_spreg);
8564
8565     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8566     break;
8567   }
8568   case llvm::Triple::systemz: {
8569     // Always pass an -march option, since our default of z10 is later
8570     // than the GNU assembler's default.
8571     StringRef CPUName = getSystemZTargetCPU(Args);
8572     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8573     break;
8574   }
8575   }
8576
8577   Args.AddAllArgs(CmdArgs, options::OPT_I);
8578   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8579
8580   CmdArgs.push_back("-o");
8581   CmdArgs.push_back(Output.getFilename());
8582
8583   for (const auto &II : Inputs)
8584     CmdArgs.push_back(II.getFilename());
8585
8586   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8587   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8588
8589   // Handle the debug info splitting at object creation time if we're
8590   // creating an object.
8591   // TODO: Currently only works on linux with newer objcopy.
8592   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8593       getToolChain().getTriple().isOSLinux())
8594     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8595                    SplitDebugName(Args, Inputs[0]));
8596 }
8597
8598 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8599                       ArgStringList &CmdArgs, const ArgList &Args) {
8600   bool isAndroid = Triple.isAndroid();
8601   bool isCygMing = Triple.isOSCygMing();
8602   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8603                       Args.hasArg(options::OPT_static);
8604   if (!D.CCCIsCXX())
8605     CmdArgs.push_back("-lgcc");
8606
8607   if (StaticLibgcc || isAndroid) {
8608     if (D.CCCIsCXX())
8609       CmdArgs.push_back("-lgcc");
8610   } else {
8611     if (!D.CCCIsCXX() && !isCygMing)
8612       CmdArgs.push_back("--as-needed");
8613     CmdArgs.push_back("-lgcc_s");
8614     if (!D.CCCIsCXX() && !isCygMing)
8615       CmdArgs.push_back("--no-as-needed");
8616   }
8617
8618   if (StaticLibgcc && !isAndroid)
8619     CmdArgs.push_back("-lgcc_eh");
8620   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8621     CmdArgs.push_back("-lgcc");
8622
8623   // According to Android ABI, we have to link with libdl if we are
8624   // linking with non-static libgcc.
8625   //
8626   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
8627   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8628   if (isAndroid && !StaticLibgcc)
8629     CmdArgs.push_back("-ldl");
8630 }
8631
8632 static std::string getLinuxDynamicLinker(const ArgList &Args,
8633                                          const toolchains::Linux &ToolChain) {
8634   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8635
8636   if (ToolChain.getTriple().isAndroid()) {
8637     if (ToolChain.getTriple().isArch64Bit())
8638       return "/system/bin/linker64";
8639     else
8640       return "/system/bin/linker";
8641   } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8642              Arch == llvm::Triple::sparcel)
8643     return "/lib/ld-linux.so.2";
8644   else if (Arch == llvm::Triple::aarch64)
8645     return "/lib/ld-linux-aarch64.so.1";
8646   else if (Arch == llvm::Triple::aarch64_be)
8647     return "/lib/ld-linux-aarch64_be.so.1";
8648   else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8649     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8650         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8651       return "/lib/ld-linux-armhf.so.3";
8652     else
8653       return "/lib/ld-linux.so.3";
8654   } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8655     // TODO: check which dynamic linker name.
8656     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8657         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8658       return "/lib/ld-linux-armhf.so.3";
8659     else
8660       return "/lib/ld-linux.so.3";
8661   } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8662              Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8663     std::string LibDir =
8664         "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8665     StringRef LibName;
8666     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8667     if (mips::isUCLibc(Args))
8668       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8669     else if (!ToolChain.getTriple().hasEnvironment()) {
8670       bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8671                 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8672       LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8673     } else
8674       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8675
8676     return (LibDir + "/" + LibName).str();
8677   } else if (Arch == llvm::Triple::ppc)
8678     return "/lib/ld.so.1";
8679   else if (Arch == llvm::Triple::ppc64) {
8680     if (ppc::hasPPCAbiArg(Args, "elfv2"))
8681       return "/lib64/ld64.so.2";
8682     return "/lib64/ld64.so.1";
8683   } else if (Arch == llvm::Triple::ppc64le) {
8684     if (ppc::hasPPCAbiArg(Args, "elfv1"))
8685       return "/lib64/ld64.so.1";
8686     return "/lib64/ld64.so.2";
8687   } else if (Arch == llvm::Triple::systemz)
8688     return "/lib/ld64.so.1";
8689   else if (Arch == llvm::Triple::sparcv9)
8690     return "/lib64/ld-linux.so.2";
8691   else if (Arch == llvm::Triple::x86_64 &&
8692            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8693     return "/libx32/ld-linux-x32.so.2";
8694   else
8695     return "/lib64/ld-linux-x86-64.so.2";
8696 }
8697
8698 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8699                            ArgStringList &CmdArgs, const ArgList &Args) {
8700   // Make use of compiler-rt if --rtlib option is used
8701   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8702
8703   switch (RLT) {
8704   case ToolChain::RLT_CompilerRT:
8705     switch (TC.getTriple().getOS()) {
8706     default:
8707       llvm_unreachable("unsupported OS");
8708     case llvm::Triple::Win32:
8709     case llvm::Triple::Linux:
8710       addClangRT(TC, Args, CmdArgs);
8711       break;
8712     }
8713     break;
8714   case ToolChain::RLT_Libgcc:
8715     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8716     break;
8717   }
8718 }
8719
8720 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8721   switch (T.getArch()) {
8722   case llvm::Triple::x86:
8723     return "elf_i386";
8724   case llvm::Triple::aarch64:
8725     return "aarch64linux";
8726   case llvm::Triple::aarch64_be:
8727     return "aarch64_be_linux";
8728   case llvm::Triple::arm:
8729   case llvm::Triple::thumb:
8730     return "armelf_linux_eabi";
8731   case llvm::Triple::armeb:
8732   case llvm::Triple::thumbeb:
8733     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
8734   case llvm::Triple::ppc:
8735     return "elf32ppclinux";
8736   case llvm::Triple::ppc64:
8737     return "elf64ppc";
8738   case llvm::Triple::ppc64le:
8739     return "elf64lppc";
8740   case llvm::Triple::sparc:
8741   case llvm::Triple::sparcel:
8742     return "elf32_sparc";
8743   case llvm::Triple::sparcv9:
8744     return "elf64_sparc";
8745   case llvm::Triple::mips:
8746     return "elf32btsmip";
8747   case llvm::Triple::mipsel:
8748     return "elf32ltsmip";
8749   case llvm::Triple::mips64:
8750     if (mips::hasMipsAbiArg(Args, "n32"))
8751       return "elf32btsmipn32";
8752     return "elf64btsmip";
8753   case llvm::Triple::mips64el:
8754     if (mips::hasMipsAbiArg(Args, "n32"))
8755       return "elf32ltsmipn32";
8756     return "elf64ltsmip";
8757   case llvm::Triple::systemz:
8758     return "elf64_s390";
8759   case llvm::Triple::x86_64:
8760     if (T.getEnvironment() == llvm::Triple::GNUX32)
8761       return "elf32_x86_64";
8762     return "elf_x86_64";
8763   default:
8764     llvm_unreachable("Unexpected arch");
8765   }
8766 }
8767
8768 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8769                                     const InputInfo &Output,
8770                                     const InputInfoList &Inputs,
8771                                     const ArgList &Args,
8772                                     const char *LinkingOutput) const {
8773   const toolchains::Linux &ToolChain =
8774       static_cast<const toolchains::Linux &>(getToolChain());
8775   const Driver &D = ToolChain.getDriver();
8776
8777   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8778   llvm::Triple Triple = llvm::Triple(TripleStr);
8779
8780   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8781   const bool isAndroid = ToolChain.getTriple().isAndroid();
8782   const bool IsPIE =
8783       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8784       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8785   const bool HasCRTBeginEndFiles =
8786       ToolChain.getTriple().hasEnvironment() ||
8787       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8788
8789   ArgStringList CmdArgs;
8790
8791   // Silence warning for "clang -g foo.o -o foo"
8792   Args.ClaimAllArgs(options::OPT_g_Group);
8793   // and "clang -emit-llvm foo.o -o foo"
8794   Args.ClaimAllArgs(options::OPT_emit_llvm);
8795   // and for "clang -w foo.o -o foo". Other warning options are already
8796   // handled somewhere else.
8797   Args.ClaimAllArgs(options::OPT_w);
8798
8799   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8800   if (llvm::sys::path::filename(Exec) == "lld") {
8801     CmdArgs.push_back("-flavor");
8802     CmdArgs.push_back("old-gnu");
8803     CmdArgs.push_back("-target");
8804     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8805   }
8806
8807   if (!D.SysRoot.empty())
8808     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8809
8810   if (IsPIE)
8811     CmdArgs.push_back("-pie");
8812
8813   if (Args.hasArg(options::OPT_rdynamic))
8814     CmdArgs.push_back("-export-dynamic");
8815
8816   if (Args.hasArg(options::OPT_s))
8817     CmdArgs.push_back("-s");
8818
8819   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8820     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8821
8822   for (const auto &Opt : ToolChain.ExtraOpts)
8823     CmdArgs.push_back(Opt.c_str());
8824
8825   if (!Args.hasArg(options::OPT_static)) {
8826     CmdArgs.push_back("--eh-frame-hdr");
8827   }
8828
8829   CmdArgs.push_back("-m");
8830   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8831
8832   if (Args.hasArg(options::OPT_static)) {
8833     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8834         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8835       CmdArgs.push_back("-Bstatic");
8836     else
8837       CmdArgs.push_back("-static");
8838   } else if (Args.hasArg(options::OPT_shared)) {
8839     CmdArgs.push_back("-shared");
8840   }
8841
8842   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8843       Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8844       (!Args.hasArg(options::OPT_static) &&
8845        !Args.hasArg(options::OPT_shared))) {
8846     CmdArgs.push_back("-dynamic-linker");
8847     CmdArgs.push_back(Args.MakeArgString(
8848         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8849   }
8850
8851   CmdArgs.push_back("-o");
8852   CmdArgs.push_back(Output.getFilename());
8853
8854   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8855     if (!isAndroid) {
8856       const char *crt1 = nullptr;
8857       if (!Args.hasArg(options::OPT_shared)) {
8858         if (Args.hasArg(options::OPT_pg))
8859           crt1 = "gcrt1.o";
8860         else if (IsPIE)
8861           crt1 = "Scrt1.o";
8862         else
8863           crt1 = "crt1.o";
8864       }
8865       if (crt1)
8866         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8867
8868       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8869     }
8870
8871     const char *crtbegin;
8872     if (Args.hasArg(options::OPT_static))
8873       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8874     else if (Args.hasArg(options::OPT_shared))
8875       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8876     else if (IsPIE)
8877       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8878     else
8879       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8880
8881     if (HasCRTBeginEndFiles)
8882       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8883
8884     // Add crtfastmath.o if available and fast math is enabled.
8885     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8886   }
8887
8888   Args.AddAllArgs(CmdArgs, options::OPT_L);
8889   Args.AddAllArgs(CmdArgs, options::OPT_u);
8890
8891   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8892
8893   if (D.isUsingLTO())
8894     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8895
8896   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8897     CmdArgs.push_back("--no-demangle");
8898
8899   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8900   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8901   // The profile runtime also needs access to system libraries.
8902   getToolChain().addProfileRTLibs(Args, CmdArgs);
8903
8904   if (D.CCCIsCXX() &&
8905       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8906     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8907                                !Args.hasArg(options::OPT_static);
8908     if (OnlyLibstdcxxStatic)
8909       CmdArgs.push_back("-Bstatic");
8910     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8911     if (OnlyLibstdcxxStatic)
8912       CmdArgs.push_back("-Bdynamic");
8913     CmdArgs.push_back("-lm");
8914   }
8915   // Silence warnings when linking C code with a C++ '-stdlib' argument.
8916   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8917
8918   if (!Args.hasArg(options::OPT_nostdlib)) {
8919     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8920       if (Args.hasArg(options::OPT_static))
8921         CmdArgs.push_back("--start-group");
8922
8923       if (NeedsSanitizerDeps)
8924         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8925
8926       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8927                          Args.hasArg(options::OPT_pthreads);
8928
8929       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8930                        options::OPT_fno_openmp, false)) {
8931         // OpenMP runtimes implies pthreads when using the GNU toolchain.
8932         // FIXME: Does this really make sense for all GNU toolchains?
8933         WantPthread = true;
8934
8935         // Also link the particular OpenMP runtimes.
8936         switch (getOpenMPRuntime(ToolChain, Args)) {
8937         case OMPRT_OMP:
8938           CmdArgs.push_back("-lomp");
8939           break;
8940         case OMPRT_GOMP:
8941           CmdArgs.push_back("-lgomp");
8942
8943           // FIXME: Exclude this for platforms with libgomp that don't require
8944           // librt. Most modern Linux platforms require it, but some may not.
8945           CmdArgs.push_back("-lrt");
8946           break;
8947         case OMPRT_IOMP5:
8948           CmdArgs.push_back("-liomp5");
8949           break;
8950         case OMPRT_Unknown:
8951           // Already diagnosed.
8952           break;
8953         }
8954       }
8955
8956       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8957
8958       if (WantPthread && !isAndroid)
8959         CmdArgs.push_back("-lpthread");
8960
8961       CmdArgs.push_back("-lc");
8962
8963       if (Args.hasArg(options::OPT_static))
8964         CmdArgs.push_back("--end-group");
8965       else
8966         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8967     }
8968
8969     if (!Args.hasArg(options::OPT_nostartfiles)) {
8970       const char *crtend;
8971       if (Args.hasArg(options::OPT_shared))
8972         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8973       else if (IsPIE)
8974         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8975       else
8976         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8977
8978       if (HasCRTBeginEndFiles)
8979         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8980       if (!isAndroid)
8981         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8982     }
8983   }
8984
8985   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8986 }
8987
8988 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8989 // for the various SFI requirements like register masking. The assembly tool
8990 // inserts the file containing the macros as an input into all the assembly
8991 // jobs.
8992 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8993                                            const InputInfo &Output,
8994                                            const InputInfoList &Inputs,
8995                                            const ArgList &Args,
8996                                            const char *LinkingOutput) const {
8997   const toolchains::NaClToolChain &ToolChain =
8998       static_cast<const toolchains::NaClToolChain &>(getToolChain());
8999   InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9000                        "nacl-arm-macros.s");
9001   InputInfoList NewInputs;
9002   NewInputs.push_back(NaClMacros);
9003   NewInputs.append(Inputs.begin(), Inputs.end());
9004   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9005                                     LinkingOutput);
9006 }
9007
9008 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9009 // we use static by default, do not yet support sanitizers or LTO, and a few
9010 // others. Eventually we can support more of that and hopefully migrate back
9011 // to gnutools::Linker.
9012 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9013                                      const InputInfo &Output,
9014                                      const InputInfoList &Inputs,
9015                                      const ArgList &Args,
9016                                      const char *LinkingOutput) const {
9017
9018   const toolchains::NaClToolChain &ToolChain =
9019       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9020   const Driver &D = ToolChain.getDriver();
9021   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9022   const bool IsStatic =
9023       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9024
9025   ArgStringList CmdArgs;
9026
9027   // Silence warning for "clang -g foo.o -o foo"
9028   Args.ClaimAllArgs(options::OPT_g_Group);
9029   // and "clang -emit-llvm foo.o -o foo"
9030   Args.ClaimAllArgs(options::OPT_emit_llvm);
9031   // and for "clang -w foo.o -o foo". Other warning options are already
9032   // handled somewhere else.
9033   Args.ClaimAllArgs(options::OPT_w);
9034
9035   if (!D.SysRoot.empty())
9036     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9037
9038   if (Args.hasArg(options::OPT_rdynamic))
9039     CmdArgs.push_back("-export-dynamic");
9040
9041   if (Args.hasArg(options::OPT_s))
9042     CmdArgs.push_back("-s");
9043
9044   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9045   // from there is --build-id, which we do want.
9046   CmdArgs.push_back("--build-id");
9047
9048   if (!IsStatic)
9049     CmdArgs.push_back("--eh-frame-hdr");
9050
9051   CmdArgs.push_back("-m");
9052   if (Arch == llvm::Triple::x86)
9053     CmdArgs.push_back("elf_i386_nacl");
9054   else if (Arch == llvm::Triple::arm)
9055     CmdArgs.push_back("armelf_nacl");
9056   else if (Arch == llvm::Triple::x86_64)
9057     CmdArgs.push_back("elf_x86_64_nacl");
9058   else if (Arch == llvm::Triple::mipsel)
9059     CmdArgs.push_back("mipselelf_nacl");
9060   else
9061     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9062                                               << "Native Client";
9063
9064   if (IsStatic)
9065     CmdArgs.push_back("-static");
9066   else if (Args.hasArg(options::OPT_shared))
9067     CmdArgs.push_back("-shared");
9068
9069   CmdArgs.push_back("-o");
9070   CmdArgs.push_back(Output.getFilename());
9071   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9072     if (!Args.hasArg(options::OPT_shared))
9073       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9074     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9075
9076     const char *crtbegin;
9077     if (IsStatic)
9078       crtbegin = "crtbeginT.o";
9079     else if (Args.hasArg(options::OPT_shared))
9080       crtbegin = "crtbeginS.o";
9081     else
9082       crtbegin = "crtbegin.o";
9083     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9084   }
9085
9086   Args.AddAllArgs(CmdArgs, options::OPT_L);
9087   Args.AddAllArgs(CmdArgs, options::OPT_u);
9088
9089   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9090
9091   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9092     CmdArgs.push_back("--no-demangle");
9093
9094   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9095
9096   if (D.CCCIsCXX() &&
9097       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9098     bool OnlyLibstdcxxStatic =
9099         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9100     if (OnlyLibstdcxxStatic)
9101       CmdArgs.push_back("-Bstatic");
9102     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9103     if (OnlyLibstdcxxStatic)
9104       CmdArgs.push_back("-Bdynamic");
9105     CmdArgs.push_back("-lm");
9106   }
9107
9108   if (!Args.hasArg(options::OPT_nostdlib)) {
9109     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9110       // Always use groups, since it has no effect on dynamic libraries.
9111       CmdArgs.push_back("--start-group");
9112       CmdArgs.push_back("-lc");
9113       // NaCl's libc++ currently requires libpthread, so just always include it
9114       // in the group for C++.
9115       if (Args.hasArg(options::OPT_pthread) ||
9116           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9117         // Gold, used by Mips, handles nested groups differently than ld, and
9118         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9119         // which is not a desired behaviour here.
9120         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9121         if (getToolChain().getArch() == llvm::Triple::mipsel)
9122           CmdArgs.push_back("-lnacl");
9123
9124         CmdArgs.push_back("-lpthread");
9125       }
9126
9127       CmdArgs.push_back("-lgcc");
9128       CmdArgs.push_back("--as-needed");
9129       if (IsStatic)
9130         CmdArgs.push_back("-lgcc_eh");
9131       else
9132         CmdArgs.push_back("-lgcc_s");
9133       CmdArgs.push_back("--no-as-needed");
9134
9135       // Mips needs to create and use pnacl_legacy library that contains
9136       // definitions from bitcode/pnaclmm.c and definitions for
9137       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9138       if (getToolChain().getArch() == llvm::Triple::mipsel)
9139         CmdArgs.push_back("-lpnacl_legacy");
9140
9141       CmdArgs.push_back("--end-group");
9142     }
9143
9144     if (!Args.hasArg(options::OPT_nostartfiles)) {
9145       const char *crtend;
9146       if (Args.hasArg(options::OPT_shared))
9147         crtend = "crtendS.o";
9148       else
9149         crtend = "crtend.o";
9150
9151       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9152       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9153     }
9154   }
9155
9156   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9157   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9158 }
9159
9160 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9161                                     const InputInfo &Output,
9162                                     const InputInfoList &Inputs,
9163                                     const ArgList &Args,
9164                                     const char *LinkingOutput) const {
9165   claimNoWarnArgs(Args);
9166   ArgStringList CmdArgs;
9167
9168   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9169
9170   CmdArgs.push_back("-o");
9171   CmdArgs.push_back(Output.getFilename());
9172
9173   for (const auto &II : Inputs)
9174     CmdArgs.push_back(II.getFilename());
9175
9176   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9177   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9178 }
9179
9180 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9181                                  const InputInfo &Output,
9182                                  const InputInfoList &Inputs,
9183                                  const ArgList &Args,
9184                                  const char *LinkingOutput) const {
9185   const Driver &D = getToolChain().getDriver();
9186   ArgStringList CmdArgs;
9187
9188   if (Output.isFilename()) {
9189     CmdArgs.push_back("-o");
9190     CmdArgs.push_back(Output.getFilename());
9191   } else {
9192     assert(Output.isNothing() && "Invalid output.");
9193   }
9194
9195   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9196     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9197     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9198     CmdArgs.push_back(
9199         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9200     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9201   }
9202
9203   Args.AddAllArgs(CmdArgs,
9204                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9205
9206   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9207
9208   getToolChain().addProfileRTLibs(Args, CmdArgs);
9209
9210   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9211     if (D.CCCIsCXX()) {
9212       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9213       CmdArgs.push_back("-lm");
9214     }
9215   }
9216
9217   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9218     if (Args.hasArg(options::OPT_pthread))
9219       CmdArgs.push_back("-lpthread");
9220     CmdArgs.push_back("-lc");
9221     CmdArgs.push_back("-lCompilerRT-Generic");
9222     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9223     CmdArgs.push_back(
9224         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9225   }
9226
9227   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9228   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9229 }
9230
9231 /// DragonFly Tools
9232
9233 // For now, DragonFly Assemble does just about the same as for
9234 // FreeBSD, but this may change soon.
9235 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9236                                         const InputInfo &Output,
9237                                         const InputInfoList &Inputs,
9238                                         const ArgList &Args,
9239                                         const char *LinkingOutput) const {
9240   claimNoWarnArgs(Args);
9241   ArgStringList CmdArgs;
9242
9243   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9244   // instruct as in the base system to assemble 32-bit code.
9245   if (getToolChain().getArch() == llvm::Triple::x86)
9246     CmdArgs.push_back("--32");
9247
9248   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9249
9250   CmdArgs.push_back("-o");
9251   CmdArgs.push_back(Output.getFilename());
9252
9253   for (const auto &II : Inputs)
9254     CmdArgs.push_back(II.getFilename());
9255
9256   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9257   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9258 }
9259
9260 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9261                                      const InputInfo &Output,
9262                                      const InputInfoList &Inputs,
9263                                      const ArgList &Args,
9264                                      const char *LinkingOutput) const {
9265   const Driver &D = getToolChain().getDriver();
9266   ArgStringList CmdArgs;
9267
9268   if (!D.SysRoot.empty())
9269     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9270
9271   CmdArgs.push_back("--eh-frame-hdr");
9272   if (Args.hasArg(options::OPT_static)) {
9273     CmdArgs.push_back("-Bstatic");
9274   } else {
9275     if (Args.hasArg(options::OPT_rdynamic))
9276       CmdArgs.push_back("-export-dynamic");
9277     if (Args.hasArg(options::OPT_shared))
9278       CmdArgs.push_back("-Bshareable");
9279     else {
9280       CmdArgs.push_back("-dynamic-linker");
9281       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9282     }
9283     CmdArgs.push_back("--hash-style=gnu");
9284     CmdArgs.push_back("--enable-new-dtags");
9285   }
9286
9287   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9288   // instruct ld in the base system to link 32-bit code.
9289   if (getToolChain().getArch() == llvm::Triple::x86) {
9290     CmdArgs.push_back("-m");
9291     CmdArgs.push_back("elf_i386");
9292   }
9293
9294   if (Output.isFilename()) {
9295     CmdArgs.push_back("-o");
9296     CmdArgs.push_back(Output.getFilename());
9297   } else {
9298     assert(Output.isNothing() && "Invalid output.");
9299   }
9300
9301   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9302     if (!Args.hasArg(options::OPT_shared)) {
9303       if (Args.hasArg(options::OPT_pg))
9304         CmdArgs.push_back(
9305             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9306       else {
9307         if (Args.hasArg(options::OPT_pie))
9308           CmdArgs.push_back(
9309               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9310         else
9311           CmdArgs.push_back(
9312               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9313       }
9314     }
9315     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9316     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9317       CmdArgs.push_back(
9318           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9319     else
9320       CmdArgs.push_back(
9321           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9322   }
9323
9324   Args.AddAllArgs(CmdArgs,
9325                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9326
9327   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9328
9329   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9330     CmdArgs.push_back("-L/usr/lib/gcc50");
9331
9332     if (!Args.hasArg(options::OPT_static)) {
9333       CmdArgs.push_back("-rpath");
9334       CmdArgs.push_back("/usr/lib/gcc50");
9335     }
9336
9337     if (D.CCCIsCXX()) {
9338       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9339       CmdArgs.push_back("-lm");
9340     }
9341
9342     if (Args.hasArg(options::OPT_pthread))
9343       CmdArgs.push_back("-lpthread");
9344
9345     if (!Args.hasArg(options::OPT_nolibc)) {
9346       CmdArgs.push_back("-lc");
9347     }
9348
9349     if (Args.hasArg(options::OPT_static) ||
9350         Args.hasArg(options::OPT_static_libgcc)) {
9351         CmdArgs.push_back("-lgcc");
9352         CmdArgs.push_back("-lgcc_eh");
9353     } else {
9354       if (Args.hasArg(options::OPT_shared_libgcc)) {
9355           CmdArgs.push_back("-lgcc_pic");
9356           if (!Args.hasArg(options::OPT_shared))
9357             CmdArgs.push_back("-lgcc");
9358       } else {
9359           CmdArgs.push_back("-lgcc");
9360           CmdArgs.push_back("--as-needed");
9361           CmdArgs.push_back("-lgcc_pic");
9362           CmdArgs.push_back("--no-as-needed");
9363       }
9364     }
9365   }
9366
9367   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9368     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9369       CmdArgs.push_back(
9370           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9371     else
9372       CmdArgs.push_back(
9373           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9374     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9375   }
9376
9377   getToolChain().addProfileRTLibs(Args, CmdArgs);
9378
9379   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9380   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9381 }
9382
9383 // Try to find Exe from a Visual Studio distribution.  This first tries to find
9384 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9385 // making sure that whatever executable that's found is not a same-named exe
9386 // from clang itself to prevent clang from falling back to itself.
9387 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9388                                               const char *Exe,
9389                                               const char *ClangProgramPath) {
9390   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9391   std::string visualStudioBinDir;
9392   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9393                                          visualStudioBinDir)) {
9394     SmallString<128> FilePath(visualStudioBinDir);
9395     llvm::sys::path::append(FilePath, Exe);
9396     if (llvm::sys::fs::can_execute(FilePath.c_str()))
9397       return FilePath.str();
9398   }
9399
9400   return Exe;
9401 }
9402
9403 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9404                                         const InputInfo &Output,
9405                                         const InputInfoList &Inputs,
9406                                         const ArgList &Args,
9407                                         const char *LinkingOutput) const {
9408   ArgStringList CmdArgs;
9409   const ToolChain &TC = getToolChain();
9410
9411   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9412   if (Output.isFilename())
9413     CmdArgs.push_back(
9414         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9415
9416   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9417       !C.getDriver().IsCLMode())
9418     CmdArgs.push_back("-defaultlib:libcmt");
9419
9420   if (!llvm::sys::Process::GetEnv("LIB")) {
9421     // If the VC environment hasn't been configured (perhaps because the user
9422     // did not run vcvarsall), try to build a consistent link environment.  If
9423     // the environment variable is set however, assume the user knows what
9424     // they're doing.
9425     std::string VisualStudioDir;
9426     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9427     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9428       SmallString<128> LibDir(VisualStudioDir);
9429       llvm::sys::path::append(LibDir, "VC", "lib");
9430       switch (MSVC.getArch()) {
9431       case llvm::Triple::x86:
9432         // x86 just puts the libraries directly in lib
9433         break;
9434       case llvm::Triple::x86_64:
9435         llvm::sys::path::append(LibDir, "amd64");
9436         break;
9437       case llvm::Triple::arm:
9438         llvm::sys::path::append(LibDir, "arm");
9439         break;
9440       default:
9441         break;
9442       }
9443       CmdArgs.push_back(
9444           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9445
9446       if (MSVC.useUniversalCRT(VisualStudioDir)) {
9447         std::string UniversalCRTLibPath;
9448         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9449           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9450                                                UniversalCRTLibPath.c_str()));
9451       }
9452     }
9453
9454     std::string WindowsSdkLibPath;
9455     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9456       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9457                                            WindowsSdkLibPath.c_str()));
9458   }
9459
9460   CmdArgs.push_back("-nologo");
9461
9462   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9463     CmdArgs.push_back("-debug");
9464
9465   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9466                          options::OPT_shared);
9467   if (DLL) {
9468     CmdArgs.push_back(Args.MakeArgString("-dll"));
9469
9470     SmallString<128> ImplibName(Output.getFilename());
9471     llvm::sys::path::replace_extension(ImplibName, "lib");
9472     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9473   }
9474
9475   if (TC.getSanitizerArgs().needsAsanRt()) {
9476     CmdArgs.push_back(Args.MakeArgString("-debug"));
9477     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9478     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9479       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9480         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9481       // Make sure the dynamic runtime thunk is not optimized out at link time
9482       // to ensure proper SEH handling.
9483       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9484     } else if (DLL) {
9485       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9486     } else {
9487       for (const auto &Lib : {"asan", "asan_cxx"})
9488         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9489     }
9490   }
9491
9492   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9493
9494   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9495                    options::OPT_fno_openmp, false)) {
9496     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9497     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9498     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9499                                          TC.getDriver().Dir + "/../lib"));
9500     switch (getOpenMPRuntime(getToolChain(), Args)) {
9501     case OMPRT_OMP:
9502       CmdArgs.push_back("-defaultlib:libomp.lib");
9503       break;
9504     case OMPRT_IOMP5:
9505       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9506       break;
9507     case OMPRT_GOMP:
9508       break;
9509     case OMPRT_Unknown:
9510       // Already diagnosed.
9511       break;
9512     }
9513   }
9514
9515   // Add filenames, libraries, and other linker inputs.
9516   for (const auto &Input : Inputs) {
9517     if (Input.isFilename()) {
9518       CmdArgs.push_back(Input.getFilename());
9519       continue;
9520     }
9521
9522     const Arg &A = Input.getInputArg();
9523
9524     // Render -l options differently for the MSVC linker.
9525     if (A.getOption().matches(options::OPT_l)) {
9526       StringRef Lib = A.getValue();
9527       const char *LinkLibArg;
9528       if (Lib.endswith(".lib"))
9529         LinkLibArg = Args.MakeArgString(Lib);
9530       else
9531         LinkLibArg = Args.MakeArgString(Lib + ".lib");
9532       CmdArgs.push_back(LinkLibArg);
9533       continue;
9534     }
9535
9536     // Otherwise, this is some other kind of linker input option like -Wl, -z,
9537     // or -L. Render it, even if MSVC doesn't understand it.
9538     A.renderAsInput(Args, CmdArgs);
9539   }
9540
9541   TC.addProfileRTLibs(Args, CmdArgs);
9542
9543   // We need to special case some linker paths.  In the case of lld, we need to
9544   // translate 'lld' into 'lld-link', and in the case of the regular msvc
9545   // linker, we need to use a special search algorithm.
9546   llvm::SmallString<128> linkPath;
9547   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9548   if (Linker.equals_lower("lld"))
9549     Linker = "lld-link";
9550
9551   if (Linker.equals_lower("link")) {
9552     // If we're using the MSVC linker, it's not sufficient to just use link
9553     // from the program PATH, because other environments like GnuWin32 install
9554     // their own link.exe which may come first.
9555     linkPath = FindVisualStudioExecutable(TC, "link.exe",
9556                                           C.getDriver().getClangProgramPath());
9557   } else {
9558     linkPath = Linker;
9559     llvm::sys::path::replace_extension(linkPath, "exe");
9560     linkPath = TC.GetProgramPath(linkPath.c_str());
9561   }
9562
9563   const char *Exec = Args.MakeArgString(linkPath);
9564   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9565 }
9566
9567 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9568                                           const InputInfo &Output,
9569                                           const InputInfoList &Inputs,
9570                                           const ArgList &Args,
9571                                           const char *LinkingOutput) const {
9572   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9573 }
9574
9575 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9576     Compilation &C, const JobAction &JA, const InputInfo &Output,
9577     const InputInfoList &Inputs, const ArgList &Args,
9578     const char *LinkingOutput) const {
9579   ArgStringList CmdArgs;
9580   CmdArgs.push_back("/nologo");
9581   CmdArgs.push_back("/c");  // Compile only.
9582   CmdArgs.push_back("/W0"); // No warnings.
9583
9584   // The goal is to be able to invoke this tool correctly based on
9585   // any flag accepted by clang-cl.
9586
9587   // These are spelled the same way in clang and cl.exe,.
9588   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9589
9590   // Optimization level.
9591   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9592     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9593                                                                       : "/Oi-");
9594   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9595     if (A->getOption().getID() == options::OPT_O0) {
9596       CmdArgs.push_back("/Od");
9597     } else {
9598       CmdArgs.push_back("/Og");
9599
9600       StringRef OptLevel = A->getValue();
9601       if (OptLevel == "s" || OptLevel == "z")
9602         CmdArgs.push_back("/Os");
9603       else
9604         CmdArgs.push_back("/Ot");
9605
9606       CmdArgs.push_back("/Ob2");
9607     }
9608   }
9609   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9610                                options::OPT_fno_omit_frame_pointer))
9611     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9612                           ? "/Oy"
9613                           : "/Oy-");
9614   if (!Args.hasArg(options::OPT_fwritable_strings))
9615     CmdArgs.push_back("/GF");
9616
9617   // Flags for which clang-cl has an alias.
9618   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9619
9620   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9621                    /*default=*/false))
9622     CmdArgs.push_back("/GR-");
9623   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9624                                options::OPT_fno_function_sections))
9625     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9626                           ? "/Gy"
9627                           : "/Gy-");
9628   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9629                                options::OPT_fno_data_sections))
9630     CmdArgs.push_back(
9631         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9632   if (Args.hasArg(options::OPT_fsyntax_only))
9633     CmdArgs.push_back("/Zs");
9634   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9635                   options::OPT__SLASH_Z7))
9636     CmdArgs.push_back("/Z7");
9637
9638   std::vector<std::string> Includes =
9639       Args.getAllArgValues(options::OPT_include);
9640   for (const auto &Include : Includes)
9641     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9642
9643   // Flags that can simply be passed through.
9644   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9645   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9646   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9647   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9648
9649   // The order of these flags is relevant, so pick the last one.
9650   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9651                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9652     A->render(Args, CmdArgs);
9653
9654   // Input filename.
9655   assert(Inputs.size() == 1);
9656   const InputInfo &II = Inputs[0];
9657   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9658   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9659   if (II.isFilename())
9660     CmdArgs.push_back(II.getFilename());
9661   else
9662     II.getInputArg().renderAsInput(Args, CmdArgs);
9663
9664   // Output filename.
9665   assert(Output.getType() == types::TY_Object);
9666   const char *Fo =
9667       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9668   CmdArgs.push_back(Fo);
9669
9670   const Driver &D = getToolChain().getDriver();
9671   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9672                                                 D.getClangProgramPath());
9673   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9674                                     CmdArgs, Inputs);
9675 }
9676
9677 /// MinGW Tools
9678 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9679                                     const InputInfo &Output,
9680                                     const InputInfoList &Inputs,
9681                                     const ArgList &Args,
9682                                     const char *LinkingOutput) const {
9683   claimNoWarnArgs(Args);
9684   ArgStringList CmdArgs;
9685
9686   if (getToolChain().getArch() == llvm::Triple::x86) {
9687     CmdArgs.push_back("--32");
9688   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9689     CmdArgs.push_back("--64");
9690   }
9691
9692   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9693
9694   CmdArgs.push_back("-o");
9695   CmdArgs.push_back(Output.getFilename());
9696
9697   for (const auto &II : Inputs)
9698     CmdArgs.push_back(II.getFilename());
9699
9700   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9701   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9702
9703   if (Args.hasArg(options::OPT_gsplit_dwarf))
9704     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9705                    SplitDebugName(Args, Inputs[0]));
9706 }
9707
9708 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9709                               ArgStringList &CmdArgs) const {
9710   if (Args.hasArg(options::OPT_mthreads))
9711     CmdArgs.push_back("-lmingwthrd");
9712   CmdArgs.push_back("-lmingw32");
9713
9714   // Make use of compiler-rt if --rtlib option is used
9715   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9716   if (RLT == ToolChain::RLT_Libgcc) {
9717     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9718                   Args.hasArg(options::OPT_static);
9719     bool Shared = Args.hasArg(options::OPT_shared);
9720     bool CXX = getToolChain().getDriver().CCCIsCXX();
9721
9722     if (Static || (!CXX && !Shared)) {
9723       CmdArgs.push_back("-lgcc");
9724       CmdArgs.push_back("-lgcc_eh");
9725     } else {
9726       CmdArgs.push_back("-lgcc_s");
9727       CmdArgs.push_back("-lgcc");
9728     }
9729   } else {
9730     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9731   }
9732
9733   CmdArgs.push_back("-lmoldname");
9734   CmdArgs.push_back("-lmingwex");
9735   CmdArgs.push_back("-lmsvcrt");
9736 }
9737
9738 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9739                                  const InputInfo &Output,
9740                                  const InputInfoList &Inputs,
9741                                  const ArgList &Args,
9742                                  const char *LinkingOutput) const {
9743   const ToolChain &TC = getToolChain();
9744   const Driver &D = TC.getDriver();
9745   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9746
9747   ArgStringList CmdArgs;
9748
9749   // Silence warning for "clang -g foo.o -o foo"
9750   Args.ClaimAllArgs(options::OPT_g_Group);
9751   // and "clang -emit-llvm foo.o -o foo"
9752   Args.ClaimAllArgs(options::OPT_emit_llvm);
9753   // and for "clang -w foo.o -o foo". Other warning options are already
9754   // handled somewhere else.
9755   Args.ClaimAllArgs(options::OPT_w);
9756
9757   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9758   if (LinkerName.equals_lower("lld")) {
9759     CmdArgs.push_back("-flavor");
9760     CmdArgs.push_back("gnu");
9761   } else if (!LinkerName.equals_lower("ld")) {
9762     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9763   }
9764
9765   if (!D.SysRoot.empty())
9766     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9767
9768   if (Args.hasArg(options::OPT_s))
9769     CmdArgs.push_back("-s");
9770
9771   CmdArgs.push_back("-m");
9772   if (TC.getArch() == llvm::Triple::x86)
9773     CmdArgs.push_back("i386pe");
9774   if (TC.getArch() == llvm::Triple::x86_64)
9775     CmdArgs.push_back("i386pep");
9776   if (TC.getArch() == llvm::Triple::arm)
9777     CmdArgs.push_back("thumb2pe");
9778
9779   if (Args.hasArg(options::OPT_mwindows)) {
9780     CmdArgs.push_back("--subsystem");
9781     CmdArgs.push_back("windows");
9782   } else if (Args.hasArg(options::OPT_mconsole)) {
9783     CmdArgs.push_back("--subsystem");
9784     CmdArgs.push_back("console");
9785   }
9786
9787   if (Args.hasArg(options::OPT_static))
9788     CmdArgs.push_back("-Bstatic");
9789   else {
9790     if (Args.hasArg(options::OPT_mdll))
9791       CmdArgs.push_back("--dll");
9792     else if (Args.hasArg(options::OPT_shared))
9793       CmdArgs.push_back("--shared");
9794     CmdArgs.push_back("-Bdynamic");
9795     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9796       CmdArgs.push_back("-e");
9797       if (TC.getArch() == llvm::Triple::x86)
9798         CmdArgs.push_back("_DllMainCRTStartup@12");
9799       else
9800         CmdArgs.push_back("DllMainCRTStartup");
9801       CmdArgs.push_back("--enable-auto-image-base");
9802     }
9803   }
9804
9805   CmdArgs.push_back("-o");
9806   CmdArgs.push_back(Output.getFilename());
9807
9808   Args.AddAllArgs(CmdArgs, options::OPT_e);
9809   // FIXME: add -N, -n flags
9810   Args.AddLastArg(CmdArgs, options::OPT_r);
9811   Args.AddLastArg(CmdArgs, options::OPT_s);
9812   Args.AddLastArg(CmdArgs, options::OPT_t);
9813   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9814   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9815
9816   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9817     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9818       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9819     } else {
9820       if (Args.hasArg(options::OPT_municode))
9821         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9822       else
9823         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9824     }
9825     if (Args.hasArg(options::OPT_pg))
9826       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9827     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9828   }
9829
9830   Args.AddAllArgs(CmdArgs, options::OPT_L);
9831   TC.AddFilePathLibArgs(Args, CmdArgs);
9832   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9833
9834   // TODO: Add ASan stuff here
9835
9836   // TODO: Add profile stuff here
9837
9838   if (D.CCCIsCXX() &&
9839       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9840     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9841                                !Args.hasArg(options::OPT_static);
9842     if (OnlyLibstdcxxStatic)
9843       CmdArgs.push_back("-Bstatic");
9844     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9845     if (OnlyLibstdcxxStatic)
9846       CmdArgs.push_back("-Bdynamic");
9847   }
9848
9849   if (!Args.hasArg(options::OPT_nostdlib)) {
9850     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9851       if (Args.hasArg(options::OPT_static))
9852         CmdArgs.push_back("--start-group");
9853
9854       if (Args.hasArg(options::OPT_fstack_protector) ||
9855           Args.hasArg(options::OPT_fstack_protector_strong) ||
9856           Args.hasArg(options::OPT_fstack_protector_all)) {
9857         CmdArgs.push_back("-lssp_nonshared");
9858         CmdArgs.push_back("-lssp");
9859       }
9860       if (Args.hasArg(options::OPT_fopenmp))
9861         CmdArgs.push_back("-lgomp");
9862
9863       AddLibGCC(Args, CmdArgs);
9864
9865       if (Args.hasArg(options::OPT_pg))
9866         CmdArgs.push_back("-lgmon");
9867
9868       if (Args.hasArg(options::OPT_pthread))
9869         CmdArgs.push_back("-lpthread");
9870
9871       // add system libraries
9872       if (Args.hasArg(options::OPT_mwindows)) {
9873         CmdArgs.push_back("-lgdi32");
9874         CmdArgs.push_back("-lcomdlg32");
9875       }
9876       CmdArgs.push_back("-ladvapi32");
9877       CmdArgs.push_back("-lshell32");
9878       CmdArgs.push_back("-luser32");
9879       CmdArgs.push_back("-lkernel32");
9880
9881       if (Args.hasArg(options::OPT_static))
9882         CmdArgs.push_back("--end-group");
9883       else if (!LinkerName.equals_lower("lld"))
9884         AddLibGCC(Args, CmdArgs);
9885     }
9886
9887     if (!Args.hasArg(options::OPT_nostartfiles)) {
9888       // Add crtfastmath.o if available and fast math is enabled.
9889       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9890
9891       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9892     }
9893   }
9894   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9895   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9896 }
9897
9898 /// XCore Tools
9899 // We pass assemble and link construction to the xcc tool.
9900
9901 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9902                                     const InputInfo &Output,
9903                                     const InputInfoList &Inputs,
9904                                     const ArgList &Args,
9905                                     const char *LinkingOutput) const {
9906   claimNoWarnArgs(Args);
9907   ArgStringList CmdArgs;
9908
9909   CmdArgs.push_back("-o");
9910   CmdArgs.push_back(Output.getFilename());
9911
9912   CmdArgs.push_back("-c");
9913
9914   if (Args.hasArg(options::OPT_v))
9915     CmdArgs.push_back("-v");
9916
9917   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9918     if (!A->getOption().matches(options::OPT_g0))
9919       CmdArgs.push_back("-g");
9920
9921   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9922                    false))
9923     CmdArgs.push_back("-fverbose-asm");
9924
9925   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9926
9927   for (const auto &II : Inputs)
9928     CmdArgs.push_back(II.getFilename());
9929
9930   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9931   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9932 }
9933
9934 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9935                                  const InputInfo &Output,
9936                                  const InputInfoList &Inputs,
9937                                  const ArgList &Args,
9938                                  const char *LinkingOutput) const {
9939   ArgStringList CmdArgs;
9940
9941   if (Output.isFilename()) {
9942     CmdArgs.push_back("-o");
9943     CmdArgs.push_back(Output.getFilename());
9944   } else {
9945     assert(Output.isNothing() && "Invalid output.");
9946   }
9947
9948   if (Args.hasArg(options::OPT_v))
9949     CmdArgs.push_back("-v");
9950
9951   // Pass -fexceptions through to the linker if it was present.
9952   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9953                    false))
9954     CmdArgs.push_back("-fexceptions");
9955
9956   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9957
9958   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9959   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9960 }
9961
9962 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9963                                            const InputInfo &Output,
9964                                            const InputInfoList &Inputs,
9965                                            const ArgList &Args,
9966                                            const char *LinkingOutput) const {
9967   claimNoWarnArgs(Args);
9968   const auto &TC =
9969       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9970   ArgStringList CmdArgs;
9971   const char *Exec;
9972
9973   switch (TC.getArch()) {
9974   default:
9975     llvm_unreachable("unsupported architecture");
9976   case llvm::Triple::arm:
9977   case llvm::Triple::thumb:
9978     break;
9979   case llvm::Triple::x86:
9980     CmdArgs.push_back("--32");
9981     break;
9982   case llvm::Triple::x86_64:
9983     CmdArgs.push_back("--64");
9984     break;
9985   }
9986
9987   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9988
9989   CmdArgs.push_back("-o");
9990   CmdArgs.push_back(Output.getFilename());
9991
9992   for (const auto &Input : Inputs)
9993     CmdArgs.push_back(Input.getFilename());
9994
9995   const std::string Assembler = TC.GetProgramPath("as");
9996   Exec = Args.MakeArgString(Assembler);
9997
9998   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9999 }
10000
10001 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10002                                         const InputInfo &Output,
10003                                         const InputInfoList &Inputs,
10004                                         const ArgList &Args,
10005                                         const char *LinkingOutput) const {
10006   const auto &TC =
10007       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10008   const llvm::Triple &T = TC.getTriple();
10009   const Driver &D = TC.getDriver();
10010   SmallString<128> EntryPoint;
10011   ArgStringList CmdArgs;
10012   const char *Exec;
10013
10014   // Silence warning for "clang -g foo.o -o foo"
10015   Args.ClaimAllArgs(options::OPT_g_Group);
10016   // and "clang -emit-llvm foo.o -o foo"
10017   Args.ClaimAllArgs(options::OPT_emit_llvm);
10018   // and for "clang -w foo.o -o foo"
10019   Args.ClaimAllArgs(options::OPT_w);
10020   // Other warning options are already handled somewhere else.
10021
10022   if (!D.SysRoot.empty())
10023     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10024
10025   if (Args.hasArg(options::OPT_pie))
10026     CmdArgs.push_back("-pie");
10027   if (Args.hasArg(options::OPT_rdynamic))
10028     CmdArgs.push_back("-export-dynamic");
10029   if (Args.hasArg(options::OPT_s))
10030     CmdArgs.push_back("--strip-all");
10031
10032   CmdArgs.push_back("-m");
10033   switch (TC.getArch()) {
10034   default:
10035     llvm_unreachable("unsupported architecture");
10036   case llvm::Triple::arm:
10037   case llvm::Triple::thumb:
10038     // FIXME: this is incorrect for WinCE
10039     CmdArgs.push_back("thumb2pe");
10040     break;
10041   case llvm::Triple::x86:
10042     CmdArgs.push_back("i386pe");
10043     EntryPoint.append("_");
10044     break;
10045   case llvm::Triple::x86_64:
10046     CmdArgs.push_back("i386pep");
10047     break;
10048   }
10049
10050   if (Args.hasArg(options::OPT_shared)) {
10051     switch (T.getArch()) {
10052     default:
10053       llvm_unreachable("unsupported architecture");
10054     case llvm::Triple::arm:
10055     case llvm::Triple::thumb:
10056     case llvm::Triple::x86_64:
10057       EntryPoint.append("_DllMainCRTStartup");
10058       break;
10059     case llvm::Triple::x86:
10060       EntryPoint.append("_DllMainCRTStartup@12");
10061       break;
10062     }
10063
10064     CmdArgs.push_back("-shared");
10065     CmdArgs.push_back("-Bdynamic");
10066
10067     CmdArgs.push_back("--enable-auto-image-base");
10068
10069     CmdArgs.push_back("--entry");
10070     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10071   } else {
10072     EntryPoint.append("mainCRTStartup");
10073
10074     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10075                                                        : "-Bdynamic");
10076
10077     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10078       CmdArgs.push_back("--entry");
10079       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10080     }
10081
10082     // FIXME: handle subsystem
10083   }
10084
10085   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10086   CmdArgs.push_back("--allow-multiple-definition");
10087
10088   CmdArgs.push_back("-o");
10089   CmdArgs.push_back(Output.getFilename());
10090
10091   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10092     SmallString<261> ImpLib(Output.getFilename());
10093     llvm::sys::path::replace_extension(ImpLib, ".lib");
10094
10095     CmdArgs.push_back("--out-implib");
10096     CmdArgs.push_back(Args.MakeArgString(ImpLib));
10097   }
10098
10099   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10100     const std::string CRTPath(D.SysRoot + "/usr/lib/");
10101     const char *CRTBegin;
10102
10103     CRTBegin =
10104         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10105     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10106   }
10107
10108   Args.AddAllArgs(CmdArgs, options::OPT_L);
10109   TC.AddFilePathLibArgs(Args, CmdArgs);
10110   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10111
10112   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10113       !Args.hasArg(options::OPT_nodefaultlibs)) {
10114     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10115                      !Args.hasArg(options::OPT_static);
10116     if (StaticCXX)
10117       CmdArgs.push_back("-Bstatic");
10118     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10119     if (StaticCXX)
10120       CmdArgs.push_back("-Bdynamic");
10121   }
10122
10123   if (!Args.hasArg(options::OPT_nostdlib)) {
10124     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10125       // TODO handle /MT[d] /MD[d]
10126       CmdArgs.push_back("-lmsvcrt");
10127       AddRunTimeLibs(TC, D, CmdArgs, Args);
10128     }
10129   }
10130
10131   if (TC.getSanitizerArgs().needsAsanRt()) {
10132     // TODO handle /MT[d] /MD[d]
10133     if (Args.hasArg(options::OPT_shared)) {
10134       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10135     } else {
10136       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10137         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10138         // Make sure the dynamic runtime thunk is not optimized out at link time
10139         // to ensure proper SEH handling.
10140         CmdArgs.push_back(Args.MakeArgString("--undefined"));
10141         CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10142                                                  ? "___asan_seh_interceptor"
10143                                                  : "__asan_seh_interceptor"));
10144     }
10145   }
10146
10147   Exec = Args.MakeArgString(TC.GetLinkerPath());
10148
10149   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10150 }
10151
10152 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10153                                           const InputInfo &Output,
10154                                           const InputInfoList &Inputs,
10155                                           const ArgList &Args,
10156                                           const char *LinkingOutput) const {
10157   ArgStringList CmdArgs;
10158   assert(Inputs.size() == 1);
10159   const InputInfo &II = Inputs[0];
10160   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10161          II.getType() == types::TY_PP_CXX);
10162
10163   if (JA.getKind() == Action::PreprocessJobClass) {
10164     Args.ClaimAllArgs();
10165     CmdArgs.push_back("-E");
10166   } else {
10167     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10168     CmdArgs.push_back("-S");
10169     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10170   }
10171   CmdArgs.push_back("-mcpu=myriad2");
10172   CmdArgs.push_back("-DMYRIAD2");
10173
10174   // Append all -I, -iquote, -isystem paths, defines/undefines,
10175   // 'f' flags, optimize flags, and warning options.
10176   // These are spelled the same way in clang and moviCompile.
10177   Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10178                             options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10179                             options::OPT_f_Group, options::OPT_f_clang_Group,
10180                             options::OPT_g_Group, options::OPT_M_Group,
10181                             options::OPT_O_Group, options::OPT_W_Group});
10182
10183   // If we're producing a dependency file, and assembly is the final action,
10184   // then the name of the target in the dependency file should be the '.o'
10185   // file, not the '.s' file produced by this step. For example, instead of
10186   //  /tmp/mumble.s: mumble.c .../someheader.h
10187   // the filename on the lefthand side should be "mumble.o"
10188   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10189       C.getActions().size() == 1 &&
10190       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10191     Arg *A = Args.getLastArg(options::OPT_o);
10192     if (A) {
10193       CmdArgs.push_back("-MT");
10194       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10195     }
10196   }
10197
10198   CmdArgs.push_back(II.getFilename());
10199   CmdArgs.push_back("-o");
10200   CmdArgs.push_back(Output.getFilename());
10201
10202   std::string Exec =
10203       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10204   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10205                                           CmdArgs, Inputs));
10206 }
10207
10208 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10209                                            const InputInfo &Output,
10210                                            const InputInfoList &Inputs,
10211                                            const ArgList &Args,
10212                                            const char *LinkingOutput) const {
10213   ArgStringList CmdArgs;
10214
10215   assert(Inputs.size() == 1);
10216   const InputInfo &II = Inputs[0];
10217   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10218   assert(Output.getType() == types::TY_Object);
10219
10220   CmdArgs.push_back("-no6thSlotCompression");
10221   CmdArgs.push_back("-cv:myriad2"); // Chip Version
10222   CmdArgs.push_back("-noSPrefixing");
10223   CmdArgs.push_back("-a"); // Mystery option.
10224   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10225   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10226     A->claim();
10227     CmdArgs.push_back(
10228         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10229   }
10230   CmdArgs.push_back("-elf"); // Output format.
10231   CmdArgs.push_back(II.getFilename());
10232   CmdArgs.push_back(
10233       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10234
10235   std::string Exec =
10236       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10237   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10238                                           CmdArgs, Inputs));
10239 }
10240
10241 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10242                                          const InputInfo &Output,
10243                                          const InputInfoList &Inputs,
10244                                          const ArgList &Args,
10245                                          const char *LinkingOutput) const {
10246   const auto &TC =
10247       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10248   const llvm::Triple &T = TC.getTriple();
10249   ArgStringList CmdArgs;
10250   bool UseStartfiles =
10251       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10252   bool UseDefaultLibs =
10253       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10254
10255   if (T.getArch() == llvm::Triple::sparc)
10256     CmdArgs.push_back("-EB");
10257   else // SHAVE assumes little-endian, and sparcel is expressly so.
10258     CmdArgs.push_back("-EL");
10259
10260   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10261   // but we never pass through a --sysroot option and various other bits.
10262   // For example, there are no sanitizers (yet) nor gold linker.
10263
10264   // Eat some arguments that may be present but have no effect.
10265   Args.ClaimAllArgs(options::OPT_g_Group);
10266   Args.ClaimAllArgs(options::OPT_w);
10267   Args.ClaimAllArgs(options::OPT_static_libgcc);
10268
10269   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10270     CmdArgs.push_back("-s");
10271
10272   CmdArgs.push_back("-o");
10273   CmdArgs.push_back(Output.getFilename());
10274
10275   if (UseStartfiles) {
10276     // If you want startfiles, it means you want the builtin crti and crtbegin,
10277     // but not crt0. Myriad link commands provide their own crt0.o as needed.
10278     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10279     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10280   }
10281
10282   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10283                             options::OPT_e, options::OPT_s, options::OPT_t,
10284                             options::OPT_Z_Flag, options::OPT_r});
10285
10286   TC.AddFilePathLibArgs(Args, CmdArgs);
10287
10288   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10289
10290   if (UseDefaultLibs) {
10291     if (C.getDriver().CCCIsCXX())
10292       CmdArgs.push_back("-lstdc++");
10293     if (T.getOS() == llvm::Triple::RTEMS) {
10294       CmdArgs.push_back("--start-group");
10295       CmdArgs.push_back("-lc");
10296       // You must provide your own "-L" option to enable finding these.
10297       CmdArgs.push_back("-lrtemscpu");
10298       CmdArgs.push_back("-lrtemsbsp");
10299       CmdArgs.push_back("--end-group");
10300     } else {
10301       CmdArgs.push_back("-lc");
10302     }
10303     CmdArgs.push_back("-lgcc");
10304   }
10305   if (UseStartfiles) {
10306     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10307     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10308   }
10309
10310   std::string Exec =
10311       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10312   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10313                                           CmdArgs, Inputs));
10314 }
10315
10316 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10317                                     const InputInfo &Output,
10318                                     const InputInfoList &Inputs,
10319                                     const ArgList &Args,
10320                                     const char *LinkingOutput) const {
10321   claimNoWarnArgs(Args);
10322   ArgStringList CmdArgs;
10323
10324   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10325
10326   CmdArgs.push_back("-o");
10327   CmdArgs.push_back(Output.getFilename());
10328
10329   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10330   const InputInfo &Input = Inputs[0];
10331   assert(Input.isFilename() && "Invalid input.");
10332   CmdArgs.push_back(Input.getFilename());
10333
10334   const char *Exec =
10335       Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10336   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10337 }
10338
10339 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10340   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10341   if (SanArgs.needsUbsanRt()) {
10342     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10343   }
10344   if (SanArgs.needsAsanRt()) {
10345     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10346   }
10347 }
10348
10349 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10350                                 const JobAction &JA, const InputInfo &Output,
10351                                 const InputInfoList &Inputs,
10352                                 const ArgList &Args,
10353                                 const char *LinkingOutput) {
10354   const toolchains::FreeBSD &ToolChain =
10355       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10356   const Driver &D = ToolChain.getDriver();
10357   ArgStringList CmdArgs;
10358
10359   // Silence warning for "clang -g foo.o -o foo"
10360   Args.ClaimAllArgs(options::OPT_g_Group);
10361   // and "clang -emit-llvm foo.o -o foo"
10362   Args.ClaimAllArgs(options::OPT_emit_llvm);
10363   // and for "clang -w foo.o -o foo". Other warning options are already
10364   // handled somewhere else.
10365   Args.ClaimAllArgs(options::OPT_w);
10366
10367   if (!D.SysRoot.empty())
10368     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10369
10370   if (Args.hasArg(options::OPT_pie))
10371     CmdArgs.push_back("-pie");
10372
10373   if (Args.hasArg(options::OPT_rdynamic))
10374     CmdArgs.push_back("-export-dynamic");
10375   if (Args.hasArg(options::OPT_shared))
10376     CmdArgs.push_back("--oformat=so");
10377
10378   if (Output.isFilename()) {
10379     CmdArgs.push_back("-o");
10380     CmdArgs.push_back(Output.getFilename());
10381   } else {
10382     assert(Output.isNothing() && "Invalid output.");
10383   }
10384
10385   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10386
10387   Args.AddAllArgs(CmdArgs, options::OPT_L);
10388   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10389   Args.AddAllArgs(CmdArgs, options::OPT_e);
10390   Args.AddAllArgs(CmdArgs, options::OPT_s);
10391   Args.AddAllArgs(CmdArgs, options::OPT_t);
10392   Args.AddAllArgs(CmdArgs, options::OPT_r);
10393
10394   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10395     CmdArgs.push_back("--no-demangle");
10396
10397   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10398
10399   if (Args.hasArg(options::OPT_pthread)) {
10400     CmdArgs.push_back("-lpthread");
10401   }
10402
10403   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10404
10405   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10406 }
10407
10408 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10409                                  const JobAction &JA, const InputInfo &Output,
10410                                  const InputInfoList &Inputs,
10411                                  const ArgList &Args,
10412                                  const char *LinkingOutput) {
10413   const toolchains::FreeBSD &ToolChain =
10414       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10415   const Driver &D = ToolChain.getDriver();
10416   ArgStringList CmdArgs;
10417
10418   // Silence warning for "clang -g foo.o -o foo"
10419   Args.ClaimAllArgs(options::OPT_g_Group);
10420   // and "clang -emit-llvm foo.o -o foo"
10421   Args.ClaimAllArgs(options::OPT_emit_llvm);
10422   // and for "clang -w foo.o -o foo". Other warning options are already
10423   // handled somewhere else.
10424   Args.ClaimAllArgs(options::OPT_w);
10425
10426   if (!D.SysRoot.empty())
10427     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10428
10429   if (Args.hasArg(options::OPT_pie))
10430     CmdArgs.push_back("-pie");
10431
10432   if (Args.hasArg(options::OPT_static)) {
10433     CmdArgs.push_back("-Bstatic");
10434   } else {
10435     if (Args.hasArg(options::OPT_rdynamic))
10436       CmdArgs.push_back("-export-dynamic");
10437     CmdArgs.push_back("--eh-frame-hdr");
10438     if (Args.hasArg(options::OPT_shared)) {
10439       CmdArgs.push_back("-Bshareable");
10440     } else {
10441       CmdArgs.push_back("-dynamic-linker");
10442       CmdArgs.push_back("/libexec/ld-elf.so.1");
10443     }
10444     CmdArgs.push_back("--enable-new-dtags");
10445   }
10446
10447   if (Output.isFilename()) {
10448     CmdArgs.push_back("-o");
10449     CmdArgs.push_back(Output.getFilename());
10450   } else {
10451     assert(Output.isNothing() && "Invalid output.");
10452   }
10453
10454   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10455
10456   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10457     const char *crt1 = nullptr;
10458     if (!Args.hasArg(options::OPT_shared)) {
10459       if (Args.hasArg(options::OPT_pg))
10460         crt1 = "gcrt1.o";
10461       else if (Args.hasArg(options::OPT_pie))
10462         crt1 = "Scrt1.o";
10463       else
10464         crt1 = "crt1.o";
10465     }
10466     if (crt1)
10467       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10468
10469     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10470
10471     const char *crtbegin = nullptr;
10472     if (Args.hasArg(options::OPT_static))
10473       crtbegin = "crtbeginT.o";
10474     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10475       crtbegin = "crtbeginS.o";
10476     else
10477       crtbegin = "crtbegin.o";
10478
10479     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10480   }
10481
10482   Args.AddAllArgs(CmdArgs, options::OPT_L);
10483   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10484   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10485   Args.AddAllArgs(CmdArgs, options::OPT_e);
10486   Args.AddAllArgs(CmdArgs, options::OPT_s);
10487   Args.AddAllArgs(CmdArgs, options::OPT_t);
10488   Args.AddAllArgs(CmdArgs, options::OPT_r);
10489
10490   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10491     CmdArgs.push_back("--no-demangle");
10492
10493   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10494
10495   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10496     // For PS4, we always want to pass libm, libstdc++ and libkernel
10497     // libraries for both C and C++ compilations.
10498     CmdArgs.push_back("-lkernel");
10499     if (D.CCCIsCXX()) {
10500       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10501       if (Args.hasArg(options::OPT_pg))
10502         CmdArgs.push_back("-lm_p");
10503       else
10504         CmdArgs.push_back("-lm");
10505     }
10506     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10507     // the default system libraries. Just mimic this for now.
10508     if (Args.hasArg(options::OPT_pg))
10509       CmdArgs.push_back("-lgcc_p");
10510     else
10511       CmdArgs.push_back("-lcompiler_rt");
10512     if (Args.hasArg(options::OPT_static)) {
10513       CmdArgs.push_back("-lstdc++");
10514     } else if (Args.hasArg(options::OPT_pg)) {
10515       CmdArgs.push_back("-lgcc_eh_p");
10516     } else {
10517       CmdArgs.push_back("--as-needed");
10518       CmdArgs.push_back("-lstdc++");
10519       CmdArgs.push_back("--no-as-needed");
10520     }
10521
10522     if (Args.hasArg(options::OPT_pthread)) {
10523       if (Args.hasArg(options::OPT_pg))
10524         CmdArgs.push_back("-lpthread_p");
10525       else
10526         CmdArgs.push_back("-lpthread");
10527     }
10528
10529     if (Args.hasArg(options::OPT_pg)) {
10530       if (Args.hasArg(options::OPT_shared))
10531         CmdArgs.push_back("-lc");
10532       else {
10533         if (Args.hasArg(options::OPT_static)) {
10534           CmdArgs.push_back("--start-group");
10535           CmdArgs.push_back("-lc_p");
10536           CmdArgs.push_back("-lpthread_p");
10537           CmdArgs.push_back("--end-group");
10538         } else {
10539           CmdArgs.push_back("-lc_p");
10540         }
10541       }
10542       CmdArgs.push_back("-lgcc_p");
10543     } else {
10544       if (Args.hasArg(options::OPT_static)) {
10545         CmdArgs.push_back("--start-group");
10546         CmdArgs.push_back("-lc");
10547         CmdArgs.push_back("-lpthread");
10548         CmdArgs.push_back("--end-group");
10549       } else {
10550         CmdArgs.push_back("-lc");
10551       }
10552       CmdArgs.push_back("-lcompiler_rt");
10553     }
10554
10555     if (Args.hasArg(options::OPT_static)) {
10556       CmdArgs.push_back("-lstdc++");
10557     } else if (Args.hasArg(options::OPT_pg)) {
10558       CmdArgs.push_back("-lgcc_eh_p");
10559     } else {
10560       CmdArgs.push_back("--as-needed");
10561       CmdArgs.push_back("-lstdc++");
10562       CmdArgs.push_back("--no-as-needed");
10563     }
10564   }
10565
10566   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10567     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10568       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10569     else
10570       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10571     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10572   }
10573
10574   const char *Exec =
10575 #ifdef LLVM_ON_WIN32
10576       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10577 #else
10578       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10579 #endif
10580
10581   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10582 }
10583
10584 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10585                                 const InputInfo &Output,
10586                                 const InputInfoList &Inputs,
10587                                 const ArgList &Args,
10588                                 const char *LinkingOutput) const {
10589   const toolchains::FreeBSD &ToolChain =
10590       static_cast<const toolchains::FreeBSD &>(getToolChain());
10591   const Driver &D = ToolChain.getDriver();
10592   bool PS4Linker;
10593   StringRef LinkerOptName;
10594   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10595     LinkerOptName = A->getValue();
10596     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10597       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10598   }
10599
10600   if (LinkerOptName == "gold")
10601     PS4Linker = false;
10602   else if (LinkerOptName == "ps4")
10603     PS4Linker = true;
10604   else
10605     PS4Linker = !Args.hasArg(options::OPT_shared);
10606
10607   if (PS4Linker)
10608     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10609   else
10610     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10611 }