]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge ^/head r293016 through r293035.
[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)
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 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2073 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2074                                   std::vector<const char *> &Features) {
2075   SmallVector<StringRef, 8> Split;
2076   text.split(Split, StringRef("+"), -1, false);
2077
2078   for (StringRef Feature : Split) {
2079     const char *result = llvm::StringSwitch<const char *>(Feature)
2080                              .Case("fp", "+fp-armv8")
2081                              .Case("simd", "+neon")
2082                              .Case("crc", "+crc")
2083                              .Case("crypto", "+crypto")
2084                              .Case("fp16", "+fullfp16")
2085                              .Case("profile", "+spe")
2086                              .Case("nofp", "-fp-armv8")
2087                              .Case("nosimd", "-neon")
2088                              .Case("nocrc", "-crc")
2089                              .Case("nocrypto", "-crypto")
2090                              .Case("nofp16", "-fullfp16")
2091                              .Case("noprofile", "-spe")
2092                              .Default(nullptr);
2093     if (result)
2094       Features.push_back(result);
2095     else if (Feature == "neon" || Feature == "noneon")
2096       D.Diag(diag::err_drv_no_neon_modifier);
2097     else
2098       return false;
2099   }
2100   return true;
2101 }
2102
2103 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2104 // decode CPU and feature.
2105 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2106                               std::vector<const char *> &Features) {
2107   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2108   CPU = Split.first;
2109   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2110       CPU == "cortex-a72" || CPU == "cortex-a35") {
2111     Features.push_back("+neon");
2112     Features.push_back("+crc");
2113     Features.push_back("+crypto");
2114   } else if (CPU == "generic") {
2115     Features.push_back("+neon");
2116   } else {
2117     return false;
2118   }
2119
2120   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2121     return false;
2122
2123   return true;
2124 }
2125
2126 static bool
2127 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2128                                 const ArgList &Args,
2129                                 std::vector<const char *> &Features) {
2130   std::string MarchLowerCase = March.lower();
2131   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2132
2133   if (Split.first == "armv8-a" || Split.first == "armv8a") {
2134     // ok, no additional features.
2135   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2136     Features.push_back("+v8.1a");
2137   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2138     Features.push_back("+v8.2a");
2139   } else {
2140     return false;
2141   }
2142
2143   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2144     return false;
2145
2146   return true;
2147 }
2148
2149 static bool
2150 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2151                                const ArgList &Args,
2152                                std::vector<const char *> &Features) {
2153   StringRef CPU;
2154   std::string McpuLowerCase = Mcpu.lower();
2155   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2156     return false;
2157
2158   return true;
2159 }
2160
2161 static bool
2162 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2163                                      const ArgList &Args,
2164                                      std::vector<const char *> &Features) {
2165   std::string MtuneLowerCase = Mtune.lower();
2166   // Handle CPU name is 'native'.
2167   if (MtuneLowerCase == "native")
2168     MtuneLowerCase = llvm::sys::getHostCPUName();
2169   if (MtuneLowerCase == "cyclone") {
2170     Features.push_back("+zcm");
2171     Features.push_back("+zcz");
2172   }
2173   return true;
2174 }
2175
2176 static bool
2177 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2178                                     const ArgList &Args,
2179                                     std::vector<const char *> &Features) {
2180   StringRef CPU;
2181   std::vector<const char *> DecodedFeature;
2182   std::string McpuLowerCase = Mcpu.lower();
2183   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2184     return false;
2185
2186   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2187 }
2188
2189 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2190                                      std::vector<const char *> &Features) {
2191   Arg *A;
2192   bool success = true;
2193   // Enable NEON by default.
2194   Features.push_back("+neon");
2195   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2196     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2197   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2198     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2199   else if (Args.hasArg(options::OPT_arch))
2200     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2201                                              Features);
2202
2203   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2204     success =
2205         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2206   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2207     success =
2208         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2209   else if (Args.hasArg(options::OPT_arch))
2210     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2211                                                   Args, Features);
2212
2213   if (!success)
2214     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2215
2216   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2217     Features.push_back("-fp-armv8");
2218     Features.push_back("-crypto");
2219     Features.push_back("-neon");
2220   }
2221
2222   // En/disable crc
2223   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2224     if (A->getOption().matches(options::OPT_mcrc))
2225       Features.push_back("+crc");
2226     else
2227       Features.push_back("-crc");
2228   }
2229
2230   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2231                                options::OPT_munaligned_access))
2232     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2233       Features.push_back("+strict-align");
2234
2235   if (Args.hasArg(options::OPT_ffixed_x18))
2236     Features.push_back("+reserve-x18");
2237 }
2238
2239 static void getHexagonTargetFeatures(const ArgList &Args,
2240                                      std::vector<const char *> &Features) {
2241   bool HasHVX = false, HasHVXD = false;
2242
2243   // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2244   // doing dependent option handling here rather than in initFeatureMap or a
2245   // similar handler.
2246   for (auto &A : Args) {
2247     auto &Opt = A->getOption();
2248     if (Opt.matches(options::OPT_mhexagon_hvx))
2249       HasHVX = true;
2250     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2251       HasHVXD = HasHVX = false;
2252     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2253       HasHVXD = HasHVX = true;
2254     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2255       HasHVXD = false;
2256     else
2257       continue;
2258     A->claim();
2259   }
2260
2261   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
2262   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2263 }
2264
2265 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2266                                          std::vector<const char *> &Features) {
2267   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2268 }
2269
2270 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2271                               const ArgList &Args, ArgStringList &CmdArgs,
2272                               bool ForAS) {
2273   const Driver &D = TC.getDriver();
2274   std::vector<const char *> Features;
2275   switch (Triple.getArch()) {
2276   default:
2277     break;
2278   case llvm::Triple::mips:
2279   case llvm::Triple::mipsel:
2280   case llvm::Triple::mips64:
2281   case llvm::Triple::mips64el:
2282     getMIPSTargetFeatures(D, Triple, Args, Features);
2283     break;
2284
2285   case llvm::Triple::arm:
2286   case llvm::Triple::armeb:
2287   case llvm::Triple::thumb:
2288   case llvm::Triple::thumbeb:
2289     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2290     break;
2291
2292   case llvm::Triple::ppc:
2293   case llvm::Triple::ppc64:
2294   case llvm::Triple::ppc64le:
2295     getPPCTargetFeatures(D, Triple, Args, Features);
2296     break;
2297   case llvm::Triple::systemz:
2298     getSystemZTargetFeatures(Args, Features);
2299     break;
2300   case llvm::Triple::aarch64:
2301   case llvm::Triple::aarch64_be:
2302     getAArch64TargetFeatures(D, Args, Features);
2303     break;
2304   case llvm::Triple::x86:
2305   case llvm::Triple::x86_64:
2306     getX86TargetFeatures(D, Triple, Args, Features);
2307     break;
2308   case llvm::Triple::hexagon:
2309     getHexagonTargetFeatures(Args, Features);
2310     break;
2311   case llvm::Triple::wasm32:
2312   case llvm::Triple::wasm64:
2313     getWebAssemblyTargetFeatures(Args, Features);
2314     break;
2315   }
2316
2317   // Find the last of each feature.
2318   llvm::StringMap<unsigned> LastOpt;
2319   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2320     const char *Name = Features[I];
2321     assert(Name[0] == '-' || Name[0] == '+');
2322     LastOpt[Name + 1] = I;
2323   }
2324
2325   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2326     // If this feature was overridden, ignore it.
2327     const char *Name = Features[I];
2328     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2329     assert(LastI != LastOpt.end());
2330     unsigned Last = LastI->second;
2331     if (Last != I)
2332       continue;
2333
2334     CmdArgs.push_back("-target-feature");
2335     CmdArgs.push_back(Name);
2336   }
2337 }
2338
2339 static bool
2340 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2341                                           const llvm::Triple &Triple) {
2342   // We use the zero-cost exception tables for Objective-C if the non-fragile
2343   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2344   // later.
2345   if (runtime.isNonFragile())
2346     return true;
2347
2348   if (!Triple.isMacOSX())
2349     return false;
2350
2351   return (!Triple.isMacOSXVersionLT(10, 5) &&
2352           (Triple.getArch() == llvm::Triple::x86_64 ||
2353            Triple.getArch() == llvm::Triple::arm));
2354 }
2355
2356 /// Adds exception related arguments to the driver command arguments. There's a
2357 /// master flag, -fexceptions and also language specific flags to enable/disable
2358 /// C++ and Objective-C exceptions. This makes it possible to for example
2359 /// disable C++ exceptions but enable Objective-C exceptions.
2360 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2361                              const ToolChain &TC, bool KernelOrKext,
2362                              const ObjCRuntime &objcRuntime,
2363                              ArgStringList &CmdArgs) {
2364   const Driver &D = TC.getDriver();
2365   const llvm::Triple &Triple = TC.getTriple();
2366
2367   if (KernelOrKext) {
2368     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2369     // arguments now to avoid warnings about unused arguments.
2370     Args.ClaimAllArgs(options::OPT_fexceptions);
2371     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2372     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2373     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2374     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2375     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2376     return;
2377   }
2378
2379   // See if the user explicitly enabled exceptions.
2380   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2381                          false);
2382
2383   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2384   // is not necessarily sensible, but follows GCC.
2385   if (types::isObjC(InputType) &&
2386       Args.hasFlag(options::OPT_fobjc_exceptions,
2387                    options::OPT_fno_objc_exceptions, true)) {
2388     CmdArgs.push_back("-fobjc-exceptions");
2389
2390     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2391   }
2392
2393   if (types::isCXX(InputType)) {
2394     // Disable C++ EH by default on XCore, PS4, and MSVC.
2395     // FIXME: Remove MSVC from this list once things work.
2396     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2397                                 !Triple.isPS4CPU() &&
2398                                 !Triple.isWindowsMSVCEnvironment();
2399     Arg *ExceptionArg = Args.getLastArg(
2400         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2401         options::OPT_fexceptions, options::OPT_fno_exceptions);
2402     if (ExceptionArg)
2403       CXXExceptionsEnabled =
2404           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2405           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2406
2407     if (CXXExceptionsEnabled) {
2408       if (Triple.isPS4CPU()) {
2409         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2410         assert(ExceptionArg &&
2411                "On the PS4 exceptions should only be enabled if passing "
2412                "an argument");
2413         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2414           const Arg *RTTIArg = TC.getRTTIArg();
2415           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2416           D.Diag(diag::err_drv_argument_not_allowed_with)
2417               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2418         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2419           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2420       } else
2421         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2422
2423       CmdArgs.push_back("-fcxx-exceptions");
2424
2425       EH = true;
2426     }
2427   }
2428
2429   if (EH)
2430     CmdArgs.push_back("-fexceptions");
2431 }
2432
2433 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2434   bool Default = true;
2435   if (TC.getTriple().isOSDarwin()) {
2436     // The native darwin assembler doesn't support the linker_option directives,
2437     // so we disable them if we think the .s file will be passed to it.
2438     Default = TC.useIntegratedAs();
2439   }
2440   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2441                        Default);
2442 }
2443
2444 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2445                                         const ToolChain &TC) {
2446   bool UseDwarfDirectory =
2447       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2448                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2449   return !UseDwarfDirectory;
2450 }
2451
2452 /// \brief Check whether the given input tree contains any compilation actions.
2453 static bool ContainsCompileAction(const Action *A) {
2454   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2455     return true;
2456
2457   for (const auto &Act : *A)
2458     if (ContainsCompileAction(Act))
2459       return true;
2460
2461   return false;
2462 }
2463
2464 /// \brief Check if -relax-all should be passed to the internal assembler.
2465 /// This is done by default when compiling non-assembler source with -O0.
2466 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2467   bool RelaxDefault = true;
2468
2469   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2470     RelaxDefault = A->getOption().matches(options::OPT_O0);
2471
2472   if (RelaxDefault) {
2473     RelaxDefault = false;
2474     for (const auto &Act : C.getActions()) {
2475       if (ContainsCompileAction(Act)) {
2476         RelaxDefault = true;
2477         break;
2478       }
2479     }
2480   }
2481
2482   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2483                       RelaxDefault);
2484 }
2485
2486 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2487 // to the corresponding DebugInfoKind.
2488 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2489   assert(A.getOption().matches(options::OPT_gN_Group) &&
2490          "Not a -g option that specifies a debug-info level");
2491   if (A.getOption().matches(options::OPT_g0) ||
2492       A.getOption().matches(options::OPT_ggdb0))
2493     return CodeGenOptions::NoDebugInfo;
2494   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2495       A.getOption().matches(options::OPT_ggdb1))
2496     return CodeGenOptions::DebugLineTablesOnly;
2497   return CodeGenOptions::LimitedDebugInfo;
2498 }
2499
2500 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2501 // on mismatch. The StringRef input (rather than an Arg) allows
2502 // for use by the "-Xassembler" option parser.
2503 static unsigned DwarfVersionNum(StringRef ArgValue) {
2504   return llvm::StringSwitch<unsigned>(ArgValue)
2505       .Case("-gdwarf-2", 2)
2506       .Case("-gdwarf-3", 3)
2507       .Case("-gdwarf-4", 4)
2508       .Case("-gdwarf-5", 5)
2509       .Default(0);
2510 }
2511
2512 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2513                                     CodeGenOptions::DebugInfoKind DebugInfoKind,
2514                                     unsigned DwarfVersion,
2515                                     llvm::DebuggerKind DebuggerTuning) {
2516   switch (DebugInfoKind) {
2517   case CodeGenOptions::DebugLineTablesOnly:
2518     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2519     break;
2520   case CodeGenOptions::LimitedDebugInfo:
2521     CmdArgs.push_back("-debug-info-kind=limited");
2522     break;
2523   case CodeGenOptions::FullDebugInfo:
2524     CmdArgs.push_back("-debug-info-kind=standalone");
2525     break;
2526   default:
2527     break;
2528   }
2529   if (DwarfVersion > 0)
2530     CmdArgs.push_back(
2531         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2532   switch (DebuggerTuning) {
2533   case llvm::DebuggerKind::GDB:
2534     CmdArgs.push_back("-debugger-tuning=gdb");
2535     break;
2536   case llvm::DebuggerKind::LLDB:
2537     CmdArgs.push_back("-debugger-tuning=lldb");
2538     break;
2539   case llvm::DebuggerKind::SCE:
2540     CmdArgs.push_back("-debugger-tuning=sce");
2541     break;
2542   default:
2543     break;
2544   }
2545 }
2546
2547 static void CollectArgsForIntegratedAssembler(Compilation &C,
2548                                               const ArgList &Args,
2549                                               ArgStringList &CmdArgs,
2550                                               const Driver &D) {
2551   if (UseRelaxAll(C, Args))
2552     CmdArgs.push_back("-mrelax-all");
2553
2554   // Only default to -mincremental-linker-compatible if we think we are
2555   // targeting the MSVC linker.
2556   bool DefaultIncrementalLinkerCompatible =
2557       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2558   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2559                    options::OPT_mno_incremental_linker_compatible,
2560                    DefaultIncrementalLinkerCompatible))
2561     CmdArgs.push_back("-mincremental-linker-compatible");
2562
2563   // When passing -I arguments to the assembler we sometimes need to
2564   // unconditionally take the next argument.  For example, when parsing
2565   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2566   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2567   // arg after parsing the '-I' arg.
2568   bool TakeNextArg = false;
2569
2570   // When using an integrated assembler, translate -Wa, and -Xassembler
2571   // options.
2572   bool CompressDebugSections = false;
2573   for (const Arg *A :
2574        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2575     A->claim();
2576
2577     for (StringRef Value : A->getValues()) {
2578       if (TakeNextArg) {
2579         CmdArgs.push_back(Value.data());
2580         TakeNextArg = false;
2581         continue;
2582       }
2583
2584       switch (C.getDefaultToolChain().getArch()) {
2585       default:
2586         break;
2587       case llvm::Triple::mips:
2588       case llvm::Triple::mipsel:
2589       case llvm::Triple::mips64:
2590       case llvm::Triple::mips64el:
2591         if (Value == "--trap") {
2592           CmdArgs.push_back("-target-feature");
2593           CmdArgs.push_back("+use-tcc-in-div");
2594           continue;
2595         }
2596         if (Value == "--break") {
2597           CmdArgs.push_back("-target-feature");
2598           CmdArgs.push_back("-use-tcc-in-div");
2599           continue;
2600         }
2601         if (Value.startswith("-msoft-float")) {
2602           CmdArgs.push_back("-target-feature");
2603           CmdArgs.push_back("+soft-float");
2604           continue;
2605         }
2606         if (Value.startswith("-mhard-float")) {
2607           CmdArgs.push_back("-target-feature");
2608           CmdArgs.push_back("-soft-float");
2609           continue;
2610         }
2611         break;
2612       }
2613
2614       if (Value == "-force_cpusubtype_ALL") {
2615         // Do nothing, this is the default and we don't support anything else.
2616       } else if (Value == "-L") {
2617         CmdArgs.push_back("-msave-temp-labels");
2618       } else if (Value == "--fatal-warnings") {
2619         CmdArgs.push_back("-massembler-fatal-warnings");
2620       } else if (Value == "--noexecstack") {
2621         CmdArgs.push_back("-mnoexecstack");
2622       } else if (Value == "-compress-debug-sections" ||
2623                  Value == "--compress-debug-sections") {
2624         CompressDebugSections = true;
2625       } else if (Value == "-nocompress-debug-sections" ||
2626                  Value == "--nocompress-debug-sections") {
2627         CompressDebugSections = false;
2628       } else if (Value.startswith("-I")) {
2629         CmdArgs.push_back(Value.data());
2630         // We need to consume the next argument if the current arg is a plain
2631         // -I. The next arg will be the include directory.
2632         if (Value == "-I")
2633           TakeNextArg = true;
2634       } else if (Value.startswith("-gdwarf-")) {
2635         // "-gdwarf-N" options are not cc1as options.
2636         unsigned DwarfVersion = DwarfVersionNum(Value);
2637         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2638           CmdArgs.push_back(Value.data());
2639         } else {
2640           RenderDebugEnablingArgs(
2641               Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2642               llvm::DebuggerKind::Default);
2643         }
2644       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2645                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2646         // Do nothing, we'll validate it later.
2647       } else {
2648         D.Diag(diag::err_drv_unsupported_option_argument)
2649             << A->getOption().getName() << Value;
2650       }
2651     }
2652   }
2653   if (CompressDebugSections) {
2654     if (llvm::zlib::isAvailable())
2655       CmdArgs.push_back("-compress-debug-sections");
2656     else
2657       D.Diag(diag::warn_debug_compression_unavailable);
2658   }
2659 }
2660
2661 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2662 // FIXME: Make sure we can also emit shared objects if they're requested
2663 // and available, check for possible errors, etc.
2664 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2665                        ArgStringList &CmdArgs) {
2666   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2667 }
2668
2669 namespace {
2670 enum OpenMPRuntimeKind {
2671   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2672   /// without knowing what runtime to target.
2673   OMPRT_Unknown,
2674
2675   /// The LLVM OpenMP runtime. When completed and integrated, this will become
2676   /// the default for Clang.
2677   OMPRT_OMP,
2678
2679   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2680   /// this runtime but can swallow the pragmas, and find and link against the
2681   /// runtime library itself.
2682   OMPRT_GOMP,
2683
2684   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2685   /// OpenMP runtime. We support this mode for users with existing dependencies
2686   /// on this runtime library name.
2687   OMPRT_IOMP5
2688 };
2689 }
2690
2691 /// Compute the desired OpenMP runtime from the flag provided.
2692 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2693                                           const ArgList &Args) {
2694   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2695
2696   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2697   if (A)
2698     RuntimeName = A->getValue();
2699
2700   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2701                 .Case("libomp", OMPRT_OMP)
2702                 .Case("libgomp", OMPRT_GOMP)
2703                 .Case("libiomp5", OMPRT_IOMP5)
2704                 .Default(OMPRT_Unknown);
2705
2706   if (RT == OMPRT_Unknown) {
2707     if (A)
2708       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2709           << A->getOption().getName() << A->getValue();
2710     else
2711       // FIXME: We could use a nicer diagnostic here.
2712       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2713   }
2714
2715   return RT;
2716 }
2717
2718 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2719                               const ArgList &Args) {
2720   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2721                     options::OPT_fno_openmp, false))
2722     return;
2723
2724   switch (getOpenMPRuntime(TC, Args)) {
2725   case OMPRT_OMP:
2726     CmdArgs.push_back("-lomp");
2727     break;
2728   case OMPRT_GOMP:
2729     CmdArgs.push_back("-lgomp");
2730     break;
2731   case OMPRT_IOMP5:
2732     CmdArgs.push_back("-liomp5");
2733     break;
2734   case OMPRT_Unknown:
2735     // Already diagnosed.
2736     break;
2737   }
2738 }
2739
2740 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2741                                 ArgStringList &CmdArgs, StringRef Sanitizer,
2742                                 bool IsShared) {
2743   // Static runtimes must be forced into executable, so we wrap them in
2744   // whole-archive.
2745   if (!IsShared) CmdArgs.push_back("-whole-archive");
2746   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2747   if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2748 }
2749
2750 // Tries to use a file with the list of dynamic symbols that need to be exported
2751 // from the runtime library. Returns true if the file was found.
2752 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2753                                     ArgStringList &CmdArgs,
2754                                     StringRef Sanitizer) {
2755   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2756   if (llvm::sys::fs::exists(SanRT + ".syms")) {
2757     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2758     return true;
2759   }
2760   return false;
2761 }
2762
2763 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2764                                      ArgStringList &CmdArgs) {
2765   // Force linking against the system libraries sanitizers depends on
2766   // (see PR15823 why this is necessary).
2767   CmdArgs.push_back("--no-as-needed");
2768   CmdArgs.push_back("-lpthread");
2769   CmdArgs.push_back("-lrt");
2770   CmdArgs.push_back("-lm");
2771   // There's no libdl on FreeBSD.
2772   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2773     CmdArgs.push_back("-ldl");
2774 }
2775
2776 static void
2777 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2778                          SmallVectorImpl<StringRef> &SharedRuntimes,
2779                          SmallVectorImpl<StringRef> &StaticRuntimes,
2780                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2781   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2782   // Collect shared runtimes.
2783   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2784     SharedRuntimes.push_back("asan");
2785   }
2786
2787   // Collect static runtimes.
2788   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2789     // Don't link static runtimes into DSOs or if compiling for Android.
2790     return;
2791   }
2792   if (SanArgs.needsAsanRt()) {
2793     if (SanArgs.needsSharedAsanRt()) {
2794       HelperStaticRuntimes.push_back("asan-preinit");
2795     } else {
2796       StaticRuntimes.push_back("asan");
2797       if (SanArgs.linkCXXRuntimes())
2798         StaticRuntimes.push_back("asan_cxx");
2799     }
2800   }
2801   if (SanArgs.needsDfsanRt())
2802     StaticRuntimes.push_back("dfsan");
2803   if (SanArgs.needsLsanRt())
2804     StaticRuntimes.push_back("lsan");
2805   if (SanArgs.needsMsanRt()) {
2806     StaticRuntimes.push_back("msan");
2807     if (SanArgs.linkCXXRuntimes())
2808       StaticRuntimes.push_back("msan_cxx");
2809   }
2810   if (SanArgs.needsTsanRt()) {
2811     StaticRuntimes.push_back("tsan");
2812     if (SanArgs.linkCXXRuntimes())
2813       StaticRuntimes.push_back("tsan_cxx");
2814   }
2815   if (SanArgs.needsUbsanRt()) {
2816     StaticRuntimes.push_back("ubsan_standalone");
2817     if (SanArgs.linkCXXRuntimes())
2818       StaticRuntimes.push_back("ubsan_standalone_cxx");
2819   }
2820   if (SanArgs.needsSafeStackRt())
2821     StaticRuntimes.push_back("safestack");
2822   if (SanArgs.needsCfiRt())
2823     StaticRuntimes.push_back("cfi");
2824   if (SanArgs.needsCfiDiagRt())
2825     StaticRuntimes.push_back("cfi_diag");
2826 }
2827
2828 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2829 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2830 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2831                                  ArgStringList &CmdArgs) {
2832   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2833       HelperStaticRuntimes;
2834   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2835                            HelperStaticRuntimes);
2836   for (auto RT : SharedRuntimes)
2837     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2838   for (auto RT : HelperStaticRuntimes)
2839     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2840   bool AddExportDynamic = false;
2841   for (auto RT : StaticRuntimes) {
2842     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2843     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2844   }
2845   // If there is a static runtime with no dynamic list, force all the symbols
2846   // to be dynamic to be sure we export sanitizer interface functions.
2847   if (AddExportDynamic)
2848     CmdArgs.push_back("-export-dynamic");
2849   return !StaticRuntimes.empty();
2850 }
2851
2852 static bool areOptimizationsEnabled(const ArgList &Args) {
2853   // Find the last -O arg and see if it is non-zero.
2854   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2855     return !A->getOption().matches(options::OPT_O0);
2856   // Defaults to -O0.
2857   return false;
2858 }
2859
2860 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2861                                            const llvm::Triple &Triple) {
2862   switch (Triple.getArch()) {
2863   case llvm::Triple::xcore:
2864   case llvm::Triple::wasm32:
2865   case llvm::Triple::wasm64:
2866     // XCore never wants frame pointers, regardless of OS.
2867     // WebAssembly never wants frame pointers.
2868     return false;
2869   default:
2870     break;
2871   }
2872
2873   if (Triple.isOSLinux()) {
2874     switch (Triple.getArch()) {
2875     // Don't use a frame pointer on linux if optimizing for certain targets.
2876     case llvm::Triple::mips64:
2877     case llvm::Triple::mips64el:
2878     case llvm::Triple::mips:
2879     case llvm::Triple::mipsel:
2880     case llvm::Triple::systemz:
2881     case llvm::Triple::x86:
2882     case llvm::Triple::x86_64:
2883       return !areOptimizationsEnabled(Args);
2884     default:
2885       return true;
2886     }
2887   }
2888
2889   if (Triple.isOSWindows()) {
2890     switch (Triple.getArch()) {
2891     case llvm::Triple::x86:
2892       return !areOptimizationsEnabled(Args);
2893     case llvm::Triple::arm:
2894     case llvm::Triple::thumb:
2895       // Windows on ARM builds with FPO disabled to aid fast stack walking
2896       return true;
2897     default:
2898       // All other supported Windows ISAs use xdata unwind information, so frame
2899       // pointers are not generally useful.
2900       return false;
2901     }
2902   }
2903
2904   return true;
2905 }
2906
2907 static bool shouldUseFramePointer(const ArgList &Args,
2908                                   const llvm::Triple &Triple) {
2909   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2910                                options::OPT_fomit_frame_pointer))
2911     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2912   if (Args.hasArg(options::OPT_pg))
2913     return true;
2914
2915   return shouldUseFramePointerForTarget(Args, Triple);
2916 }
2917
2918 static bool shouldUseLeafFramePointer(const ArgList &Args,
2919                                       const llvm::Triple &Triple) {
2920   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2921                                options::OPT_momit_leaf_frame_pointer))
2922     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2923   if (Args.hasArg(options::OPT_pg))
2924     return true;
2925
2926   if (Triple.isPS4CPU())
2927     return false;
2928
2929   return shouldUseFramePointerForTarget(Args, Triple);
2930 }
2931
2932 /// Add a CC1 option to specify the debug compilation directory.
2933 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2934   SmallString<128> cwd;
2935   if (!llvm::sys::fs::current_path(cwd)) {
2936     CmdArgs.push_back("-fdebug-compilation-dir");
2937     CmdArgs.push_back(Args.MakeArgString(cwd));
2938   }
2939 }
2940
2941 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2942   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2943   if (FinalOutput && Args.hasArg(options::OPT_c)) {
2944     SmallString<128> T(FinalOutput->getValue());
2945     llvm::sys::path::replace_extension(T, "dwo");
2946     return Args.MakeArgString(T);
2947   } else {
2948     // Use the compilation dir.
2949     SmallString<128> T(
2950         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2951     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2952     llvm::sys::path::replace_extension(F, "dwo");
2953     T += F;
2954     return Args.MakeArgString(F);
2955   }
2956 }
2957
2958 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2959                            const JobAction &JA, const ArgList &Args,
2960                            const InputInfo &Output, const char *OutFile) {
2961   ArgStringList ExtractArgs;
2962   ExtractArgs.push_back("--extract-dwo");
2963
2964   ArgStringList StripArgs;
2965   StripArgs.push_back("--strip-dwo");
2966
2967   // Grabbing the output of the earlier compile step.
2968   StripArgs.push_back(Output.getFilename());
2969   ExtractArgs.push_back(Output.getFilename());
2970   ExtractArgs.push_back(OutFile);
2971
2972   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2973   InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
2974
2975   // First extract the dwo sections.
2976   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2977
2978   // Then remove them from the original .o file.
2979   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2980 }
2981
2982 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2983 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2984 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2985   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2986     if (A->getOption().matches(options::OPT_O4) ||
2987         A->getOption().matches(options::OPT_Ofast))
2988       return true;
2989
2990     if (A->getOption().matches(options::OPT_O0))
2991       return false;
2992
2993     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2994
2995     // Vectorize -Os.
2996     StringRef S(A->getValue());
2997     if (S == "s")
2998       return true;
2999
3000     // Don't vectorize -Oz, unless it's the slp vectorizer.
3001     if (S == "z")
3002       return isSlpVec;
3003
3004     unsigned OptLevel = 0;
3005     if (S.getAsInteger(10, OptLevel))
3006       return false;
3007
3008     return OptLevel > 1;
3009   }
3010
3011   return false;
3012 }
3013
3014 /// Add -x lang to \p CmdArgs for \p Input.
3015 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3016                              ArgStringList &CmdArgs) {
3017   // When using -verify-pch, we don't want to provide the type
3018   // 'precompiled-header' if it was inferred from the file extension
3019   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3020     return;
3021
3022   CmdArgs.push_back("-x");
3023   if (Args.hasArg(options::OPT_rewrite_objc))
3024     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3025   else
3026     CmdArgs.push_back(types::getTypeName(Input.getType()));
3027 }
3028
3029 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3030   if (Version < 100)
3031     return VersionTuple(Version);
3032
3033   if (Version < 10000)
3034     return VersionTuple(Version / 100, Version % 100);
3035
3036   unsigned Build = 0, Factor = 1;
3037   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3038     Build = Build + (Version % 10) * Factor;
3039   return VersionTuple(Version / 100, Version % 100, Build);
3040 }
3041
3042 // Claim options we don't want to warn if they are unused. We do this for
3043 // options that build systems might add but are unused when assembling or only
3044 // running the preprocessor for example.
3045 static void claimNoWarnArgs(const ArgList &Args) {
3046   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3047   // preprocessing, precompiling or assembling.
3048   Args.ClaimAllArgs(options::OPT_flto_EQ);
3049   Args.ClaimAllArgs(options::OPT_flto);
3050   Args.ClaimAllArgs(options::OPT_fno_lto);
3051 }
3052
3053 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3054 #ifdef LLVM_ON_UNIX
3055   const char *Username = getenv("LOGNAME");
3056 #else
3057   const char *Username = getenv("USERNAME");
3058 #endif
3059   if (Username) {
3060     // Validate that LoginName can be used in a path, and get its length.
3061     size_t Len = 0;
3062     for (const char *P = Username; *P; ++P, ++Len) {
3063       if (!isAlphanumeric(*P) && *P != '_') {
3064         Username = nullptr;
3065         break;
3066       }
3067     }
3068
3069     if (Username && Len > 0) {
3070       Result.append(Username, Username + Len);
3071       return;
3072     }
3073   }
3074
3075 // Fallback to user id.
3076 #ifdef LLVM_ON_UNIX
3077   std::string UID = llvm::utostr(getuid());
3078 #else
3079   // FIXME: Windows seems to have an 'SID' that might work.
3080   std::string UID = "9999";
3081 #endif
3082   Result.append(UID.begin(), UID.end());
3083 }
3084
3085 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3086                                           const llvm::Triple &Triple,
3087                                           const llvm::opt::ArgList &Args,
3088                                           bool IsWindowsMSVC) {
3089   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3090                    IsWindowsMSVC) ||
3091       Args.hasArg(options::OPT_fmsc_version) ||
3092       Args.hasArg(options::OPT_fms_compatibility_version)) {
3093     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3094     const Arg *MSCompatibilityVersion =
3095         Args.getLastArg(options::OPT_fms_compatibility_version);
3096
3097     if (MSCVersion && MSCompatibilityVersion) {
3098       if (D)
3099         D->Diag(diag::err_drv_argument_not_allowed_with)
3100             << MSCVersion->getAsString(Args)
3101             << MSCompatibilityVersion->getAsString(Args);
3102       return VersionTuple();
3103     }
3104
3105     if (MSCompatibilityVersion) {
3106       VersionTuple MSVT;
3107       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3108         D->Diag(diag::err_drv_invalid_value)
3109             << MSCompatibilityVersion->getAsString(Args)
3110             << MSCompatibilityVersion->getValue();
3111       return MSVT;
3112     }
3113
3114     if (MSCVersion) {
3115       unsigned Version = 0;
3116       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3117         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3118                                              << MSCVersion->getValue();
3119       return getMSCompatibilityVersion(Version);
3120     }
3121
3122     unsigned Major, Minor, Micro;
3123     Triple.getEnvironmentVersion(Major, Minor, Micro);
3124     if (Major || Minor || Micro)
3125       return VersionTuple(Major, Minor, Micro);
3126
3127     return VersionTuple(18);
3128   }
3129   return VersionTuple();
3130 }
3131
3132 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3133                                    const InputInfo &Output, const ArgList &Args,
3134                                    ArgStringList &CmdArgs) {
3135   auto *ProfileGenerateArg = Args.getLastArg(
3136       options::OPT_fprofile_instr_generate,
3137       options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3138       options::OPT_fprofile_generate_EQ,
3139       options::OPT_fno_profile_instr_generate);
3140   if (ProfileGenerateArg &&
3141       ProfileGenerateArg->getOption().matches(
3142           options::OPT_fno_profile_instr_generate))
3143     ProfileGenerateArg = nullptr;
3144
3145   auto *ProfileUseArg = Args.getLastArg(
3146       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3147       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3148       options::OPT_fno_profile_instr_use);
3149   if (ProfileUseArg &&
3150       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3151     ProfileUseArg = nullptr;
3152
3153   if (ProfileGenerateArg && ProfileUseArg)
3154     D.Diag(diag::err_drv_argument_not_allowed_with)
3155         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3156
3157   if (ProfileGenerateArg) {
3158     if (ProfileGenerateArg->getOption().matches(
3159             options::OPT_fprofile_instr_generate_EQ))
3160       ProfileGenerateArg->render(Args, CmdArgs);
3161     else if (ProfileGenerateArg->getOption().matches(
3162                  options::OPT_fprofile_generate_EQ)) {
3163       SmallString<128> Path(ProfileGenerateArg->getValue());
3164       llvm::sys::path::append(Path, "default.profraw");
3165       CmdArgs.push_back(
3166           Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3167     } else
3168       Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3169   }
3170
3171   if (ProfileUseArg) {
3172     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3173       ProfileUseArg->render(Args, CmdArgs);
3174     else if ((ProfileUseArg->getOption().matches(
3175                   options::OPT_fprofile_use_EQ) ||
3176               ProfileUseArg->getOption().matches(
3177                   options::OPT_fprofile_instr_use))) {
3178       SmallString<128> Path(
3179           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3180       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3181         llvm::sys::path::append(Path, "default.profdata");
3182       CmdArgs.push_back(
3183           Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3184     }
3185   }
3186
3187   if (Args.hasArg(options::OPT_ftest_coverage) ||
3188       Args.hasArg(options::OPT_coverage))
3189     CmdArgs.push_back("-femit-coverage-notes");
3190   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3191                    false) ||
3192       Args.hasArg(options::OPT_coverage))
3193     CmdArgs.push_back("-femit-coverage-data");
3194
3195   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3196                    options::OPT_fno_coverage_mapping, false) &&
3197       !ProfileGenerateArg)
3198     D.Diag(diag::err_drv_argument_only_allowed_with)
3199         << "-fcoverage-mapping"
3200         << "-fprofile-instr-generate";
3201
3202   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3203                    options::OPT_fno_coverage_mapping, false))
3204     CmdArgs.push_back("-fcoverage-mapping");
3205
3206   if (C.getArgs().hasArg(options::OPT_c) ||
3207       C.getArgs().hasArg(options::OPT_S)) {
3208     if (Output.isFilename()) {
3209       CmdArgs.push_back("-coverage-file");
3210       SmallString<128> CoverageFilename;
3211       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3212         CoverageFilename = FinalOutput->getValue();
3213       } else {
3214         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3215       }
3216       if (llvm::sys::path::is_relative(CoverageFilename)) {
3217         SmallString<128> Pwd;
3218         if (!llvm::sys::fs::current_path(Pwd)) {
3219           llvm::sys::path::append(Pwd, CoverageFilename);
3220           CoverageFilename.swap(Pwd);
3221         }
3222       }
3223       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3224     }
3225   }
3226 }
3227
3228 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3229                                 ArgStringList &CmdArgs) {
3230   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3231                     false) ||
3232        Args.hasFlag(options::OPT_fprofile_generate,
3233                     options::OPT_fno_profile_instr_generate, false) ||
3234        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3235                     options::OPT_fno_profile_instr_generate, false) ||
3236        Args.hasFlag(options::OPT_fprofile_instr_generate,
3237                     options::OPT_fno_profile_instr_generate, false) ||
3238        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3239                     options::OPT_fno_profile_instr_generate, false) ||
3240        Args.hasArg(options::OPT_fcreate_profile) ||
3241        Args.hasArg(options::OPT_coverage)))
3242     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3243 }
3244
3245 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3246 /// smooshes them together with platform defaults, to decide whether
3247 /// this compile should be using PIC mode or not. Returns a tuple of
3248 /// (RelocationModel, PICLevel, IsPIE).
3249 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3250 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3251              const ArgList &Args) {
3252   // FIXME: why does this code...and so much everywhere else, use both
3253   // ToolChain.getTriple() and Triple?
3254   bool PIE = ToolChain.isPIEDefault();
3255   bool PIC = PIE || ToolChain.isPICDefault();
3256   // The Darwin default to use PIC does not apply when using -static.
3257   if (ToolChain.getTriple().isOSDarwin() && Args.hasArg(options::OPT_static))
3258     PIE = PIC = false;
3259   bool IsPICLevelTwo = PIC;
3260
3261   bool KernelOrKext =
3262       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3263
3264   // Android-specific defaults for PIC/PIE
3265   if (ToolChain.getTriple().isAndroid()) {
3266     switch (ToolChain.getArch()) {
3267     case llvm::Triple::arm:
3268     case llvm::Triple::armeb:
3269     case llvm::Triple::thumb:
3270     case llvm::Triple::thumbeb:
3271     case llvm::Triple::aarch64:
3272     case llvm::Triple::mips:
3273     case llvm::Triple::mipsel:
3274     case llvm::Triple::mips64:
3275     case llvm::Triple::mips64el:
3276       PIC = true; // "-fpic"
3277       break;
3278
3279     case llvm::Triple::x86:
3280     case llvm::Triple::x86_64:
3281       PIC = true; // "-fPIC"
3282       IsPICLevelTwo = true;
3283       break;
3284
3285     default:
3286       break;
3287     }
3288   }
3289
3290   // OpenBSD-specific defaults for PIE
3291   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3292     switch (ToolChain.getArch()) {
3293     case llvm::Triple::mips64:
3294     case llvm::Triple::mips64el:
3295     case llvm::Triple::sparcel:
3296     case llvm::Triple::x86:
3297     case llvm::Triple::x86_64:
3298       IsPICLevelTwo = false; // "-fpie"
3299       break;
3300
3301     case llvm::Triple::ppc:
3302     case llvm::Triple::sparc:
3303     case llvm::Triple::sparcv9:
3304       IsPICLevelTwo = true; // "-fPIE"
3305       break;
3306
3307     default:
3308       break;
3309     }
3310   }
3311
3312   // The last argument relating to either PIC or PIE wins, and no
3313   // other argument is used. If the last argument is any flavor of the
3314   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3315   // option implicitly enables PIC at the same level.
3316   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3317                                     options::OPT_fpic, options::OPT_fno_pic,
3318                                     options::OPT_fPIE, options::OPT_fno_PIE,
3319                                     options::OPT_fpie, options::OPT_fno_pie);
3320   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3321   // is forced, then neither PIC nor PIE flags will have no effect.
3322   if (!ToolChain.isPICDefaultForced()) {
3323     if (LastPICArg) {
3324       Option O = LastPICArg->getOption();
3325       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3326           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3327         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3328         PIC =
3329             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3330         IsPICLevelTwo =
3331             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3332       } else {
3333         PIE = PIC = false;
3334         if (Triple.isPS4CPU()) {
3335           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3336           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3337           if (Model != "kernel") {
3338             PIC = true;
3339             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3340                 << LastPICArg->getSpelling();
3341           }
3342         }
3343       }
3344     }
3345   }
3346
3347   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3348   // PIC level would've been set to level 1, force it back to level 2 PIC
3349   // instead.
3350   if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3351     IsPICLevelTwo |= ToolChain.isPICDefault();
3352
3353   // This kernel flags are a trump-card: they will disable PIC/PIE
3354   // generation, independent of the argument order.
3355   if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3356                        !Triple.isWatchOS()))
3357     PIC = PIE = false;
3358
3359   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3360     // This is a very special mode. It trumps the other modes, almost no one
3361     // uses it, and it isn't even valid on any OS but Darwin.
3362     if (!ToolChain.getTriple().isOSDarwin())
3363       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3364           << A->getSpelling() << ToolChain.getTriple().str();
3365
3366     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3367
3368     // Only a forced PIC mode can cause the actual compile to have PIC defines
3369     // etc., no flags are sufficient. This behavior was selected to closely
3370     // match that of llvm-gcc and Apple GCC before that.
3371     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3372
3373     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3374   }
3375
3376   if (PIC)
3377     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3378
3379   return std::make_tuple(llvm::Reloc::Static, 0, false);
3380 }
3381
3382 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3383   switch (Model) {
3384   case llvm::Reloc::Default:
3385     return nullptr;
3386   case llvm::Reloc::Static:
3387     return "static";
3388   case llvm::Reloc::PIC_:
3389     return "pic";
3390   case llvm::Reloc::DynamicNoPIC:
3391     return "dynamic-no-pic";
3392   }
3393   llvm_unreachable("Unknown Reloc::Model kind");
3394 }
3395
3396 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3397                              ArgStringList &CmdArgs) {
3398   llvm::Reloc::Model RelocationModel;
3399   unsigned PICLevel;
3400   bool IsPIE;
3401   std::tie(RelocationModel, PICLevel, IsPIE) =
3402       ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3403
3404   if (RelocationModel != llvm::Reloc::Static)
3405     CmdArgs.push_back("-KPIC");
3406 }
3407
3408 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3409                          const InputInfo &Output, const InputInfoList &Inputs,
3410                          const ArgList &Args, const char *LinkingOutput) const {
3411   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3412   const llvm::Triple Triple(TripleStr);
3413
3414   bool KernelOrKext =
3415       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3416   const Driver &D = getToolChain().getDriver();
3417   ArgStringList CmdArgs;
3418
3419   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3420   bool IsWindowsCygnus =
3421       getToolChain().getTriple().isWindowsCygwinEnvironment();
3422   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3423   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3424
3425   // Check number of inputs for sanity. We need at least one input.
3426   assert(Inputs.size() >= 1 && "Must have at least one input.");
3427   const InputInfo &Input = Inputs[0];
3428   // CUDA compilation may have multiple inputs (source file + results of
3429   // device-side compilations). All other jobs are expected to have exactly one
3430   // input.
3431   bool IsCuda = types::isCuda(Input.getType());
3432   assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3433
3434   // Invoke ourselves in -cc1 mode.
3435   //
3436   // FIXME: Implement custom jobs for internal actions.
3437   CmdArgs.push_back("-cc1");
3438
3439   // Add the "effective" target triple.
3440   CmdArgs.push_back("-triple");
3441   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3442
3443   const ToolChain *AuxToolChain = nullptr;
3444   if (IsCuda) {
3445     // FIXME: We need a (better) way to pass information about
3446     // particular compilation pass we're constructing here. For now we
3447     // can check which toolchain we're using and pick the other one to
3448     // extract the triple.
3449     if (&getToolChain() == C.getCudaDeviceToolChain())
3450       AuxToolChain = C.getCudaHostToolChain();
3451     else if (&getToolChain() == C.getCudaHostToolChain())
3452       AuxToolChain = C.getCudaDeviceToolChain();
3453     else
3454       llvm_unreachable("Can't figure out CUDA compilation mode.");
3455     assert(AuxToolChain != nullptr && "No aux toolchain.");
3456     CmdArgs.push_back("-aux-triple");
3457     CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3458     CmdArgs.push_back("-fcuda-target-overloads");
3459     CmdArgs.push_back("-fcuda-disable-target-call-checks");
3460   }
3461
3462   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3463                                Triple.getArch() == llvm::Triple::thumb)) {
3464     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3465     unsigned Version;
3466     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3467     if (Version < 7)
3468       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3469                                                 << TripleStr;
3470   }
3471
3472   // Push all default warning arguments that are specific to
3473   // the given target.  These come before user provided warning options
3474   // are provided.
3475   getToolChain().addClangWarningOptions(CmdArgs);
3476
3477   // Select the appropriate action.
3478   RewriteKind rewriteKind = RK_None;
3479
3480   if (isa<AnalyzeJobAction>(JA)) {
3481     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3482     CmdArgs.push_back("-analyze");
3483   } else if (isa<MigrateJobAction>(JA)) {
3484     CmdArgs.push_back("-migrate");
3485   } else if (isa<PreprocessJobAction>(JA)) {
3486     if (Output.getType() == types::TY_Dependencies)
3487       CmdArgs.push_back("-Eonly");
3488     else {
3489       CmdArgs.push_back("-E");
3490       if (Args.hasArg(options::OPT_rewrite_objc) &&
3491           !Args.hasArg(options::OPT_g_Group))
3492         CmdArgs.push_back("-P");
3493     }
3494   } else if (isa<AssembleJobAction>(JA)) {
3495     CmdArgs.push_back("-emit-obj");
3496
3497     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3498
3499     // Also ignore explicit -force_cpusubtype_ALL option.
3500     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3501   } else if (isa<PrecompileJobAction>(JA)) {
3502     // Use PCH if the user requested it.
3503     bool UsePCH = D.CCCUsePCH;
3504
3505     if (JA.getType() == types::TY_Nothing)
3506       CmdArgs.push_back("-fsyntax-only");
3507     else if (UsePCH)
3508       CmdArgs.push_back("-emit-pch");
3509     else
3510       CmdArgs.push_back("-emit-pth");
3511   } else if (isa<VerifyPCHJobAction>(JA)) {
3512     CmdArgs.push_back("-verify-pch");
3513   } else {
3514     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3515            "Invalid action for clang tool.");
3516     if (JA.getType() == types::TY_Nothing) {
3517       CmdArgs.push_back("-fsyntax-only");
3518     } else if (JA.getType() == types::TY_LLVM_IR ||
3519                JA.getType() == types::TY_LTO_IR) {
3520       CmdArgs.push_back("-emit-llvm");
3521     } else if (JA.getType() == types::TY_LLVM_BC ||
3522                JA.getType() == types::TY_LTO_BC) {
3523       CmdArgs.push_back("-emit-llvm-bc");
3524     } else if (JA.getType() == types::TY_PP_Asm) {
3525       CmdArgs.push_back("-S");
3526     } else if (JA.getType() == types::TY_AST) {
3527       CmdArgs.push_back("-emit-pch");
3528     } else if (JA.getType() == types::TY_ModuleFile) {
3529       CmdArgs.push_back("-module-file-info");
3530     } else if (JA.getType() == types::TY_RewrittenObjC) {
3531       CmdArgs.push_back("-rewrite-objc");
3532       rewriteKind = RK_NonFragile;
3533     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3534       CmdArgs.push_back("-rewrite-objc");
3535       rewriteKind = RK_Fragile;
3536     } else {
3537       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3538     }
3539
3540     // Preserve use-list order by default when emitting bitcode, so that
3541     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3542     // same result as running passes here.  For LTO, we don't need to preserve
3543     // the use-list order, since serialization to bitcode is part of the flow.
3544     if (JA.getType() == types::TY_LLVM_BC)
3545       CmdArgs.push_back("-emit-llvm-uselists");
3546
3547     if (D.isUsingLTO())
3548       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3549   }
3550
3551   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3552     if (!types::isLLVMIR(Input.getType()))
3553       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3554                                                        << "-x ir";
3555     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3556   }
3557
3558   // We normally speed up the clang process a bit by skipping destructors at
3559   // exit, but when we're generating diagnostics we can rely on some of the
3560   // cleanup.
3561   if (!C.isForDiagnostics())
3562     CmdArgs.push_back("-disable-free");
3563
3564 // Disable the verification pass in -asserts builds.
3565 #ifdef NDEBUG
3566   CmdArgs.push_back("-disable-llvm-verifier");
3567 #endif
3568
3569   // Set the main file name, so that debug info works even with
3570   // -save-temps.
3571   CmdArgs.push_back("-main-file-name");
3572   CmdArgs.push_back(getBaseInputName(Args, Input));
3573
3574   // Some flags which affect the language (via preprocessor
3575   // defines).
3576   if (Args.hasArg(options::OPT_static))
3577     CmdArgs.push_back("-static-define");
3578
3579   if (isa<AnalyzeJobAction>(JA)) {
3580     // Enable region store model by default.
3581     CmdArgs.push_back("-analyzer-store=region");
3582
3583     // Treat blocks as analysis entry points.
3584     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3585
3586     CmdArgs.push_back("-analyzer-eagerly-assume");
3587
3588     // Add default argument set.
3589     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3590       CmdArgs.push_back("-analyzer-checker=core");
3591
3592       if (!IsWindowsMSVC)
3593         CmdArgs.push_back("-analyzer-checker=unix");
3594
3595       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3596         CmdArgs.push_back("-analyzer-checker=osx");
3597
3598       CmdArgs.push_back("-analyzer-checker=deadcode");
3599
3600       if (types::isCXX(Input.getType()))
3601         CmdArgs.push_back("-analyzer-checker=cplusplus");
3602
3603       // Enable the following experimental checkers for testing.
3604       CmdArgs.push_back(
3605           "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3606       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3607       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3608       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3609       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3610       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3611
3612       // Default nullability checks.
3613       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3614       CmdArgs.push_back(
3615           "-analyzer-checker=nullability.NullReturnedFromNonnull");
3616     }
3617
3618     // Set the output format. The default is plist, for (lame) historical
3619     // reasons.
3620     CmdArgs.push_back("-analyzer-output");
3621     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3622       CmdArgs.push_back(A->getValue());
3623     else
3624       CmdArgs.push_back("plist");
3625
3626     // Disable the presentation of standard compiler warnings when
3627     // using --analyze.  We only want to show static analyzer diagnostics
3628     // or frontend errors.
3629     CmdArgs.push_back("-w");
3630
3631     // Add -Xanalyzer arguments when running as analyzer.
3632     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3633   }
3634
3635   CheckCodeGenerationOptions(D, Args);
3636
3637   llvm::Reloc::Model RelocationModel;
3638   unsigned PICLevel;
3639   bool IsPIE;
3640   std::tie(RelocationModel, PICLevel, IsPIE) =
3641       ParsePICArgs(getToolChain(), Triple, Args);
3642
3643   const char *RMName = RelocationModelName(RelocationModel);
3644   if (RMName) {
3645     CmdArgs.push_back("-mrelocation-model");
3646     CmdArgs.push_back(RMName);
3647   }
3648   if (PICLevel > 0) {
3649     CmdArgs.push_back("-pic-level");
3650     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3651     if (IsPIE) {
3652       CmdArgs.push_back("-pie-level");
3653       CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3654     }
3655   }
3656
3657   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3658     CmdArgs.push_back("-meabi");
3659     CmdArgs.push_back(A->getValue());
3660   }
3661
3662   CmdArgs.push_back("-mthread-model");
3663   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3664     CmdArgs.push_back(A->getValue());
3665   else
3666     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3667
3668   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3669
3670   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3671                     options::OPT_fno_merge_all_constants))
3672     CmdArgs.push_back("-fno-merge-all-constants");
3673
3674   // LLVM Code Generator Options.
3675
3676   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3677       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3678     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3679                                       options::OPT_frewrite_map_file_EQ)) {
3680       CmdArgs.push_back("-frewrite-map-file");
3681       CmdArgs.push_back(A->getValue());
3682       A->claim();
3683     }
3684   }
3685
3686   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3687     StringRef v = A->getValue();
3688     CmdArgs.push_back("-mllvm");
3689     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3690     A->claim();
3691   }
3692
3693   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3694     CmdArgs.push_back("-mregparm");
3695     CmdArgs.push_back(A->getValue());
3696   }
3697
3698   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3699                                options::OPT_freg_struct_return)) {
3700     if (getToolChain().getArch() != llvm::Triple::x86) {
3701       D.Diag(diag::err_drv_unsupported_opt_for_target)
3702           << A->getSpelling() << getToolChain().getTriple().str();
3703     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3704       CmdArgs.push_back("-fpcc-struct-return");
3705     } else {
3706       assert(A->getOption().matches(options::OPT_freg_struct_return));
3707       CmdArgs.push_back("-freg-struct-return");
3708     }
3709   }
3710
3711   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3712     CmdArgs.push_back("-mrtd");
3713
3714   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3715     CmdArgs.push_back("-mdisable-fp-elim");
3716   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3717                     options::OPT_fno_zero_initialized_in_bss))
3718     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3719
3720   bool OFastEnabled = isOptimizationLevelFast(Args);
3721   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3722   // enabled.  This alias option is being used to simplify the hasFlag logic.
3723   OptSpecifier StrictAliasingAliasOption =
3724       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3725   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3726   // doesn't do any TBAA.
3727   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3728   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3729                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3730     CmdArgs.push_back("-relaxed-aliasing");
3731   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3732                     options::OPT_fno_struct_path_tbaa))
3733     CmdArgs.push_back("-no-struct-path-tbaa");
3734   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3735                    false))
3736     CmdArgs.push_back("-fstrict-enums");
3737   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3738                    options::OPT_fno_strict_vtable_pointers,
3739                    false))
3740     CmdArgs.push_back("-fstrict-vtable-pointers");
3741   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3742                     options::OPT_fno_optimize_sibling_calls))
3743     CmdArgs.push_back("-mdisable-tail-calls");
3744
3745   // Handle segmented stacks.
3746   if (Args.hasArg(options::OPT_fsplit_stack))
3747     CmdArgs.push_back("-split-stacks");
3748
3749   // If -Ofast is the optimization level, then -ffast-math should be enabled.
3750   // This alias option is being used to simplify the getLastArg logic.
3751   OptSpecifier FastMathAliasOption =
3752       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3753
3754   // Handle various floating point optimization flags, mapping them to the
3755   // appropriate LLVM code generation flags. The pattern for all of these is to
3756   // default off the codegen optimizations, and if any flag enables them and no
3757   // flag disables them after the flag enabling them, enable the codegen
3758   // optimization. This is complicated by several "umbrella" flags.
3759   if (Arg *A = Args.getLastArg(
3760           options::OPT_ffast_math, FastMathAliasOption,
3761           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3762           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3763           options::OPT_fno_honor_infinities))
3764     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3765         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3766         A->getOption().getID() != options::OPT_fhonor_infinities)
3767       CmdArgs.push_back("-menable-no-infs");
3768   if (Arg *A = Args.getLastArg(
3769           options::OPT_ffast_math, FastMathAliasOption,
3770           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3771           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3772           options::OPT_fno_honor_nans))
3773     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3774         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3775         A->getOption().getID() != options::OPT_fhonor_nans)
3776       CmdArgs.push_back("-menable-no-nans");
3777
3778   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3779   bool MathErrno = getToolChain().IsMathErrnoDefault();
3780   if (Arg *A =
3781           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3782                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
3783                           options::OPT_fno_math_errno)) {
3784     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3785     // However, turning *off* -ffast_math merely restores the toolchain default
3786     // (which may be false).
3787     if (A->getOption().getID() == options::OPT_fno_math_errno ||
3788         A->getOption().getID() == options::OPT_ffast_math ||
3789         A->getOption().getID() == options::OPT_Ofast)
3790       MathErrno = false;
3791     else if (A->getOption().getID() == options::OPT_fmath_errno)
3792       MathErrno = true;
3793   }
3794   if (MathErrno)
3795     CmdArgs.push_back("-fmath-errno");
3796
3797   // There are several flags which require disabling very specific
3798   // optimizations. Any of these being disabled forces us to turn off the
3799   // entire set of LLVM optimizations, so collect them through all the flag
3800   // madness.
3801   bool AssociativeMath = false;
3802   if (Arg *A = Args.getLastArg(
3803           options::OPT_ffast_math, FastMathAliasOption,
3804           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3805           options::OPT_fno_unsafe_math_optimizations,
3806           options::OPT_fassociative_math, options::OPT_fno_associative_math))
3807     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3808         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3809         A->getOption().getID() != options::OPT_fno_associative_math)
3810       AssociativeMath = true;
3811   bool ReciprocalMath = false;
3812   if (Arg *A = Args.getLastArg(
3813           options::OPT_ffast_math, FastMathAliasOption,
3814           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3815           options::OPT_fno_unsafe_math_optimizations,
3816           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3817     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3818         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3819         A->getOption().getID() != options::OPT_fno_reciprocal_math)
3820       ReciprocalMath = true;
3821   bool SignedZeros = true;
3822   if (Arg *A = Args.getLastArg(
3823           options::OPT_ffast_math, FastMathAliasOption,
3824           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3825           options::OPT_fno_unsafe_math_optimizations,
3826           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3827     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3828         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3829         A->getOption().getID() != options::OPT_fsigned_zeros)
3830       SignedZeros = false;
3831   bool TrappingMath = true;
3832   if (Arg *A = Args.getLastArg(
3833           options::OPT_ffast_math, FastMathAliasOption,
3834           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3835           options::OPT_fno_unsafe_math_optimizations,
3836           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3837     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3838         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3839         A->getOption().getID() != options::OPT_ftrapping_math)
3840       TrappingMath = false;
3841   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3842       !TrappingMath)
3843     CmdArgs.push_back("-menable-unsafe-fp-math");
3844
3845   if (!SignedZeros)
3846     CmdArgs.push_back("-fno-signed-zeros");
3847
3848   if (ReciprocalMath)
3849     CmdArgs.push_back("-freciprocal-math");
3850
3851   // Validate and pass through -fp-contract option.
3852   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3853                                options::OPT_fno_fast_math,
3854                                options::OPT_ffp_contract)) {
3855     if (A->getOption().getID() == options::OPT_ffp_contract) {
3856       StringRef Val = A->getValue();
3857       if (Val == "fast" || Val == "on" || Val == "off") {
3858         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3859       } else {
3860         D.Diag(diag::err_drv_unsupported_option_argument)
3861             << A->getOption().getName() << Val;
3862       }
3863     } else if (A->getOption().matches(options::OPT_ffast_math) ||
3864                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3865       // If fast-math is set then set the fp-contract mode to fast.
3866       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3867     }
3868   }
3869
3870   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3871
3872   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3873   // and if we find them, tell the frontend to provide the appropriate
3874   // preprocessor macros. This is distinct from enabling any optimizations as
3875   // these options induce language changes which must survive serialization
3876   // and deserialization, etc.
3877   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3878                                options::OPT_fno_fast_math))
3879     if (!A->getOption().matches(options::OPT_fno_fast_math))
3880       CmdArgs.push_back("-ffast-math");
3881   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3882                                options::OPT_fno_fast_math))
3883     if (A->getOption().matches(options::OPT_ffinite_math_only))
3884       CmdArgs.push_back("-ffinite-math-only");
3885
3886   // Decide whether to use verbose asm. Verbose assembly is the default on
3887   // toolchains which have the integrated assembler on by default.
3888   bool IsIntegratedAssemblerDefault =
3889       getToolChain().IsIntegratedAssemblerDefault();
3890   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3891                    IsIntegratedAssemblerDefault) ||
3892       Args.hasArg(options::OPT_dA))
3893     CmdArgs.push_back("-masm-verbose");
3894
3895   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3896                     IsIntegratedAssemblerDefault))
3897     CmdArgs.push_back("-no-integrated-as");
3898
3899   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3900     CmdArgs.push_back("-mdebug-pass");
3901     CmdArgs.push_back("Structure");
3902   }
3903   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3904     CmdArgs.push_back("-mdebug-pass");
3905     CmdArgs.push_back("Arguments");
3906   }
3907
3908   // Enable -mconstructor-aliases except on darwin, where we have to
3909   // work around a linker bug;  see <rdar://problem/7651567>.
3910   if (!getToolChain().getTriple().isOSDarwin())
3911     CmdArgs.push_back("-mconstructor-aliases");
3912
3913   // Darwin's kernel doesn't support guard variables; just die if we
3914   // try to use them.
3915   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3916     CmdArgs.push_back("-fforbid-guard-variables");
3917
3918   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3919                    false)) {
3920     CmdArgs.push_back("-mms-bitfields");
3921   }
3922
3923   // This is a coarse approximation of what llvm-gcc actually does, both
3924   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3925   // complicated ways.
3926   bool AsynchronousUnwindTables =
3927       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3928                    options::OPT_fno_asynchronous_unwind_tables,
3929                    (getToolChain().IsUnwindTablesDefault() ||
3930                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3931                        !KernelOrKext);
3932   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3933                    AsynchronousUnwindTables))
3934     CmdArgs.push_back("-munwind-tables");
3935
3936   getToolChain().addClangTargetOptions(Args, CmdArgs);
3937
3938   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3939     CmdArgs.push_back("-mlimit-float-precision");
3940     CmdArgs.push_back(A->getValue());
3941   }
3942
3943   // FIXME: Handle -mtune=.
3944   (void)Args.hasArg(options::OPT_mtune_EQ);
3945
3946   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3947     CmdArgs.push_back("-mcode-model");
3948     CmdArgs.push_back(A->getValue());
3949   }
3950
3951   // Add the target cpu
3952   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3953   if (!CPU.empty()) {
3954     CmdArgs.push_back("-target-cpu");
3955     CmdArgs.push_back(Args.MakeArgString(CPU));
3956   }
3957
3958   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3959     CmdArgs.push_back("-mfpmath");
3960     CmdArgs.push_back(A->getValue());
3961   }
3962
3963   // Add the target features
3964   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3965
3966   // Add target specific flags.
3967   switch (getToolChain().getArch()) {
3968   default:
3969     break;
3970
3971   case llvm::Triple::arm:
3972   case llvm::Triple::armeb:
3973   case llvm::Triple::thumb:
3974   case llvm::Triple::thumbeb:
3975     // Use the effective triple, which takes into account the deployment target.
3976     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3977     break;
3978
3979   case llvm::Triple::aarch64:
3980   case llvm::Triple::aarch64_be:
3981     AddAArch64TargetArgs(Args, CmdArgs);
3982     break;
3983
3984   case llvm::Triple::mips:
3985   case llvm::Triple::mipsel:
3986   case llvm::Triple::mips64:
3987   case llvm::Triple::mips64el:
3988     AddMIPSTargetArgs(Args, CmdArgs);
3989     break;
3990
3991   case llvm::Triple::ppc:
3992   case llvm::Triple::ppc64:
3993   case llvm::Triple::ppc64le:
3994     AddPPCTargetArgs(Args, CmdArgs);
3995     break;
3996
3997   case llvm::Triple::sparc:
3998   case llvm::Triple::sparcel:
3999   case llvm::Triple::sparcv9:
4000     AddSparcTargetArgs(Args, CmdArgs);
4001     break;
4002
4003   case llvm::Triple::x86:
4004   case llvm::Triple::x86_64:
4005     AddX86TargetArgs(Args, CmdArgs);
4006     break;
4007
4008   case llvm::Triple::hexagon:
4009     AddHexagonTargetArgs(Args, CmdArgs);
4010     break;
4011   }
4012
4013   // The 'g' groups options involve a somewhat intricate sequence of decisions
4014   // about what to pass from the driver to the frontend, but by the time they
4015   // reach cc1 they've been factored into three well-defined orthogonal choices:
4016   //  * what level of debug info to generate
4017   //  * what dwarf version to write
4018   //  * what debugger tuning to use
4019   // This avoids having to monkey around further in cc1 other than to disable
4020   // codeview if not running in a Windows environment. Perhaps even that
4021   // decision should be made in the driver as well though.
4022   unsigned DwarfVersion = 0;
4023   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4024   // These two are potentially updated by AddClangCLArgs.
4025   enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4026       CodeGenOptions::NoDebugInfo;
4027   bool EmitCodeView = false;
4028
4029   // Add clang-cl arguments.
4030   if (getToolChain().getDriver().IsCLMode())
4031     AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4032
4033   // Pass the linker version in use.
4034   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4035     CmdArgs.push_back("-target-linker-version");
4036     CmdArgs.push_back(A->getValue());
4037   }
4038
4039   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4040     CmdArgs.push_back("-momit-leaf-frame-pointer");
4041
4042   // Explicitly error on some things we know we don't support and can't just
4043   // ignore.
4044   types::ID InputType = Input.getType();
4045   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4046     Arg *Unsupported;
4047     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4048         getToolChain().getArch() == llvm::Triple::x86) {
4049       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4050           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4051         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4052             << Unsupported->getOption().getName();
4053     }
4054   }
4055
4056   Args.AddAllArgs(CmdArgs, options::OPT_v);
4057   Args.AddLastArg(CmdArgs, options::OPT_H);
4058   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4059     CmdArgs.push_back("-header-include-file");
4060     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4061                                                : "-");
4062   }
4063   Args.AddLastArg(CmdArgs, options::OPT_P);
4064   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4065
4066   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4067     CmdArgs.push_back("-diagnostic-log-file");
4068     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4069                                                  : "-");
4070   }
4071
4072   Args.ClaimAllArgs(options::OPT_g_Group);
4073   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4074   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4075     // If the last option explicitly specified a debug-info level, use it.
4076     if (A->getOption().matches(options::OPT_gN_Group)) {
4077       DebugInfoKind = DebugLevelToInfoKind(*A);
4078       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4079       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4080       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4081       if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4082           A->getIndex() > SplitDwarfArg->getIndex())
4083         SplitDwarfArg = nullptr;
4084     } else
4085       // For any other 'g' option, use Limited.
4086       DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4087   }
4088
4089   // If a debugger tuning argument appeared, remember it.
4090   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4091                                options::OPT_ggdbN_Group)) {
4092     if (A->getOption().matches(options::OPT_glldb))
4093       DebuggerTuning = llvm::DebuggerKind::LLDB;
4094     else if (A->getOption().matches(options::OPT_gsce))
4095       DebuggerTuning = llvm::DebuggerKind::SCE;
4096     else
4097       DebuggerTuning = llvm::DebuggerKind::GDB;
4098   }
4099
4100   // If a -gdwarf argument appeared, remember it.
4101   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4102                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4103     DwarfVersion = DwarfVersionNum(A->getSpelling());
4104
4105   // Forward -gcodeview.
4106   // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4107   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4108     // DwarfVersion remains at 0 if no explicit choice was made.
4109     CmdArgs.push_back("-gcodeview");
4110   } else if (DwarfVersion == 0 &&
4111              DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4112     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4113   }
4114
4115   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4116   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4117
4118   // PS4 defaults to no column info
4119   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4120                    /*Default=*/ !IsPS4CPU))
4121     CmdArgs.push_back("-dwarf-column-info");
4122
4123   // FIXME: Move backend command line options to the module.
4124   if (Args.hasArg(options::OPT_gmodules)) {
4125     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4126     CmdArgs.push_back("-dwarf-ext-refs");
4127     CmdArgs.push_back("-fmodule-format=obj");
4128   }
4129
4130   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4131   // splitting and extraction.
4132   // FIXME: Currently only works on Linux.
4133   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4134     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4135     CmdArgs.push_back("-backend-option");
4136     CmdArgs.push_back("-split-dwarf=Enable");
4137   }
4138
4139   // After we've dealt with all combinations of things that could
4140   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4141   // figure out if we need to "upgrade" it to standalone debug info.
4142   // We parse these two '-f' options whether or not they will be used,
4143   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4144   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4145                                     options::OPT_fno_standalone_debug,
4146                                     getToolChain().GetDefaultStandaloneDebug());
4147   if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4148     DebugInfoKind = CodeGenOptions::FullDebugInfo;
4149   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4150                           DebuggerTuning);
4151
4152   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4153   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4154     CmdArgs.push_back("-backend-option");
4155     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4156   }
4157
4158   // -gdwarf-aranges turns on the emission of the aranges section in the
4159   // backend.
4160   // Always enabled on the PS4.
4161   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4162     CmdArgs.push_back("-backend-option");
4163     CmdArgs.push_back("-generate-arange-section");
4164   }
4165
4166   if (Args.hasFlag(options::OPT_fdebug_types_section,
4167                    options::OPT_fno_debug_types_section, false)) {
4168     CmdArgs.push_back("-backend-option");
4169     CmdArgs.push_back("-generate-type-units");
4170   }
4171
4172   // CloudABI uses -ffunction-sections and -fdata-sections by default.
4173   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
4174
4175   if (Args.hasFlag(options::OPT_ffunction_sections,
4176                    options::OPT_fno_function_sections, UseSeparateSections)) {
4177     CmdArgs.push_back("-ffunction-sections");
4178   }
4179
4180   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4181                    UseSeparateSections)) {
4182     CmdArgs.push_back("-fdata-sections");
4183   }
4184
4185   if (!Args.hasFlag(options::OPT_funique_section_names,
4186                     options::OPT_fno_unique_section_names, true))
4187     CmdArgs.push_back("-fno-unique-section-names");
4188
4189   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4190
4191   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4192
4193   // Add runtime flag for PS4 when PGO or Coverage are enabled.
4194   if (getToolChain().getTriple().isPS4CPU())
4195     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4196
4197   // Pass options for controlling the default header search paths.
4198   if (Args.hasArg(options::OPT_nostdinc)) {
4199     CmdArgs.push_back("-nostdsysteminc");
4200     CmdArgs.push_back("-nobuiltininc");
4201   } else {
4202     if (Args.hasArg(options::OPT_nostdlibinc))
4203       CmdArgs.push_back("-nostdsysteminc");
4204     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4205     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4206   }
4207
4208   // Pass the path to compiler resource files.
4209   CmdArgs.push_back("-resource-dir");
4210   CmdArgs.push_back(D.ResourceDir.c_str());
4211
4212   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4213
4214   bool ARCMTEnabled = false;
4215   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4216     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4217                                        options::OPT_ccc_arcmt_modify,
4218                                        options::OPT_ccc_arcmt_migrate)) {
4219       ARCMTEnabled = true;
4220       switch (A->getOption().getID()) {
4221       default:
4222         llvm_unreachable("missed a case");
4223       case options::OPT_ccc_arcmt_check:
4224         CmdArgs.push_back("-arcmt-check");
4225         break;
4226       case options::OPT_ccc_arcmt_modify:
4227         CmdArgs.push_back("-arcmt-modify");
4228         break;
4229       case options::OPT_ccc_arcmt_migrate:
4230         CmdArgs.push_back("-arcmt-migrate");
4231         CmdArgs.push_back("-mt-migrate-directory");
4232         CmdArgs.push_back(A->getValue());
4233
4234         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4235         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4236         break;
4237       }
4238     }
4239   } else {
4240     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4241     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4242     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4243   }
4244
4245   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4246     if (ARCMTEnabled) {
4247       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4248                                                       << "-ccc-arcmt-migrate";
4249     }
4250     CmdArgs.push_back("-mt-migrate-directory");
4251     CmdArgs.push_back(A->getValue());
4252
4253     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4254                      options::OPT_objcmt_migrate_subscripting,
4255                      options::OPT_objcmt_migrate_property)) {
4256       // None specified, means enable them all.
4257       CmdArgs.push_back("-objcmt-migrate-literals");
4258       CmdArgs.push_back("-objcmt-migrate-subscripting");
4259       CmdArgs.push_back("-objcmt-migrate-property");
4260     } else {
4261       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4262       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4263       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4264     }
4265   } else {
4266     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4267     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4268     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4269     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4270     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4271     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4272     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4273     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4274     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4275     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4276     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4277     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4278     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4279     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4280     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4281     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4282   }
4283
4284   // Add preprocessing options like -I, -D, etc. if we are using the
4285   // preprocessor.
4286   //
4287   // FIXME: Support -fpreprocessed
4288   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4289     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4290                             AuxToolChain);
4291
4292   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4293   // that "The compiler can only warn and ignore the option if not recognized".
4294   // When building with ccache, it will pass -D options to clang even on
4295   // preprocessed inputs and configure concludes that -fPIC is not supported.
4296   Args.ClaimAllArgs(options::OPT_D);
4297
4298   // Manually translate -O4 to -O3; let clang reject others.
4299   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4300     if (A->getOption().matches(options::OPT_O4)) {
4301       CmdArgs.push_back("-O3");
4302       D.Diag(diag::warn_O4_is_O3);
4303     } else {
4304       A->render(Args, CmdArgs);
4305     }
4306   }
4307
4308   // Warn about ignored options to clang.
4309   for (const Arg *A :
4310        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4311     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4312     A->claim();
4313   }
4314
4315   claimNoWarnArgs(Args);
4316
4317   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4318   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4319   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4320     CmdArgs.push_back("-pedantic");
4321   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4322   Args.AddLastArg(CmdArgs, options::OPT_w);
4323
4324   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4325   // (-ansi is equivalent to -std=c89 or -std=c++98).
4326   //
4327   // If a std is supplied, only add -trigraphs if it follows the
4328   // option.
4329   bool ImplyVCPPCXXVer = false;
4330   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4331     if (Std->getOption().matches(options::OPT_ansi))
4332       if (types::isCXX(InputType))
4333         CmdArgs.push_back("-std=c++98");
4334       else
4335         CmdArgs.push_back("-std=c89");
4336     else
4337       Std->render(Args, CmdArgs);
4338
4339     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4340     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4341                                  options::OPT_ftrigraphs,
4342                                  options::OPT_fno_trigraphs))
4343       if (A != Std)
4344         A->render(Args, CmdArgs);
4345   } else {
4346     // Honor -std-default.
4347     //
4348     // FIXME: Clang doesn't correctly handle -std= when the input language
4349     // doesn't match. For the time being just ignore this for C++ inputs;
4350     // eventually we want to do all the standard defaulting here instead of
4351     // splitting it between the driver and clang -cc1.
4352     if (!types::isCXX(InputType))
4353       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4354                                 /*Joined=*/true);
4355     else if (IsWindowsMSVC)
4356       ImplyVCPPCXXVer = true;
4357
4358     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4359                     options::OPT_fno_trigraphs);
4360   }
4361
4362   // GCC's behavior for -Wwrite-strings is a bit strange:
4363   //  * In C, this "warning flag" changes the types of string literals from
4364   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4365   //    for the discarded qualifier.
4366   //  * In C++, this is just a normal warning flag.
4367   //
4368   // Implementing this warning correctly in C is hard, so we follow GCC's
4369   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4370   // a non-const char* in C, rather than using this crude hack.
4371   if (!types::isCXX(InputType)) {
4372     // FIXME: This should behave just like a warning flag, and thus should also
4373     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4374     Arg *WriteStrings =
4375         Args.getLastArg(options::OPT_Wwrite_strings,
4376                         options::OPT_Wno_write_strings, options::OPT_w);
4377     if (WriteStrings &&
4378         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4379       CmdArgs.push_back("-fconst-strings");
4380   }
4381
4382   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4383   // during C++ compilation, which it is by default. GCC keeps this define even
4384   // in the presence of '-w', match this behavior bug-for-bug.
4385   if (types::isCXX(InputType) &&
4386       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4387                    true)) {
4388     CmdArgs.push_back("-fdeprecated-macro");
4389   }
4390
4391   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4392   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4393     if (Asm->getOption().matches(options::OPT_fasm))
4394       CmdArgs.push_back("-fgnu-keywords");
4395     else
4396       CmdArgs.push_back("-fno-gnu-keywords");
4397   }
4398
4399   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4400     CmdArgs.push_back("-fno-dwarf-directory-asm");
4401
4402   if (ShouldDisableAutolink(Args, getToolChain()))
4403     CmdArgs.push_back("-fno-autolink");
4404
4405   // Add in -fdebug-compilation-dir if necessary.
4406   addDebugCompDirArg(Args, CmdArgs);
4407
4408   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4409     StringRef Map = A->getValue();
4410     if (Map.find('=') == StringRef::npos)
4411       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4412     else
4413       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4414     A->claim();
4415   }
4416
4417   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4418                                options::OPT_ftemplate_depth_EQ)) {
4419     CmdArgs.push_back("-ftemplate-depth");
4420     CmdArgs.push_back(A->getValue());
4421   }
4422
4423   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4424     CmdArgs.push_back("-foperator-arrow-depth");
4425     CmdArgs.push_back(A->getValue());
4426   }
4427
4428   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4429     CmdArgs.push_back("-fconstexpr-depth");
4430     CmdArgs.push_back(A->getValue());
4431   }
4432
4433   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4434     CmdArgs.push_back("-fconstexpr-steps");
4435     CmdArgs.push_back(A->getValue());
4436   }
4437
4438   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4439     CmdArgs.push_back("-fbracket-depth");
4440     CmdArgs.push_back(A->getValue());
4441   }
4442
4443   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4444                                options::OPT_Wlarge_by_value_copy_def)) {
4445     if (A->getNumValues()) {
4446       StringRef bytes = A->getValue();
4447       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4448     } else
4449       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4450   }
4451
4452   if (Args.hasArg(options::OPT_relocatable_pch))
4453     CmdArgs.push_back("-relocatable-pch");
4454
4455   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4456     CmdArgs.push_back("-fconstant-string-class");
4457     CmdArgs.push_back(A->getValue());
4458   }
4459
4460   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4461     CmdArgs.push_back("-ftabstop");
4462     CmdArgs.push_back(A->getValue());
4463   }
4464
4465   CmdArgs.push_back("-ferror-limit");
4466   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4467     CmdArgs.push_back(A->getValue());
4468   else
4469     CmdArgs.push_back("19");
4470
4471   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4472     CmdArgs.push_back("-fmacro-backtrace-limit");
4473     CmdArgs.push_back(A->getValue());
4474   }
4475
4476   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4477     CmdArgs.push_back("-ftemplate-backtrace-limit");
4478     CmdArgs.push_back(A->getValue());
4479   }
4480
4481   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4482     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4483     CmdArgs.push_back(A->getValue());
4484   }
4485
4486   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4487     CmdArgs.push_back("-fspell-checking-limit");
4488     CmdArgs.push_back(A->getValue());
4489   }
4490
4491   // Pass -fmessage-length=.
4492   CmdArgs.push_back("-fmessage-length");
4493   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4494     CmdArgs.push_back(A->getValue());
4495   } else {
4496     // If -fmessage-length=N was not specified, determine whether this is a
4497     // terminal and, if so, implicitly define -fmessage-length appropriately.
4498     unsigned N = llvm::sys::Process::StandardErrColumns();
4499     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4500   }
4501
4502   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4503   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4504                                      options::OPT_fvisibility_ms_compat)) {
4505     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4506       CmdArgs.push_back("-fvisibility");
4507       CmdArgs.push_back(A->getValue());
4508     } else {
4509       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4510       CmdArgs.push_back("-fvisibility");
4511       CmdArgs.push_back("hidden");
4512       CmdArgs.push_back("-ftype-visibility");
4513       CmdArgs.push_back("default");
4514     }
4515   }
4516
4517   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4518
4519   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4520
4521   // -fhosted is default.
4522   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4523       KernelOrKext)
4524     CmdArgs.push_back("-ffreestanding");
4525
4526   // Forward -f (flag) options which we can pass directly.
4527   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4528   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4529   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4530   // Emulated TLS is enabled by default on Android, and can be enabled manually
4531   // with -femulated-tls.
4532   bool EmulatedTLSDefault = Triple.isAndroid();
4533   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4534                    EmulatedTLSDefault))
4535     CmdArgs.push_back("-femulated-tls");
4536   // AltiVec-like language extensions aren't relevant for assembling.
4537   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4538     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4539     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4540   }
4541   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4542   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4543
4544   // Forward flags for OpenMP
4545   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4546                    options::OPT_fno_openmp, false))
4547     switch (getOpenMPRuntime(getToolChain(), Args)) {
4548     case OMPRT_OMP:
4549     case OMPRT_IOMP5:
4550       // Clang can generate useful OpenMP code for these two runtime libraries.
4551       CmdArgs.push_back("-fopenmp");
4552
4553       // If no option regarding the use of TLS in OpenMP codegeneration is
4554       // given, decide a default based on the target. Otherwise rely on the
4555       // options and pass the right information to the frontend.
4556       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4557                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4558         CmdArgs.push_back("-fnoopenmp-use-tls");
4559       break;
4560     default:
4561       // By default, if Clang doesn't know how to generate useful OpenMP code
4562       // for a specific runtime library, we just don't pass the '-fopenmp' flag
4563       // down to the actual compilation.
4564       // FIXME: It would be better to have a mode which *only* omits IR
4565       // generation based on the OpenMP support so that we get consistent
4566       // semantic analysis, etc.
4567       break;
4568     }
4569
4570   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4571   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4572
4573   // Report an error for -faltivec on anything other than PowerPC.
4574   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4575     const llvm::Triple::ArchType Arch = getToolChain().getArch();
4576     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4577           Arch == llvm::Triple::ppc64le))
4578       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4579                                                        << "ppc/ppc64/ppc64le";
4580   }
4581
4582   // -fzvector is incompatible with -faltivec.
4583   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4584     if (Args.hasArg(options::OPT_faltivec))
4585       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4586                                                       << "-faltivec";
4587
4588   if (getToolChain().SupportsProfiling())
4589     Args.AddLastArg(CmdArgs, options::OPT_pg);
4590
4591   // -flax-vector-conversions is default.
4592   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4593                     options::OPT_fno_lax_vector_conversions))
4594     CmdArgs.push_back("-fno-lax-vector-conversions");
4595
4596   if (Args.getLastArg(options::OPT_fapple_kext) ||
4597       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4598     CmdArgs.push_back("-fapple-kext");
4599
4600   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4601   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4602   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4603   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4604   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4605
4606   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4607     CmdArgs.push_back("-ftrapv-handler");
4608     CmdArgs.push_back(A->getValue());
4609   }
4610
4611   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4612
4613   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4614   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4615   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4616     if (A->getOption().matches(options::OPT_fwrapv))
4617       CmdArgs.push_back("-fwrapv");
4618   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4619                                       options::OPT_fno_strict_overflow)) {
4620     if (A->getOption().matches(options::OPT_fno_strict_overflow))
4621       CmdArgs.push_back("-fwrapv");
4622   }
4623
4624   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4625                                options::OPT_fno_reroll_loops))
4626     if (A->getOption().matches(options::OPT_freroll_loops))
4627       CmdArgs.push_back("-freroll-loops");
4628
4629   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4630   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4631                   options::OPT_fno_unroll_loops);
4632
4633   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4634
4635   // -stack-protector=0 is default.
4636   unsigned StackProtectorLevel = 0;
4637   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4638     Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4639     Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4640     Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4641     Args.ClaimAllArgs(options::OPT_fstack_protector);
4642   } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4643                                       options::OPT_fstack_protector_all,
4644                                       options::OPT_fstack_protector_strong,
4645                                       options::OPT_fstack_protector)) {
4646     if (A->getOption().matches(options::OPT_fstack_protector)) {
4647       StackProtectorLevel = std::max<unsigned>(
4648           LangOptions::SSPOn,
4649           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4650     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4651       StackProtectorLevel = LangOptions::SSPStrong;
4652     else if (A->getOption().matches(options::OPT_fstack_protector_all))
4653       StackProtectorLevel = LangOptions::SSPReq;
4654   } else {
4655     StackProtectorLevel =
4656         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4657   }
4658   if (StackProtectorLevel) {
4659     CmdArgs.push_back("-stack-protector");
4660     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4661   }
4662
4663   // --param ssp-buffer-size=
4664   for (const Arg *A : Args.filtered(options::OPT__param)) {
4665     StringRef Str(A->getValue());
4666     if (Str.startswith("ssp-buffer-size=")) {
4667       if (StackProtectorLevel) {
4668         CmdArgs.push_back("-stack-protector-buffer-size");
4669         // FIXME: Verify the argument is a valid integer.
4670         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4671       }
4672       A->claim();
4673     }
4674   }
4675
4676   // Translate -mstackrealign
4677   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4678                    false))
4679     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4680
4681   if (Args.hasArg(options::OPT_mstack_alignment)) {
4682     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4683     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4684   }
4685
4686   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4687     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4688
4689     if (!Size.empty())
4690       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4691     else
4692       CmdArgs.push_back("-mstack-probe-size=0");
4693   }
4694
4695   switch (getToolChain().getArch()) {
4696   case llvm::Triple::aarch64:
4697   case llvm::Triple::aarch64_be:
4698   case llvm::Triple::arm:
4699   case llvm::Triple::armeb:
4700   case llvm::Triple::thumb:
4701   case llvm::Triple::thumbeb:
4702     CmdArgs.push_back("-fallow-half-arguments-and-returns");
4703     break;
4704
4705   default:
4706     break;
4707   }
4708
4709   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4710                                options::OPT_mno_restrict_it)) {
4711     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4712       CmdArgs.push_back("-backend-option");
4713       CmdArgs.push_back("-arm-restrict-it");
4714     } else {
4715       CmdArgs.push_back("-backend-option");
4716       CmdArgs.push_back("-arm-no-restrict-it");
4717     }
4718   } else if (Triple.isOSWindows() &&
4719              (Triple.getArch() == llvm::Triple::arm ||
4720               Triple.getArch() == llvm::Triple::thumb)) {
4721     // Windows on ARM expects restricted IT blocks
4722     CmdArgs.push_back("-backend-option");
4723     CmdArgs.push_back("-arm-restrict-it");
4724   }
4725
4726   // Forward -f options with positive and negative forms; we translate
4727   // these by hand.
4728   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4729     StringRef fname = A->getValue();
4730     if (!llvm::sys::fs::exists(fname))
4731       D.Diag(diag::err_drv_no_such_file) << fname;
4732     else
4733       A->render(Args, CmdArgs);
4734   }
4735
4736   // -fbuiltin is default unless -mkernel is used
4737   if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4738                     !Args.hasArg(options::OPT_mkernel)))
4739     CmdArgs.push_back("-fno-builtin");
4740
4741   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4742                     options::OPT_fno_assume_sane_operator_new))
4743     CmdArgs.push_back("-fno-assume-sane-operator-new");
4744
4745   // -fblocks=0 is default.
4746   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4747                    getToolChain().IsBlocksDefault()) ||
4748       (Args.hasArg(options::OPT_fgnu_runtime) &&
4749        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4750        !Args.hasArg(options::OPT_fno_blocks))) {
4751     CmdArgs.push_back("-fblocks");
4752
4753     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4754         !getToolChain().hasBlocksRuntime())
4755       CmdArgs.push_back("-fblocks-runtime-optional");
4756   }
4757
4758   // -fmodules enables the use of precompiled modules (off by default).
4759   // Users can pass -fno-cxx-modules to turn off modules support for
4760   // C++/Objective-C++ programs.
4761   bool HaveModules = false;
4762   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4763     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4764                                      options::OPT_fno_cxx_modules, true);
4765     if (AllowedInCXX || !types::isCXX(InputType)) {
4766       CmdArgs.push_back("-fmodules");
4767       HaveModules = true;
4768     }
4769   }
4770
4771   // -fmodule-maps enables implicit reading of module map files. By default,
4772   // this is enabled if we are using precompiled modules.
4773   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4774                    options::OPT_fno_implicit_module_maps, HaveModules)) {
4775     CmdArgs.push_back("-fimplicit-module-maps");
4776   }
4777
4778   // -fmodules-decluse checks that modules used are declared so (off by
4779   // default).
4780   if (Args.hasFlag(options::OPT_fmodules_decluse,
4781                    options::OPT_fno_modules_decluse, false)) {
4782     CmdArgs.push_back("-fmodules-decluse");
4783   }
4784
4785   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4786   // all #included headers are part of modules.
4787   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4788                    options::OPT_fno_modules_strict_decluse, false)) {
4789     CmdArgs.push_back("-fmodules-strict-decluse");
4790   }
4791
4792   // -fno-implicit-modules turns off implicitly compiling modules on demand.
4793   if (!Args.hasFlag(options::OPT_fimplicit_modules,
4794                     options::OPT_fno_implicit_modules)) {
4795     CmdArgs.push_back("-fno-implicit-modules");
4796   }
4797
4798   // -fmodule-name specifies the module that is currently being built (or
4799   // used for header checking by -fmodule-maps).
4800   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4801
4802   // -fmodule-map-file can be used to specify files containing module
4803   // definitions.
4804   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4805
4806   // -fmodule-file can be used to specify files containing precompiled modules.
4807   if (HaveModules)
4808     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4809   else
4810     Args.ClaimAllArgs(options::OPT_fmodule_file);
4811
4812   // -fmodule-cache-path specifies where our implicitly-built module files
4813   // should be written.
4814   SmallString<128> Path;
4815   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4816     Path = A->getValue();
4817   if (HaveModules) {
4818     if (C.isForDiagnostics()) {
4819       // When generating crash reports, we want to emit the modules along with
4820       // the reproduction sources, so we ignore any provided module path.
4821       Path = Output.getFilename();
4822       llvm::sys::path::replace_extension(Path, ".cache");
4823       llvm::sys::path::append(Path, "modules");
4824     } else if (Path.empty()) {
4825       // No module path was provided: use the default.
4826       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4827       llvm::sys::path::append(Path, "org.llvm.clang.");
4828       appendUserToPath(Path);
4829       llvm::sys::path::append(Path, "ModuleCache");
4830     }
4831     const char Arg[] = "-fmodules-cache-path=";
4832     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4833     CmdArgs.push_back(Args.MakeArgString(Path));
4834   }
4835
4836   // When building modules and generating crashdumps, we need to dump a module
4837   // dependency VFS alongside the output.
4838   if (HaveModules && C.isForDiagnostics()) {
4839     SmallString<128> VFSDir(Output.getFilename());
4840     llvm::sys::path::replace_extension(VFSDir, ".cache");
4841     // Add the cache directory as a temp so the crash diagnostics pick it up.
4842     C.addTempFile(Args.MakeArgString(VFSDir));
4843
4844     llvm::sys::path::append(VFSDir, "vfs");
4845     CmdArgs.push_back("-module-dependency-dir");
4846     CmdArgs.push_back(Args.MakeArgString(VFSDir));
4847   }
4848
4849   if (HaveModules)
4850     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4851
4852   // Pass through all -fmodules-ignore-macro arguments.
4853   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4854   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4855   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4856
4857   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4858
4859   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4860     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4861       D.Diag(diag::err_drv_argument_not_allowed_with)
4862           << A->getAsString(Args) << "-fbuild-session-timestamp";
4863
4864     llvm::sys::fs::file_status Status;
4865     if (llvm::sys::fs::status(A->getValue(), Status))
4866       D.Diag(diag::err_drv_no_such_file) << A->getValue();
4867     CmdArgs.push_back(Args.MakeArgString(
4868         "-fbuild-session-timestamp=" +
4869         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4870   }
4871
4872   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4873     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4874                          options::OPT_fbuild_session_file))
4875       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4876
4877     Args.AddLastArg(CmdArgs,
4878                     options::OPT_fmodules_validate_once_per_build_session);
4879   }
4880
4881   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4882
4883   // -faccess-control is default.
4884   if (Args.hasFlag(options::OPT_fno_access_control,
4885                    options::OPT_faccess_control, false))
4886     CmdArgs.push_back("-fno-access-control");
4887
4888   // -felide-constructors is the default.
4889   if (Args.hasFlag(options::OPT_fno_elide_constructors,
4890                    options::OPT_felide_constructors, false))
4891     CmdArgs.push_back("-fno-elide-constructors");
4892
4893   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4894
4895   if (KernelOrKext || (types::isCXX(InputType) &&
4896                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4897                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
4898     CmdArgs.push_back("-fno-rtti");
4899
4900   // -fshort-enums=0 is default for all architectures except Hexagon.
4901   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4902                    getToolChain().getArch() == llvm::Triple::hexagon))
4903     CmdArgs.push_back("-fshort-enums");
4904
4905   // -fsigned-char is default.
4906   if (Arg *A = Args.getLastArg(
4907           options::OPT_fsigned_char, options::OPT_fno_signed_char,
4908           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4909     if (A->getOption().matches(options::OPT_funsigned_char) ||
4910         A->getOption().matches(options::OPT_fno_signed_char)) {
4911       CmdArgs.push_back("-fno-signed-char");
4912     }
4913   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4914     CmdArgs.push_back("-fno-signed-char");
4915   }
4916
4917   // -fuse-cxa-atexit is default.
4918   if (!Args.hasFlag(
4919           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4920           !IsWindowsCygnus && !IsWindowsGNU &&
4921               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4922               getToolChain().getArch() != llvm::Triple::hexagon &&
4923               getToolChain().getArch() != llvm::Triple::xcore &&
4924               ((getToolChain().getTriple().getVendor() !=
4925                 llvm::Triple::MipsTechnologies) ||
4926                getToolChain().getTriple().hasEnvironment())) ||
4927       KernelOrKext)
4928     CmdArgs.push_back("-fno-use-cxa-atexit");
4929
4930   // -fms-extensions=0 is default.
4931   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4932                    IsWindowsMSVC))
4933     CmdArgs.push_back("-fms-extensions");
4934
4935   // -fno-use-line-directives is default.
4936   if (Args.hasFlag(options::OPT_fuse_line_directives,
4937                    options::OPT_fno_use_line_directives, false))
4938     CmdArgs.push_back("-fuse-line-directives");
4939
4940   // -fms-compatibility=0 is default.
4941   if (Args.hasFlag(options::OPT_fms_compatibility,
4942                    options::OPT_fno_ms_compatibility,
4943                    (IsWindowsMSVC &&
4944                     Args.hasFlag(options::OPT_fms_extensions,
4945                                  options::OPT_fno_ms_extensions, true))))
4946     CmdArgs.push_back("-fms-compatibility");
4947
4948   // -fms-compatibility-version=18.00 is default.
4949   VersionTuple MSVT = visualstudio::getMSVCVersion(
4950       &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4951   if (!MSVT.empty())
4952     CmdArgs.push_back(
4953         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4954
4955   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4956   if (ImplyVCPPCXXVer) {
4957     if (IsMSVC2015Compatible)
4958       CmdArgs.push_back("-std=c++14");
4959     else
4960       CmdArgs.push_back("-std=c++11");
4961   }
4962
4963   // -fno-borland-extensions is default.
4964   if (Args.hasFlag(options::OPT_fborland_extensions,
4965                    options::OPT_fno_borland_extensions, false))
4966     CmdArgs.push_back("-fborland-extensions");
4967
4968   // -fno-declspec is default, except for PS4.
4969   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4970                    getToolChain().getTriple().isPS4()))
4971     CmdArgs.push_back("-fdeclspec");
4972   else if (Args.hasArg(options::OPT_fno_declspec))
4973     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4974
4975   // -fthreadsafe-static is default, except for MSVC compatibility versions less
4976   // than 19.
4977   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4978                     options::OPT_fno_threadsafe_statics,
4979                     !IsWindowsMSVC || IsMSVC2015Compatible))
4980     CmdArgs.push_back("-fno-threadsafe-statics");
4981
4982   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4983   // needs it.
4984   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4985                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4986     CmdArgs.push_back("-fdelayed-template-parsing");
4987
4988   // -fgnu-keywords default varies depending on language; only pass if
4989   // specified.
4990   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4991                                options::OPT_fno_gnu_keywords))
4992     A->render(Args, CmdArgs);
4993
4994   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4995                    false))
4996     CmdArgs.push_back("-fgnu89-inline");
4997
4998   if (Args.hasArg(options::OPT_fno_inline))
4999     CmdArgs.push_back("-fno-inline");
5000
5001   if (Args.hasArg(options::OPT_fno_inline_functions))
5002     CmdArgs.push_back("-fno-inline-functions");
5003
5004   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5005
5006   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5007   // legacy is the default. Except for deployment taget of 10.5,
5008   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5009   // gets ignored silently.
5010   if (objcRuntime.isNonFragile()) {
5011     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5012                       options::OPT_fno_objc_legacy_dispatch,
5013                       objcRuntime.isLegacyDispatchDefaultForArch(
5014                           getToolChain().getArch()))) {
5015       if (getToolChain().UseObjCMixedDispatch())
5016         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5017       else
5018         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5019     }
5020   }
5021
5022   // When ObjectiveC legacy runtime is in effect on MacOSX,
5023   // turn on the option to do Array/Dictionary subscripting
5024   // by default.
5025   if (getToolChain().getArch() == llvm::Triple::x86 &&
5026       getToolChain().getTriple().isMacOSX() &&
5027       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5028       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5029       objcRuntime.isNeXTFamily())
5030     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5031
5032   // -fencode-extended-block-signature=1 is default.
5033   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5034     CmdArgs.push_back("-fencode-extended-block-signature");
5035   }
5036
5037   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5038   // NOTE: This logic is duplicated in ToolChains.cpp.
5039   bool ARC = isObjCAutoRefCount(Args);
5040   if (ARC) {
5041     getToolChain().CheckObjCARC();
5042
5043     CmdArgs.push_back("-fobjc-arc");
5044
5045     // FIXME: It seems like this entire block, and several around it should be
5046     // wrapped in isObjC, but for now we just use it here as this is where it
5047     // was being used previously.
5048     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5049       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5050         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5051       else
5052         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5053     }
5054
5055     // Allow the user to enable full exceptions code emission.
5056     // We define off for Objective-CC, on for Objective-C++.
5057     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5058                      options::OPT_fno_objc_arc_exceptions,
5059                      /*default*/ types::isCXX(InputType)))
5060       CmdArgs.push_back("-fobjc-arc-exceptions");
5061
5062   }
5063
5064   // -fobjc-infer-related-result-type is the default, except in the Objective-C
5065   // rewriter.
5066   if (rewriteKind != RK_None)
5067     CmdArgs.push_back("-fno-objc-infer-related-result-type");
5068
5069   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5070   // takes precedence.
5071   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5072   if (!GCArg)
5073     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5074   if (GCArg) {
5075     if (ARC) {
5076       D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5077     } else if (getToolChain().SupportsObjCGC()) {
5078       GCArg->render(Args, CmdArgs);
5079     } else {
5080       // FIXME: We should move this to a hard error.
5081       D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5082     }
5083   }
5084
5085   // Pass down -fobjc-weak or -fno-objc-weak if present.
5086   if (types::isObjC(InputType)) {
5087     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5088                                    options::OPT_fno_objc_weak);
5089     if (!WeakArg) {
5090       // nothing to do
5091     } else if (GCArg) {
5092       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5093         D.Diag(diag::err_objc_weak_with_gc);
5094     } else if (!objcRuntime.allowsWeak()) {
5095       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5096         D.Diag(diag::err_objc_weak_unsupported);
5097     } else {
5098       WeakArg->render(Args, CmdArgs);
5099     }
5100   }
5101
5102   if (Args.hasFlag(options::OPT_fapplication_extension,
5103                    options::OPT_fno_application_extension, false))
5104     CmdArgs.push_back("-fapplication-extension");
5105
5106   // Handle GCC-style exception args.
5107   if (!C.getDriver().IsCLMode())
5108     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5109                      CmdArgs);
5110
5111   if (getToolChain().UseSjLjExceptions(Args))
5112     CmdArgs.push_back("-fsjlj-exceptions");
5113
5114   // C++ "sane" operator new.
5115   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5116                     options::OPT_fno_assume_sane_operator_new))
5117     CmdArgs.push_back("-fno-assume-sane-operator-new");
5118
5119   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5120   // most platforms.
5121   if (Args.hasFlag(options::OPT_fsized_deallocation,
5122                    options::OPT_fno_sized_deallocation, false))
5123     CmdArgs.push_back("-fsized-deallocation");
5124
5125   // -fconstant-cfstrings is default, and may be subject to argument translation
5126   // on Darwin.
5127   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5128                     options::OPT_fno_constant_cfstrings) ||
5129       !Args.hasFlag(options::OPT_mconstant_cfstrings,
5130                     options::OPT_mno_constant_cfstrings))
5131     CmdArgs.push_back("-fno-constant-cfstrings");
5132
5133   // -fshort-wchar default varies depending on platform; only
5134   // pass if specified.
5135   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5136                                options::OPT_fno_short_wchar))
5137     A->render(Args, CmdArgs);
5138
5139   // -fno-pascal-strings is default, only pass non-default.
5140   if (Args.hasFlag(options::OPT_fpascal_strings,
5141                    options::OPT_fno_pascal_strings, false))
5142     CmdArgs.push_back("-fpascal-strings");
5143
5144   // Honor -fpack-struct= and -fpack-struct, if given. Note that
5145   // -fno-pack-struct doesn't apply to -fpack-struct=.
5146   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5147     std::string PackStructStr = "-fpack-struct=";
5148     PackStructStr += A->getValue();
5149     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5150   } else if (Args.hasFlag(options::OPT_fpack_struct,
5151                           options::OPT_fno_pack_struct, false)) {
5152     CmdArgs.push_back("-fpack-struct=1");
5153   }
5154
5155   // Handle -fmax-type-align=N and -fno-type-align
5156   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5157   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5158     if (!SkipMaxTypeAlign) {
5159       std::string MaxTypeAlignStr = "-fmax-type-align=";
5160       MaxTypeAlignStr += A->getValue();
5161       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5162     }
5163   } else if (getToolChain().getTriple().isOSDarwin()) {
5164     if (!SkipMaxTypeAlign) {
5165       std::string MaxTypeAlignStr = "-fmax-type-align=16";
5166       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5167     }
5168   }
5169
5170   // -fcommon is the default unless compiling kernel code or the target says so
5171   bool NoCommonDefault =
5172       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5173   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5174                     !NoCommonDefault))
5175     CmdArgs.push_back("-fno-common");
5176
5177   // -fsigned-bitfields is default, and clang doesn't yet support
5178   // -funsigned-bitfields.
5179   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5180                     options::OPT_funsigned_bitfields))
5181     D.Diag(diag::warn_drv_clang_unsupported)
5182         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5183
5184   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5185   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5186     D.Diag(diag::err_drv_clang_unsupported)
5187         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5188
5189   // -finput_charset=UTF-8 is default. Reject others
5190   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5191     StringRef value = inputCharset->getValue();
5192     if (value != "UTF-8")
5193       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5194                                           << value;
5195   }
5196
5197   // -fexec_charset=UTF-8 is default. Reject others
5198   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5199     StringRef value = execCharset->getValue();
5200     if (value != "UTF-8")
5201       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5202                                           << value;
5203   }
5204
5205   // -fcaret-diagnostics is default.
5206   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5207                     options::OPT_fno_caret_diagnostics, true))
5208     CmdArgs.push_back("-fno-caret-diagnostics");
5209
5210   // -fdiagnostics-fixit-info is default, only pass non-default.
5211   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5212                     options::OPT_fno_diagnostics_fixit_info))
5213     CmdArgs.push_back("-fno-diagnostics-fixit-info");
5214
5215   // Enable -fdiagnostics-show-option by default.
5216   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5217                    options::OPT_fno_diagnostics_show_option))
5218     CmdArgs.push_back("-fdiagnostics-show-option");
5219
5220   if (const Arg *A =
5221           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5222     CmdArgs.push_back("-fdiagnostics-show-category");
5223     CmdArgs.push_back(A->getValue());
5224   }
5225
5226   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5227     CmdArgs.push_back("-fdiagnostics-format");
5228     CmdArgs.push_back(A->getValue());
5229   }
5230
5231   if (Arg *A = Args.getLastArg(
5232           options::OPT_fdiagnostics_show_note_include_stack,
5233           options::OPT_fno_diagnostics_show_note_include_stack)) {
5234     if (A->getOption().matches(
5235             options::OPT_fdiagnostics_show_note_include_stack))
5236       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5237     else
5238       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5239   }
5240
5241   // Color diagnostics are the default, unless the terminal doesn't support
5242   // them.
5243   // Support both clang's -f[no-]color-diagnostics and gcc's
5244   // -f[no-]diagnostics-colors[=never|always|auto].
5245   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5246   for (const auto &Arg : Args) {
5247     const Option &O = Arg->getOption();
5248     if (!O.matches(options::OPT_fcolor_diagnostics) &&
5249         !O.matches(options::OPT_fdiagnostics_color) &&
5250         !O.matches(options::OPT_fno_color_diagnostics) &&
5251         !O.matches(options::OPT_fno_diagnostics_color) &&
5252         !O.matches(options::OPT_fdiagnostics_color_EQ))
5253       continue;
5254
5255     Arg->claim();
5256     if (O.matches(options::OPT_fcolor_diagnostics) ||
5257         O.matches(options::OPT_fdiagnostics_color)) {
5258       ShowColors = Colors_On;
5259     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5260                O.matches(options::OPT_fno_diagnostics_color)) {
5261       ShowColors = Colors_Off;
5262     } else {
5263       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5264       StringRef value(Arg->getValue());
5265       if (value == "always")
5266         ShowColors = Colors_On;
5267       else if (value == "never")
5268         ShowColors = Colors_Off;
5269       else if (value == "auto")
5270         ShowColors = Colors_Auto;
5271       else
5272         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5273             << ("-fdiagnostics-color=" + value).str();
5274     }
5275   }
5276   if (ShowColors == Colors_On ||
5277       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5278     CmdArgs.push_back("-fcolor-diagnostics");
5279
5280   if (Args.hasArg(options::OPT_fansi_escape_codes))
5281     CmdArgs.push_back("-fansi-escape-codes");
5282
5283   if (!Args.hasFlag(options::OPT_fshow_source_location,
5284                     options::OPT_fno_show_source_location))
5285     CmdArgs.push_back("-fno-show-source-location");
5286
5287   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5288                     true))
5289     CmdArgs.push_back("-fno-show-column");
5290
5291   if (!Args.hasFlag(options::OPT_fspell_checking,
5292                     options::OPT_fno_spell_checking))
5293     CmdArgs.push_back("-fno-spell-checking");
5294
5295   // -fno-asm-blocks is default.
5296   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5297                    false))
5298     CmdArgs.push_back("-fasm-blocks");
5299
5300   // -fgnu-inline-asm is default.
5301   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5302                     options::OPT_fno_gnu_inline_asm, true))
5303     CmdArgs.push_back("-fno-gnu-inline-asm");
5304
5305   // Enable vectorization per default according to the optimization level
5306   // selected. For optimization levels that want vectorization we use the alias
5307   // option to simplify the hasFlag logic.
5308   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5309   OptSpecifier VectorizeAliasOption =
5310       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5311   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5312                    options::OPT_fno_vectorize, EnableVec))
5313     CmdArgs.push_back("-vectorize-loops");
5314
5315   // -fslp-vectorize is enabled based on the optimization level selected.
5316   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5317   OptSpecifier SLPVectAliasOption =
5318       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5319   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5320                    options::OPT_fno_slp_vectorize, EnableSLPVec))
5321     CmdArgs.push_back("-vectorize-slp");
5322
5323   // -fno-slp-vectorize-aggressive is default.
5324   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5325                    options::OPT_fno_slp_vectorize_aggressive, false))
5326     CmdArgs.push_back("-vectorize-slp-aggressive");
5327
5328   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5329     A->render(Args, CmdArgs);
5330
5331   // -fdollars-in-identifiers default varies depending on platform and
5332   // language; only pass if specified.
5333   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5334                                options::OPT_fno_dollars_in_identifiers)) {
5335     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5336       CmdArgs.push_back("-fdollars-in-identifiers");
5337     else
5338       CmdArgs.push_back("-fno-dollars-in-identifiers");
5339   }
5340
5341   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5342   // practical purposes.
5343   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5344                                options::OPT_fno_unit_at_a_time)) {
5345     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5346       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5347   }
5348
5349   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5350                    options::OPT_fno_apple_pragma_pack, false))
5351     CmdArgs.push_back("-fapple-pragma-pack");
5352
5353   // le32-specific flags:
5354   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
5355   //                     by default.
5356   if (getToolChain().getArch() == llvm::Triple::le32) {
5357     CmdArgs.push_back("-fno-math-builtin");
5358   }
5359
5360 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5361 //
5362 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5363 #if 0
5364   if (getToolChain().getTriple().isOSDarwin() &&
5365       (getToolChain().getArch() == llvm::Triple::arm ||
5366        getToolChain().getArch() == llvm::Triple::thumb)) {
5367     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5368       CmdArgs.push_back("-fno-builtin-strcat");
5369     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5370       CmdArgs.push_back("-fno-builtin-strcpy");
5371   }
5372 #endif
5373
5374   // Enable rewrite includes if the user's asked for it or if we're generating
5375   // diagnostics.
5376   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5377   // nice to enable this when doing a crashdump for modules as well.
5378   if (Args.hasFlag(options::OPT_frewrite_includes,
5379                    options::OPT_fno_rewrite_includes, false) ||
5380       (C.isForDiagnostics() && !HaveModules))
5381     CmdArgs.push_back("-frewrite-includes");
5382
5383   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5384   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5385                                options::OPT_traditional_cpp)) {
5386     if (isa<PreprocessJobAction>(JA))
5387       CmdArgs.push_back("-traditional-cpp");
5388     else
5389       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5390   }
5391
5392   Args.AddLastArg(CmdArgs, options::OPT_dM);
5393   Args.AddLastArg(CmdArgs, options::OPT_dD);
5394
5395   // Handle serialized diagnostics.
5396   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5397     CmdArgs.push_back("-serialize-diagnostic-file");
5398     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5399   }
5400
5401   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5402     CmdArgs.push_back("-fretain-comments-from-system-headers");
5403
5404   // Forward -fcomment-block-commands to -cc1.
5405   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5406   // Forward -fparse-all-comments to -cc1.
5407   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5408
5409   // Turn -fplugin=name.so into -load name.so
5410   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5411     CmdArgs.push_back("-load");
5412     CmdArgs.push_back(A->getValue());
5413     A->claim();
5414   }
5415
5416   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5417   // parser.
5418   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5419   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5420     A->claim();
5421
5422     // We translate this by hand to the -cc1 argument, since nightly test uses
5423     // it and developers have been trained to spell it with -mllvm.
5424     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5425       CmdArgs.push_back("-disable-llvm-optzns");
5426     } else
5427       A->render(Args, CmdArgs);
5428   }
5429
5430   // With -save-temps, we want to save the unoptimized bitcode output from the
5431   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5432   // by the frontend.
5433   if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5434     CmdArgs.push_back("-disable-llvm-passes");
5435
5436   if (Output.getType() == types::TY_Dependencies) {
5437     // Handled with other dependency code.
5438   } else if (Output.isFilename()) {
5439     CmdArgs.push_back("-o");
5440     CmdArgs.push_back(Output.getFilename());
5441   } else {
5442     assert(Output.isNothing() && "Invalid output.");
5443   }
5444
5445   addDashXForInput(Args, Input, CmdArgs);
5446
5447   if (Input.isFilename())
5448     CmdArgs.push_back(Input.getFilename());
5449   else
5450     Input.getInputArg().renderAsInput(Args, CmdArgs);
5451
5452   Args.AddAllArgs(CmdArgs, options::OPT_undef);
5453
5454   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5455
5456   // Optionally embed the -cc1 level arguments into the debug info, for build
5457   // analysis.
5458   if (getToolChain().UseDwarfDebugFlags()) {
5459     ArgStringList OriginalArgs;
5460     for (const auto &Arg : Args)
5461       Arg->render(Args, OriginalArgs);
5462
5463     SmallString<256> Flags;
5464     Flags += Exec;
5465     for (const char *OriginalArg : OriginalArgs) {
5466       SmallString<128> EscapedArg;
5467       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5468       Flags += " ";
5469       Flags += EscapedArg;
5470     }
5471     CmdArgs.push_back("-dwarf-debug-flags");
5472     CmdArgs.push_back(Args.MakeArgString(Flags));
5473   }
5474
5475   // Add the split debug info name to the command lines here so we
5476   // can propagate it to the backend.
5477   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5478                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5479                      isa<BackendJobAction>(JA));
5480   const char *SplitDwarfOut;
5481   if (SplitDwarf) {
5482     CmdArgs.push_back("-split-dwarf-file");
5483     SplitDwarfOut = SplitDebugName(Args, Input);
5484     CmdArgs.push_back(SplitDwarfOut);
5485   }
5486
5487   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5488   // Include them with -fcuda-include-gpubinary.
5489   if (IsCuda && Inputs.size() > 1)
5490     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5491       CmdArgs.push_back("-fcuda-include-gpubinary");
5492       CmdArgs.push_back(I->getFilename());
5493     }
5494
5495   // Finally add the compile command to the compilation.
5496   if (Args.hasArg(options::OPT__SLASH_fallback) &&
5497       Output.getType() == types::TY_Object &&
5498       (InputType == types::TY_C || InputType == types::TY_CXX)) {
5499     auto CLCommand =
5500         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5501     C.addCommand(llvm::make_unique<FallbackCommand>(
5502         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5503   } else {
5504     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5505   }
5506
5507   // Handle the debug info splitting at object creation time if we're
5508   // creating an object.
5509   // TODO: Currently only works on linux with newer objcopy.
5510   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5511     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5512
5513   if (Arg *A = Args.getLastArg(options::OPT_pg))
5514     if (Args.hasArg(options::OPT_fomit_frame_pointer))
5515       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5516                                                       << A->getAsString(Args);
5517
5518   // Claim some arguments which clang supports automatically.
5519
5520   // -fpch-preprocess is used with gcc to add a special marker in the output to
5521   // include the PCH file. Clang's PTH solution is completely transparent, so we
5522   // do not need to deal with it at all.
5523   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5524
5525   // Claim some arguments which clang doesn't support, but we don't
5526   // care to warn the user about.
5527   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5528   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5529
5530   // Disable warnings for clang -E -emit-llvm foo.c
5531   Args.ClaimAllArgs(options::OPT_emit_llvm);
5532 }
5533
5534 /// Add options related to the Objective-C runtime/ABI.
5535 ///
5536 /// Returns true if the runtime is non-fragile.
5537 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5538                                       ArgStringList &cmdArgs,
5539                                       RewriteKind rewriteKind) const {
5540   // Look for the controlling runtime option.
5541   Arg *runtimeArg =
5542       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5543                       options::OPT_fobjc_runtime_EQ);
5544
5545   // Just forward -fobjc-runtime= to the frontend.  This supercedes
5546   // options about fragility.
5547   if (runtimeArg &&
5548       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5549     ObjCRuntime runtime;
5550     StringRef value = runtimeArg->getValue();
5551     if (runtime.tryParse(value)) {
5552       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5553           << value;
5554     }
5555
5556     runtimeArg->render(args, cmdArgs);
5557     return runtime;
5558   }
5559
5560   // Otherwise, we'll need the ABI "version".  Version numbers are
5561   // slightly confusing for historical reasons:
5562   //   1 - Traditional "fragile" ABI
5563   //   2 - Non-fragile ABI, version 1
5564   //   3 - Non-fragile ABI, version 2
5565   unsigned objcABIVersion = 1;
5566   // If -fobjc-abi-version= is present, use that to set the version.
5567   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5568     StringRef value = abiArg->getValue();
5569     if (value == "1")
5570       objcABIVersion = 1;
5571     else if (value == "2")
5572       objcABIVersion = 2;
5573     else if (value == "3")
5574       objcABIVersion = 3;
5575     else
5576       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5577   } else {
5578     // Otherwise, determine if we are using the non-fragile ABI.
5579     bool nonFragileABIIsDefault =
5580         (rewriteKind == RK_NonFragile ||
5581          (rewriteKind == RK_None &&
5582           getToolChain().IsObjCNonFragileABIDefault()));
5583     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5584                      options::OPT_fno_objc_nonfragile_abi,
5585                      nonFragileABIIsDefault)) {
5586 // Determine the non-fragile ABI version to use.
5587 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5588       unsigned nonFragileABIVersion = 1;
5589 #else
5590       unsigned nonFragileABIVersion = 2;
5591 #endif
5592
5593       if (Arg *abiArg =
5594               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5595         StringRef value = abiArg->getValue();
5596         if (value == "1")
5597           nonFragileABIVersion = 1;
5598         else if (value == "2")
5599           nonFragileABIVersion = 2;
5600         else
5601           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5602               << value;
5603       }
5604
5605       objcABIVersion = 1 + nonFragileABIVersion;
5606     } else {
5607       objcABIVersion = 1;
5608     }
5609   }
5610
5611   // We don't actually care about the ABI version other than whether
5612   // it's non-fragile.
5613   bool isNonFragile = objcABIVersion != 1;
5614
5615   // If we have no runtime argument, ask the toolchain for its default runtime.
5616   // However, the rewriter only really supports the Mac runtime, so assume that.
5617   ObjCRuntime runtime;
5618   if (!runtimeArg) {
5619     switch (rewriteKind) {
5620     case RK_None:
5621       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5622       break;
5623     case RK_Fragile:
5624       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5625       break;
5626     case RK_NonFragile:
5627       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5628       break;
5629     }
5630
5631     // -fnext-runtime
5632   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5633     // On Darwin, make this use the default behavior for the toolchain.
5634     if (getToolChain().getTriple().isOSDarwin()) {
5635       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5636
5637       // Otherwise, build for a generic macosx port.
5638     } else {
5639       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5640     }
5641
5642     // -fgnu-runtime
5643   } else {
5644     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5645     // Legacy behaviour is to target the gnustep runtime if we are in
5646     // non-fragile mode or the GCC runtime in fragile mode.
5647     if (isNonFragile)
5648       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5649     else
5650       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5651   }
5652
5653   cmdArgs.push_back(
5654       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5655   return runtime;
5656 }
5657
5658 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5659   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5660   I += HaveDash;
5661   return !HaveDash;
5662 }
5663
5664 namespace {
5665 struct EHFlags {
5666   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5667   bool Synch;
5668   bool Asynch;
5669   bool NoExceptC;
5670 };
5671 } // end anonymous namespace
5672
5673 /// /EH controls whether to run destructor cleanups when exceptions are
5674 /// thrown.  There are three modifiers:
5675 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5676 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5677 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5678 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
5679 ///      modifier is an optimization, so we ignore it for now.
5680 /// The default is /EHs-c-, meaning cleanups are disabled.
5681 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5682   EHFlags EH;
5683
5684   std::vector<std::string> EHArgs =
5685       Args.getAllArgValues(options::OPT__SLASH_EH);
5686   for (auto EHVal : EHArgs) {
5687     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5688       switch (EHVal[I]) {
5689       case 'a':
5690         EH.Asynch = maybeConsumeDash(EHVal, I);
5691         continue;
5692       case 'c':
5693         EH.NoExceptC = maybeConsumeDash(EHVal, I);
5694         continue;
5695       case 's':
5696         EH.Synch = maybeConsumeDash(EHVal, I);
5697         continue;
5698       default:
5699         break;
5700       }
5701       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5702       break;
5703     }
5704   }
5705
5706   return EH;
5707 }
5708
5709 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5710                            enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5711                            bool *EmitCodeView) const {
5712   unsigned RTOptionID = options::OPT__SLASH_MT;
5713
5714   if (Args.hasArg(options::OPT__SLASH_LDd))
5715     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5716     // but defining _DEBUG is sticky.
5717     RTOptionID = options::OPT__SLASH_MTd;
5718
5719   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5720     RTOptionID = A->getOption().getID();
5721
5722   StringRef FlagForCRT;
5723   switch (RTOptionID) {
5724   case options::OPT__SLASH_MD:
5725     if (Args.hasArg(options::OPT__SLASH_LDd))
5726       CmdArgs.push_back("-D_DEBUG");
5727     CmdArgs.push_back("-D_MT");
5728     CmdArgs.push_back("-D_DLL");
5729     FlagForCRT = "--dependent-lib=msvcrt";
5730     break;
5731   case options::OPT__SLASH_MDd:
5732     CmdArgs.push_back("-D_DEBUG");
5733     CmdArgs.push_back("-D_MT");
5734     CmdArgs.push_back("-D_DLL");
5735     FlagForCRT = "--dependent-lib=msvcrtd";
5736     break;
5737   case options::OPT__SLASH_MT:
5738     if (Args.hasArg(options::OPT__SLASH_LDd))
5739       CmdArgs.push_back("-D_DEBUG");
5740     CmdArgs.push_back("-D_MT");
5741     FlagForCRT = "--dependent-lib=libcmt";
5742     break;
5743   case options::OPT__SLASH_MTd:
5744     CmdArgs.push_back("-D_DEBUG");
5745     CmdArgs.push_back("-D_MT");
5746     FlagForCRT = "--dependent-lib=libcmtd";
5747     break;
5748   default:
5749     llvm_unreachable("Unexpected option ID.");
5750   }
5751
5752   if (Args.hasArg(options::OPT__SLASH_Zl)) {
5753     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5754   } else {
5755     CmdArgs.push_back(FlagForCRT.data());
5756
5757     // This provides POSIX compatibility (maps 'open' to '_open'), which most
5758     // users want.  The /Za flag to cl.exe turns this off, but it's not
5759     // implemented in clang.
5760     CmdArgs.push_back("--dependent-lib=oldnames");
5761   }
5762
5763   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5764   // would produce interleaved output, so ignore /showIncludes in such cases.
5765   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5766     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5767       A->render(Args, CmdArgs);
5768
5769   // This controls whether or not we emit RTTI data for polymorphic types.
5770   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5771                    /*default=*/false))
5772     CmdArgs.push_back("-fno-rtti-data");
5773
5774   // Emit CodeView if -Z7 is present.
5775   *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5776   bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5777   // If we are emitting CV but not DWARF, don't build information that LLVM
5778   // can't yet process.
5779   if (*EmitCodeView && !EmitDwarf)
5780     *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5781   if (*EmitCodeView)
5782     CmdArgs.push_back("-gcodeview");
5783
5784   const Driver &D = getToolChain().getDriver();
5785   EHFlags EH = parseClangCLEHFlags(D, Args);
5786   // FIXME: Do something with NoExceptC.
5787   if (EH.Synch || EH.Asynch) {
5788     CmdArgs.push_back("-fcxx-exceptions");
5789     CmdArgs.push_back("-fexceptions");
5790   }
5791
5792   // /EP should expand to -E -P.
5793   if (Args.hasArg(options::OPT__SLASH_EP)) {
5794     CmdArgs.push_back("-E");
5795     CmdArgs.push_back("-P");
5796   }
5797
5798   unsigned VolatileOptionID;
5799   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5800       getToolChain().getArch() == llvm::Triple::x86)
5801     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5802   else
5803     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5804
5805   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5806     VolatileOptionID = A->getOption().getID();
5807
5808   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5809     CmdArgs.push_back("-fms-volatile");
5810
5811   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5812   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5813   if (MostGeneralArg && BestCaseArg)
5814     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5815         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5816
5817   if (MostGeneralArg) {
5818     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5819     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5820     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5821
5822     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5823     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5824     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5825       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5826           << FirstConflict->getAsString(Args)
5827           << SecondConflict->getAsString(Args);
5828
5829     if (SingleArg)
5830       CmdArgs.push_back("-fms-memptr-rep=single");
5831     else if (MultipleArg)
5832       CmdArgs.push_back("-fms-memptr-rep=multiple");
5833     else
5834       CmdArgs.push_back("-fms-memptr-rep=virtual");
5835   }
5836
5837   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5838     A->render(Args, CmdArgs);
5839
5840   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5841     CmdArgs.push_back("-fdiagnostics-format");
5842     if (Args.hasArg(options::OPT__SLASH_fallback))
5843       CmdArgs.push_back("msvc-fallback");
5844     else
5845       CmdArgs.push_back("msvc");
5846   }
5847 }
5848
5849 visualstudio::Compiler *Clang::getCLFallback() const {
5850   if (!CLFallback)
5851     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5852   return CLFallback.get();
5853 }
5854
5855 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5856                                 ArgStringList &CmdArgs) const {
5857   StringRef CPUName;
5858   StringRef ABIName;
5859   const llvm::Triple &Triple = getToolChain().getTriple();
5860   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5861
5862   CmdArgs.push_back("-target-abi");
5863   CmdArgs.push_back(ABIName.data());
5864 }
5865
5866 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5867                            const InputInfo &Output, const InputInfoList &Inputs,
5868                            const ArgList &Args,
5869                            const char *LinkingOutput) const {
5870   ArgStringList CmdArgs;
5871
5872   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5873   const InputInfo &Input = Inputs[0];
5874
5875   std::string TripleStr =
5876       getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5877   const llvm::Triple Triple(TripleStr);
5878
5879   // Don't warn about "clang -w -c foo.s"
5880   Args.ClaimAllArgs(options::OPT_w);
5881   // and "clang -emit-llvm -c foo.s"
5882   Args.ClaimAllArgs(options::OPT_emit_llvm);
5883
5884   claimNoWarnArgs(Args);
5885
5886   // Invoke ourselves in -cc1as mode.
5887   //
5888   // FIXME: Implement custom jobs for internal actions.
5889   CmdArgs.push_back("-cc1as");
5890
5891   // Add the "effective" target triple.
5892   CmdArgs.push_back("-triple");
5893   CmdArgs.push_back(Args.MakeArgString(TripleStr));
5894
5895   // Set the output mode, we currently only expect to be used as a real
5896   // assembler.
5897   CmdArgs.push_back("-filetype");
5898   CmdArgs.push_back("obj");
5899
5900   // Set the main file name, so that debug info works even with
5901   // -save-temps or preprocessed assembly.
5902   CmdArgs.push_back("-main-file-name");
5903   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5904
5905   // Add the target cpu
5906   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5907   if (!CPU.empty()) {
5908     CmdArgs.push_back("-target-cpu");
5909     CmdArgs.push_back(Args.MakeArgString(CPU));
5910   }
5911
5912   // Add the target features
5913   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5914
5915   // Ignore explicit -force_cpusubtype_ALL option.
5916   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5917
5918   // Pass along any -I options so we get proper .include search paths.
5919   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5920
5921   // Determine the original source input.
5922   const Action *SourceAction = &JA;
5923   while (SourceAction->getKind() != Action::InputClass) {
5924     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5925     SourceAction = SourceAction->getInputs()[0];
5926   }
5927
5928   // Forward -g and handle debug info related flags, assuming we are dealing
5929   // with an actual assembly file.
5930   if (SourceAction->getType() == types::TY_Asm ||
5931       SourceAction->getType() == types::TY_PP_Asm) {
5932     bool WantDebug = false;
5933     unsigned DwarfVersion = 0;
5934     Args.ClaimAllArgs(options::OPT_g_Group);
5935     if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5936       WantDebug = !A->getOption().matches(options::OPT_g0) &&
5937         !A->getOption().matches(options::OPT_ggdb0);
5938       if (WantDebug)
5939         DwarfVersion = DwarfVersionNum(A->getSpelling());
5940     }
5941     if (DwarfVersion == 0)
5942       DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5943     RenderDebugEnablingArgs(Args, CmdArgs,
5944                             (WantDebug ? CodeGenOptions::LimitedDebugInfo
5945                                        : CodeGenOptions::NoDebugInfo),
5946                             DwarfVersion, llvm::DebuggerKind::Default);
5947
5948     // Add the -fdebug-compilation-dir flag if needed.
5949     addDebugCompDirArg(Args, CmdArgs);
5950
5951     // Set the AT_producer to the clang version when using the integrated
5952     // assembler on assembly source files.
5953     CmdArgs.push_back("-dwarf-debug-producer");
5954     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5955
5956     // And pass along -I options
5957     Args.AddAllArgs(CmdArgs, options::OPT_I);
5958   }
5959
5960   // Handle -fPIC et al -- the relocation-model affects the assembler
5961   // for some targets.
5962   llvm::Reloc::Model RelocationModel;
5963   unsigned PICLevel;
5964   bool IsPIE;
5965   std::tie(RelocationModel, PICLevel, IsPIE) =
5966       ParsePICArgs(getToolChain(), Triple, Args);
5967
5968   const char *RMName = RelocationModelName(RelocationModel);
5969   if (RMName) {
5970     CmdArgs.push_back("-mrelocation-model");
5971     CmdArgs.push_back(RMName);
5972   }
5973
5974   // Optionally embed the -cc1as level arguments into the debug info, for build
5975   // analysis.
5976   if (getToolChain().UseDwarfDebugFlags()) {
5977     ArgStringList OriginalArgs;
5978     for (const auto &Arg : Args)
5979       Arg->render(Args, OriginalArgs);
5980
5981     SmallString<256> Flags;
5982     const char *Exec = getToolChain().getDriver().getClangProgramPath();
5983     Flags += Exec;
5984     for (const char *OriginalArg : OriginalArgs) {
5985       SmallString<128> EscapedArg;
5986       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5987       Flags += " ";
5988       Flags += EscapedArg;
5989     }
5990     CmdArgs.push_back("-dwarf-debug-flags");
5991     CmdArgs.push_back(Args.MakeArgString(Flags));
5992   }
5993
5994   // FIXME: Add -static support, once we have it.
5995
5996   // Add target specific flags.
5997   switch (getToolChain().getArch()) {
5998   default:
5999     break;
6000
6001   case llvm::Triple::mips:
6002   case llvm::Triple::mipsel:
6003   case llvm::Triple::mips64:
6004   case llvm::Triple::mips64el:
6005     AddMIPSTargetArgs(Args, CmdArgs);
6006     break;
6007   }
6008
6009   // Consume all the warning flags. Usually this would be handled more
6010   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6011   // doesn't handle that so rather than warning about unused flags that are
6012   // actually used, we'll lie by omission instead.
6013   // FIXME: Stop lying and consume only the appropriate driver flags
6014   for (const Arg *A : Args.filtered(options::OPT_W_Group))
6015     A->claim();
6016
6017   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6018                                     getToolChain().getDriver());
6019
6020   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6021
6022   assert(Output.isFilename() && "Unexpected lipo output.");
6023   CmdArgs.push_back("-o");
6024   CmdArgs.push_back(Output.getFilename());
6025
6026   assert(Input.isFilename() && "Invalid input.");
6027   CmdArgs.push_back(Input.getFilename());
6028
6029   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6030   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6031
6032   // Handle the debug info splitting at object creation time if we're
6033   // creating an object.
6034   // TODO: Currently only works on linux with newer objcopy.
6035   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6036       getToolChain().getTriple().isOSLinux())
6037     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6038                    SplitDebugName(Args, Input));
6039 }
6040
6041 void GnuTool::anchor() {}
6042
6043 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6044                                const InputInfo &Output,
6045                                const InputInfoList &Inputs, const ArgList &Args,
6046                                const char *LinkingOutput) const {
6047   const Driver &D = getToolChain().getDriver();
6048   ArgStringList CmdArgs;
6049
6050   for (const auto &A : Args) {
6051     if (forwardToGCC(A->getOption())) {
6052       // Don't forward any -g arguments to assembly steps.
6053       if (isa<AssembleJobAction>(JA) &&
6054           A->getOption().matches(options::OPT_g_Group))
6055         continue;
6056
6057       // Don't forward any -W arguments to assembly and link steps.
6058       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6059           A->getOption().matches(options::OPT_W_Group))
6060         continue;
6061
6062       // It is unfortunate that we have to claim here, as this means
6063       // we will basically never report anything interesting for
6064       // platforms using a generic gcc, even if we are just using gcc
6065       // to get to the assembler.
6066       A->claim();
6067       A->render(Args, CmdArgs);
6068     }
6069   }
6070
6071   RenderExtraToolArgs(JA, CmdArgs);
6072
6073   // If using a driver driver, force the arch.
6074   if (getToolChain().getTriple().isOSDarwin()) {
6075     CmdArgs.push_back("-arch");
6076     CmdArgs.push_back(
6077         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6078   }
6079
6080   // Try to force gcc to match the tool chain we want, if we recognize
6081   // the arch.
6082   //
6083   // FIXME: The triple class should directly provide the information we want
6084   // here.
6085   switch (getToolChain().getArch()) {
6086   default:
6087     break;
6088   case llvm::Triple::x86:
6089   case llvm::Triple::ppc:
6090     CmdArgs.push_back("-m32");
6091     break;
6092   case llvm::Triple::x86_64:
6093   case llvm::Triple::ppc64:
6094   case llvm::Triple::ppc64le:
6095     CmdArgs.push_back("-m64");
6096     break;
6097   case llvm::Triple::sparcel:
6098     CmdArgs.push_back("-EL");
6099     break;
6100   }
6101
6102   if (Output.isFilename()) {
6103     CmdArgs.push_back("-o");
6104     CmdArgs.push_back(Output.getFilename());
6105   } else {
6106     assert(Output.isNothing() && "Unexpected output");
6107     CmdArgs.push_back("-fsyntax-only");
6108   }
6109
6110   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6111
6112   // Only pass -x if gcc will understand it; otherwise hope gcc
6113   // understands the suffix correctly. The main use case this would go
6114   // wrong in is for linker inputs if they happened to have an odd
6115   // suffix; really the only way to get this to happen is a command
6116   // like '-x foobar a.c' which will treat a.c like a linker input.
6117   //
6118   // FIXME: For the linker case specifically, can we safely convert
6119   // inputs into '-Wl,' options?
6120   for (const auto &II : Inputs) {
6121     // Don't try to pass LLVM or AST inputs to a generic gcc.
6122     if (types::isLLVMIR(II.getType()))
6123       D.Diag(diag::err_drv_no_linker_llvm_support)
6124           << getToolChain().getTripleString();
6125     else if (II.getType() == types::TY_AST)
6126       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6127     else if (II.getType() == types::TY_ModuleFile)
6128       D.Diag(diag::err_drv_no_module_support)
6129           << getToolChain().getTripleString();
6130
6131     if (types::canTypeBeUserSpecified(II.getType())) {
6132       CmdArgs.push_back("-x");
6133       CmdArgs.push_back(types::getTypeName(II.getType()));
6134     }
6135
6136     if (II.isFilename())
6137       CmdArgs.push_back(II.getFilename());
6138     else {
6139       const Arg &A = II.getInputArg();
6140
6141       // Reverse translate some rewritten options.
6142       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6143         CmdArgs.push_back("-lstdc++");
6144         continue;
6145       }
6146
6147       // Don't render as input, we need gcc to do the translations.
6148       A.render(Args, CmdArgs);
6149     }
6150   }
6151
6152   const std::string customGCCName = D.getCCCGenericGCCName();
6153   const char *GCCName;
6154   if (!customGCCName.empty())
6155     GCCName = customGCCName.c_str();
6156   else if (D.CCCIsCXX()) {
6157     GCCName = "g++";
6158   } else
6159     GCCName = "gcc";
6160
6161   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6162   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6163 }
6164
6165 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6166                                             ArgStringList &CmdArgs) const {
6167   CmdArgs.push_back("-E");
6168 }
6169
6170 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6171                                         ArgStringList &CmdArgs) const {
6172   const Driver &D = getToolChain().getDriver();
6173
6174   switch (JA.getType()) {
6175   // If -flto, etc. are present then make sure not to force assembly output.
6176   case types::TY_LLVM_IR:
6177   case types::TY_LTO_IR:
6178   case types::TY_LLVM_BC:
6179   case types::TY_LTO_BC:
6180     CmdArgs.push_back("-c");
6181     break;
6182   case types::TY_PP_Asm:
6183     CmdArgs.push_back("-S");
6184     break;
6185   case types::TY_Nothing:
6186     CmdArgs.push_back("-fsyntax-only");
6187     break;
6188   default:
6189     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6190   }
6191 }
6192
6193 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6194                                       ArgStringList &CmdArgs) const {
6195   // The types are (hopefully) good enough.
6196 }
6197
6198 // Hexagon tools start.
6199 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6200                                              ArgStringList &CmdArgs) const {
6201 }
6202
6203 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6204                                       const InputInfo &Output,
6205                                       const InputInfoList &Inputs,
6206                                       const ArgList &Args,
6207                                       const char *LinkingOutput) const {
6208   claimNoWarnArgs(Args);
6209
6210   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6211   const Driver &D = HTC.getDriver();
6212   ArgStringList CmdArgs;
6213
6214   std::string MArchString = "-march=hexagon";
6215   CmdArgs.push_back(Args.MakeArgString(MArchString));
6216
6217   RenderExtraToolArgs(JA, CmdArgs);
6218
6219   std::string AsName = "hexagon-llvm-mc";
6220   std::string MCpuString = "-mcpu=hexagon" +
6221         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6222   CmdArgs.push_back("-filetype=obj");
6223   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6224
6225   if (Output.isFilename()) {
6226     CmdArgs.push_back("-o");
6227     CmdArgs.push_back(Output.getFilename());
6228   } else {
6229     assert(Output.isNothing() && "Unexpected output");
6230     CmdArgs.push_back("-fsyntax-only");
6231   }
6232
6233   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6234     std::string N = llvm::utostr(G.getValue());
6235     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6236   }
6237
6238   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6239
6240   // Only pass -x if gcc will understand it; otherwise hope gcc
6241   // understands the suffix correctly. The main use case this would go
6242   // wrong in is for linker inputs if they happened to have an odd
6243   // suffix; really the only way to get this to happen is a command
6244   // like '-x foobar a.c' which will treat a.c like a linker input.
6245   //
6246   // FIXME: For the linker case specifically, can we safely convert
6247   // inputs into '-Wl,' options?
6248   for (const auto &II : Inputs) {
6249     // Don't try to pass LLVM or AST inputs to a generic gcc.
6250     if (types::isLLVMIR(II.getType()))
6251       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6252           << HTC.getTripleString();
6253     else if (II.getType() == types::TY_AST)
6254       D.Diag(clang::diag::err_drv_no_ast_support)
6255           << HTC.getTripleString();
6256     else if (II.getType() == types::TY_ModuleFile)
6257       D.Diag(diag::err_drv_no_module_support)
6258           << HTC.getTripleString();
6259
6260     if (II.isFilename())
6261       CmdArgs.push_back(II.getFilename());
6262     else
6263       // Don't render as input, we need gcc to do the translations.
6264       // FIXME: What is this?
6265       II.getInputArg().render(Args, CmdArgs);
6266   }
6267
6268   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6269   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6270 }
6271
6272 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6273                                           ArgStringList &CmdArgs) const {
6274 }
6275
6276 static void
6277 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6278                          const toolchains::HexagonToolChain &HTC,
6279                          const InputInfo &Output, const InputInfoList &Inputs,
6280                          const ArgList &Args, ArgStringList &CmdArgs,
6281                          const char *LinkingOutput) {
6282
6283   const Driver &D = HTC.getDriver();
6284
6285   //----------------------------------------------------------------------------
6286   //
6287   //----------------------------------------------------------------------------
6288   bool IsStatic = Args.hasArg(options::OPT_static);
6289   bool IsShared = Args.hasArg(options::OPT_shared);
6290   bool IsPIE = Args.hasArg(options::OPT_pie);
6291   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6292   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6293   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6294   bool UseG0 = false;
6295   bool UseShared = IsShared && !IsStatic;
6296
6297   //----------------------------------------------------------------------------
6298   // Silence warnings for various options
6299   //----------------------------------------------------------------------------
6300   Args.ClaimAllArgs(options::OPT_g_Group);
6301   Args.ClaimAllArgs(options::OPT_emit_llvm);
6302   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6303                                      // handled somewhere else.
6304   Args.ClaimAllArgs(options::OPT_static_libgcc);
6305
6306   //----------------------------------------------------------------------------
6307   //
6308   //----------------------------------------------------------------------------
6309   if (Args.hasArg(options::OPT_s))
6310     CmdArgs.push_back("-s");
6311
6312   if (Args.hasArg(options::OPT_r))
6313     CmdArgs.push_back("-r");
6314
6315   for (const auto &Opt : HTC.ExtraOpts)
6316     CmdArgs.push_back(Opt.c_str());
6317
6318   CmdArgs.push_back("-march=hexagon");
6319   std::string CpuVer =
6320         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6321   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6322   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6323
6324   if (IsShared) {
6325     CmdArgs.push_back("-shared");
6326     // The following should be the default, but doing as hexagon-gcc does.
6327     CmdArgs.push_back("-call_shared");
6328   }
6329
6330   if (IsStatic)
6331     CmdArgs.push_back("-static");
6332
6333   if (IsPIE && !IsShared)
6334     CmdArgs.push_back("-pie");
6335
6336   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6337     std::string N = llvm::utostr(G.getValue());
6338     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6339     UseG0 = G.getValue() == 0;
6340   }
6341
6342   //----------------------------------------------------------------------------
6343   //
6344   //----------------------------------------------------------------------------
6345   CmdArgs.push_back("-o");
6346   CmdArgs.push_back(Output.getFilename());
6347
6348   //----------------------------------------------------------------------------
6349   // moslib
6350   //----------------------------------------------------------------------------
6351   std::vector<std::string> OsLibs;
6352   bool HasStandalone = false;
6353
6354   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6355     A->claim();
6356     OsLibs.emplace_back(A->getValue());
6357     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6358   }
6359   if (OsLibs.empty()) {
6360     OsLibs.push_back("standalone");
6361     HasStandalone = true;
6362   }
6363
6364   //----------------------------------------------------------------------------
6365   // Start Files
6366   //----------------------------------------------------------------------------
6367   const std::string MCpuSuffix = "/" + CpuVer;
6368   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6369   const std::string RootDir =
6370       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6371   const std::string StartSubDir =
6372       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6373
6374   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6375                       const char *Name) -> std::string {
6376     std::string RelName = SubDir + Name;
6377     std::string P = HTC.GetFilePath(RelName.c_str());
6378     if (llvm::sys::fs::exists(P))
6379       return P;
6380     return RootDir + RelName;
6381   };
6382
6383   if (IncStdLib && IncStartFiles) {
6384     if (!IsShared) {
6385       if (HasStandalone) {
6386         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6387         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6388       }
6389       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6390       CmdArgs.push_back(Args.MakeArgString(Crt0));
6391     }
6392     std::string Init = UseShared
6393           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6394           : Find(RootDir, StartSubDir, "/init.o");
6395     CmdArgs.push_back(Args.MakeArgString(Init));
6396   }
6397
6398   //----------------------------------------------------------------------------
6399   // Library Search Paths
6400   //----------------------------------------------------------------------------
6401   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6402   for (const auto &LibPath : LibPaths)
6403     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6404
6405   //----------------------------------------------------------------------------
6406   //
6407   //----------------------------------------------------------------------------
6408   Args.AddAllArgs(CmdArgs,
6409                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6410                    options::OPT_t, options::OPT_u_Group});
6411
6412   AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6413
6414   //----------------------------------------------------------------------------
6415   // Libraries
6416   //----------------------------------------------------------------------------
6417   if (IncStdLib && IncDefLibs) {
6418     if (D.CCCIsCXX()) {
6419       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6420       CmdArgs.push_back("-lm");
6421     }
6422
6423     CmdArgs.push_back("--start-group");
6424
6425     if (!IsShared) {
6426       for (const std::string &Lib : OsLibs)
6427         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6428       CmdArgs.push_back("-lc");
6429     }
6430     CmdArgs.push_back("-lgcc");
6431
6432     CmdArgs.push_back("--end-group");
6433   }
6434
6435   //----------------------------------------------------------------------------
6436   // End files
6437   //----------------------------------------------------------------------------
6438   if (IncStdLib && IncStartFiles) {
6439     std::string Fini = UseShared
6440           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6441           : Find(RootDir, StartSubDir, "/fini.o");
6442     CmdArgs.push_back(Args.MakeArgString(Fini));
6443   }
6444 }
6445
6446 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6447                                    const InputInfo &Output,
6448                                    const InputInfoList &Inputs,
6449                                    const ArgList &Args,
6450                                    const char *LinkingOutput) const {
6451   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6452
6453   ArgStringList CmdArgs;
6454   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6455                            LinkingOutput);
6456
6457   std::string Linker = HTC.GetProgramPath("hexagon-link");
6458   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6459                                           CmdArgs, Inputs));
6460 }
6461 // Hexagon tools end.
6462
6463 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6464                                   const InputInfo &Output,
6465                                   const InputInfoList &Inputs,
6466                                   const ArgList &Args,
6467                                   const char *LinkingOutput) const {
6468
6469   std::string Linker = getToolChain().GetProgramPath(getShortName());
6470   ArgStringList CmdArgs;
6471   CmdArgs.push_back("-flavor");
6472   CmdArgs.push_back("old-gnu");
6473   CmdArgs.push_back("-target");
6474   CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
6475   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6476   CmdArgs.push_back("-o");
6477   CmdArgs.push_back(Output.getFilename());
6478   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6479                                           CmdArgs, Inputs));
6480 }
6481 // AMDGPU tools end.
6482
6483 wasm::Linker::Linker(const ToolChain &TC)
6484   : GnuTool("wasm::Linker", "lld", TC) {}
6485
6486 bool wasm::Linker::isLinkJob() const {
6487   return true;
6488 }
6489
6490 bool wasm::Linker::hasIntegratedCPP() const {
6491   return false;
6492 }
6493
6494 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6495                                 const InputInfo &Output,
6496                                 const InputInfoList &Inputs,
6497                                 const ArgList &Args,
6498                                 const char *LinkingOutput) const {
6499   const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6500   ArgStringList CmdArgs;
6501   CmdArgs.push_back("-flavor");
6502   CmdArgs.push_back("ld");
6503   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6504   CmdArgs.push_back("-o");
6505   CmdArgs.push_back(Output.getFilename());
6506   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6507 }
6508
6509 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6510   std::string MArch;
6511   if (!Arch.empty())
6512     MArch = Arch;
6513   else
6514     MArch = Triple.getArchName();
6515   MArch = StringRef(MArch).split("+").first.lower();
6516
6517   // Handle -march=native.
6518   if (MArch == "native") {
6519     std::string CPU = llvm::sys::getHostCPUName();
6520     if (CPU != "generic") {
6521       // Translate the native cpu into the architecture suffix for that CPU.
6522       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6523       // If there is no valid architecture suffix for this CPU we don't know how
6524       // to handle it, so return no architecture.
6525       if (Suffix.empty())
6526         MArch = "";
6527       else
6528         MArch = std::string("arm") + Suffix.str();
6529     }
6530   }
6531
6532   return MArch;
6533 }
6534
6535 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6536 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6537   std::string MArch = getARMArch(Arch, Triple);
6538   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6539   // here means an -march=native that we can't handle, so instead return no CPU.
6540   if (MArch.empty())
6541     return StringRef();
6542
6543   // We need to return an empty string here on invalid MArch values as the
6544   // various places that call this function can't cope with a null result.
6545   return Triple.getARMCPUForArch(MArch);
6546 }
6547
6548 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6549 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6550                                  const llvm::Triple &Triple) {
6551   // FIXME: Warn on inconsistent use of -mcpu and -march.
6552   // If we have -mcpu=, use that.
6553   if (!CPU.empty()) {
6554     std::string MCPU = StringRef(CPU).split("+").first.lower();
6555     // Handle -mcpu=native.
6556     if (MCPU == "native")
6557       return llvm::sys::getHostCPUName();
6558     else
6559       return MCPU;
6560   }
6561
6562   return getARMCPUForMArch(Arch, Triple);
6563 }
6564
6565 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6566 /// CPU  (or Arch, if CPU is generic).
6567 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6568 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6569                                        const llvm::Triple &Triple) {
6570   unsigned ArchKind;
6571   if (CPU == "generic") {
6572     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6573     ArchKind = llvm::ARM::parseArch(ARMArch);
6574     if (ArchKind == llvm::ARM::AK_INVALID)
6575       // In case of generic Arch, i.e. "arm",
6576       // extract arch from default cpu of the Triple
6577       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6578   } else {
6579     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6580     // armv7k triple if it's actually been specified via "-arch armv7k".
6581     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6582                           ? (unsigned)llvm::ARM::AK_ARMV7K
6583                           : llvm::ARM::parseCPUArch(CPU);
6584   }
6585   if (ArchKind == llvm::ARM::AK_INVALID)
6586     return "";
6587   return llvm::ARM::getSubArch(ArchKind);
6588 }
6589
6590 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6591                             const llvm::Triple &Triple) {
6592   if (Args.hasArg(options::OPT_r))
6593     return;
6594
6595   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6596   // to generate BE-8 executables.
6597   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6598     CmdArgs.push_back("--be8");
6599 }
6600
6601 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6602   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6603   // was first introduced in Release 3. However, other compilers have
6604   // traditionally allowed it for Release 2 so we should do the same.
6605   return (NanEncoding)llvm::StringSwitch<int>(CPU)
6606       .Case("mips1", NanLegacy)
6607       .Case("mips2", NanLegacy)
6608       .Case("mips3", NanLegacy)
6609       .Case("mips4", NanLegacy)
6610       .Case("mips5", NanLegacy)
6611       .Case("mips32", NanLegacy)
6612       .Case("mips32r2", NanLegacy | Nan2008)
6613       .Case("mips32r3", NanLegacy | Nan2008)
6614       .Case("mips32r5", NanLegacy | Nan2008)
6615       .Case("mips32r6", Nan2008)
6616       .Case("mips64", NanLegacy)
6617       .Case("mips64r2", NanLegacy | Nan2008)
6618       .Case("mips64r3", NanLegacy | Nan2008)
6619       .Case("mips64r5", NanLegacy | Nan2008)
6620       .Case("mips64r6", Nan2008)
6621       .Default(NanLegacy);
6622 }
6623
6624 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6625   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6626   return A && (A->getValue() == StringRef(Value));
6627 }
6628
6629 bool mips::isUCLibc(const ArgList &Args) {
6630   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6631   return A && A->getOption().matches(options::OPT_muclibc);
6632 }
6633
6634 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6635   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6636     return llvm::StringSwitch<bool>(NaNArg->getValue())
6637         .Case("2008", true)
6638         .Case("legacy", false)
6639         .Default(false);
6640
6641   // NaN2008 is the default for MIPS32r6/MIPS64r6.
6642   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6643       .Cases("mips32r6", "mips64r6", true)
6644       .Default(false);
6645
6646   return false;
6647 }
6648
6649 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6650                          StringRef ABIName, mips::FloatABI FloatABI) {
6651   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6652       Triple.getVendor() != llvm::Triple::MipsTechnologies)
6653     return false;
6654
6655   if (ABIName != "32")
6656     return false;
6657
6658   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6659   // present.
6660   if (FloatABI == mips::FloatABI::Soft)
6661     return false;
6662
6663   return llvm::StringSwitch<bool>(CPUName)
6664       .Cases("mips2", "mips3", "mips4", "mips5", true)
6665       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6666       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6667       .Default(false);
6668 }
6669
6670 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6671                          StringRef CPUName, StringRef ABIName,
6672                          mips::FloatABI FloatABI) {
6673   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6674
6675   // FPXX shouldn't be used if -msingle-float is present.
6676   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6677                                options::OPT_mdouble_float))
6678     if (A->getOption().matches(options::OPT_msingle_float))
6679       UseFPXX = false;
6680
6681   return UseFPXX;
6682 }
6683
6684 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6685   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6686   // archs which Darwin doesn't use.
6687
6688   // The matching this routine does is fairly pointless, since it is neither the
6689   // complete architecture list, nor a reasonable subset. The problem is that
6690   // historically the driver driver accepts this and also ties its -march=
6691   // handling to the architecture name, so we need to be careful before removing
6692   // support for it.
6693
6694   // This code must be kept in sync with Clang's Darwin specific argument
6695   // translation.
6696
6697   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6698       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6699       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6700       .Case("ppc64", llvm::Triple::ppc64)
6701       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6702       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6703              llvm::Triple::x86)
6704       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6705       // This is derived from the driver driver.
6706       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6707       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6708       .Cases("armv7s", "xscale", llvm::Triple::arm)
6709       .Case("arm64", llvm::Triple::aarch64)
6710       .Case("r600", llvm::Triple::r600)
6711       .Case("amdgcn", llvm::Triple::amdgcn)
6712       .Case("nvptx", llvm::Triple::nvptx)
6713       .Case("nvptx64", llvm::Triple::nvptx64)
6714       .Case("amdil", llvm::Triple::amdil)
6715       .Case("spir", llvm::Triple::spir)
6716       .Default(llvm::Triple::UnknownArch);
6717 }
6718
6719 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6720   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6721   T.setArch(Arch);
6722
6723   if (Str == "x86_64h")
6724     T.setArchName(Str);
6725   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6726     T.setOS(llvm::Triple::UnknownOS);
6727     T.setObjectFormat(llvm::Triple::MachO);
6728   }
6729 }
6730
6731 const char *Clang::getBaseInputName(const ArgList &Args,
6732                                     const InputInfo &Input) {
6733   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6734 }
6735
6736 const char *Clang::getBaseInputStem(const ArgList &Args,
6737                                     const InputInfoList &Inputs) {
6738   const char *Str = getBaseInputName(Args, Inputs[0]);
6739
6740   if (const char *End = strrchr(Str, '.'))
6741     return Args.MakeArgString(std::string(Str, End));
6742
6743   return Str;
6744 }
6745
6746 const char *Clang::getDependencyFileName(const ArgList &Args,
6747                                          const InputInfoList &Inputs) {
6748   // FIXME: Think about this more.
6749   std::string Res;
6750
6751   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6752     std::string Str(OutputOpt->getValue());
6753     Res = Str.substr(0, Str.rfind('.'));
6754   } else {
6755     Res = getBaseInputStem(Args, Inputs);
6756   }
6757   return Args.MakeArgString(Res + ".d");
6758 }
6759
6760 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6761                                     const InputInfo &Output,
6762                                     const InputInfoList &Inputs,
6763                                     const ArgList &Args,
6764                                     const char *LinkingOutput) const {
6765   const ToolChain &ToolChain = getToolChain();
6766   const Driver &D = ToolChain.getDriver();
6767   ArgStringList CmdArgs;
6768
6769   // Silence warning for "clang -g foo.o -o foo"
6770   Args.ClaimAllArgs(options::OPT_g_Group);
6771   // and "clang -emit-llvm foo.o -o foo"
6772   Args.ClaimAllArgs(options::OPT_emit_llvm);
6773   // and for "clang -w foo.o -o foo". Other warning options are already
6774   // handled somewhere else.
6775   Args.ClaimAllArgs(options::OPT_w);
6776
6777   if (!D.SysRoot.empty())
6778     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6779
6780   // CloudABI only supports static linkage.
6781   CmdArgs.push_back("-Bstatic");
6782   CmdArgs.push_back("--eh-frame-hdr");
6783   CmdArgs.push_back("--gc-sections");
6784
6785   if (Output.isFilename()) {
6786     CmdArgs.push_back("-o");
6787     CmdArgs.push_back(Output.getFilename());
6788   } else {
6789     assert(Output.isNothing() && "Invalid output.");
6790   }
6791
6792   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6793     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6794     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6795   }
6796
6797   Args.AddAllArgs(CmdArgs, options::OPT_L);
6798   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6799   Args.AddAllArgs(CmdArgs,
6800                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6801                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6802
6803   if (D.isUsingLTO())
6804     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6805
6806   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6807
6808   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6809     if (D.CCCIsCXX())
6810       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6811     CmdArgs.push_back("-lc");
6812     CmdArgs.push_back("-lcompiler_rt");
6813   }
6814
6815   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6816     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6817
6818   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6819   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6820 }
6821
6822 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6823                                      const InputInfo &Output,
6824                                      const InputInfoList &Inputs,
6825                                      const ArgList &Args,
6826                                      const char *LinkingOutput) const {
6827   ArgStringList CmdArgs;
6828
6829   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6830   const InputInfo &Input = Inputs[0];
6831
6832   // Determine the original source input.
6833   const Action *SourceAction = &JA;
6834   while (SourceAction->getKind() != Action::InputClass) {
6835     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6836     SourceAction = SourceAction->getInputs()[0];
6837   }
6838
6839   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6840   // sure it runs its system assembler not clang's integrated assembler.
6841   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
6842   // FIXME: at run-time detect assembler capabilities or rely on version
6843   // information forwarded by -target-assembler-version.
6844   if (Args.hasArg(options::OPT_fno_integrated_as)) {
6845     const llvm::Triple &T(getToolChain().getTriple());
6846     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6847       CmdArgs.push_back("-Q");
6848   }
6849
6850   // Forward -g, assuming we are dealing with an actual assembly file.
6851   if (SourceAction->getType() == types::TY_Asm ||
6852       SourceAction->getType() == types::TY_PP_Asm) {
6853     if (Args.hasArg(options::OPT_gstabs))
6854       CmdArgs.push_back("--gstabs");
6855     else if (Args.hasArg(options::OPT_g_Group))
6856       CmdArgs.push_back("-g");
6857   }
6858
6859   // Derived from asm spec.
6860   AddMachOArch(Args, CmdArgs);
6861
6862   // Use -force_cpusubtype_ALL on x86 by default.
6863   if (getToolChain().getArch() == llvm::Triple::x86 ||
6864       getToolChain().getArch() == llvm::Triple::x86_64 ||
6865       Args.hasArg(options::OPT_force__cpusubtype__ALL))
6866     CmdArgs.push_back("-force_cpusubtype_ALL");
6867
6868   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6869       (((Args.hasArg(options::OPT_mkernel) ||
6870          Args.hasArg(options::OPT_fapple_kext)) &&
6871         getMachOToolChain().isKernelStatic()) ||
6872        Args.hasArg(options::OPT_static)))
6873     CmdArgs.push_back("-static");
6874
6875   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6876
6877   assert(Output.isFilename() && "Unexpected lipo output.");
6878   CmdArgs.push_back("-o");
6879   CmdArgs.push_back(Output.getFilename());
6880
6881   assert(Input.isFilename() && "Invalid input.");
6882   CmdArgs.push_back(Input.getFilename());
6883
6884   // asm_final spec is empty.
6885
6886   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6887   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6888 }
6889
6890 void darwin::MachOTool::anchor() {}
6891
6892 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6893                                      ArgStringList &CmdArgs) const {
6894   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6895
6896   // Derived from darwin_arch spec.
6897   CmdArgs.push_back("-arch");
6898   CmdArgs.push_back(Args.MakeArgString(ArchName));
6899
6900   // FIXME: Is this needed anymore?
6901   if (ArchName == "arm")
6902     CmdArgs.push_back("-force_cpusubtype_ALL");
6903 }
6904
6905 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6906   // We only need to generate a temp path for LTO if we aren't compiling object
6907   // files. When compiling source files, we run 'dsymutil' after linking. We
6908   // don't run 'dsymutil' when compiling object files.
6909   for (const auto &Input : Inputs)
6910     if (Input.getType() != types::TY_Object)
6911       return true;
6912
6913   return false;
6914 }
6915
6916 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6917                                  ArgStringList &CmdArgs,
6918                                  const InputInfoList &Inputs) const {
6919   const Driver &D = getToolChain().getDriver();
6920   const toolchains::MachO &MachOTC = getMachOToolChain();
6921
6922   unsigned Version[3] = {0, 0, 0};
6923   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6924     bool HadExtra;
6925     if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6926                                    Version[2], HadExtra) ||
6927         HadExtra)
6928       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6929   }
6930
6931   // Newer linkers support -demangle. Pass it if supported and not disabled by
6932   // the user.
6933   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6934     CmdArgs.push_back("-demangle");
6935
6936   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6937     CmdArgs.push_back("-export_dynamic");
6938
6939   // If we are using App Extension restrictions, pass a flag to the linker
6940   // telling it that the compiled code has been audited.
6941   if (Args.hasFlag(options::OPT_fapplication_extension,
6942                    options::OPT_fno_application_extension, false))
6943     CmdArgs.push_back("-application_extension");
6944
6945   if (D.isUsingLTO()) {
6946     // If we are using LTO, then automatically create a temporary file path for
6947     // the linker to use, so that it's lifetime will extend past a possible
6948     // dsymutil step.
6949     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
6950       const char *TmpPath = C.getArgs().MakeArgString(
6951           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6952       C.addTempFile(TmpPath);
6953       CmdArgs.push_back("-object_path_lto");
6954       CmdArgs.push_back(TmpPath);
6955     }
6956
6957     // Use -lto_library option to specify the libLTO.dylib path. Try to find
6958     // it in clang installed libraries. If not found, the option is not used
6959     // and 'ld' will use its default mechanism to search for libLTO.dylib.
6960     if (Version[0] >= 133) {
6961       // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
6962       StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
6963       SmallString<128> LibLTOPath(P);
6964       llvm::sys::path::append(LibLTOPath, "lib");
6965       llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
6966       if (llvm::sys::fs::exists(LibLTOPath)) {
6967         CmdArgs.push_back("-lto_library");
6968         CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
6969       } else {
6970         D.Diag(diag::warn_drv_lto_libpath);
6971       }
6972     }
6973   }
6974
6975   // Derived from the "link" spec.
6976   Args.AddAllArgs(CmdArgs, options::OPT_static);
6977   if (!Args.hasArg(options::OPT_static))
6978     CmdArgs.push_back("-dynamic");
6979   if (Args.hasArg(options::OPT_fgnu_runtime)) {
6980     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6981     // here. How do we wish to handle such things?
6982   }
6983
6984   if (!Args.hasArg(options::OPT_dynamiclib)) {
6985     AddMachOArch(Args, CmdArgs);
6986     // FIXME: Why do this only on this path?
6987     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6988
6989     Args.AddLastArg(CmdArgs, options::OPT_bundle);
6990     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6991     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6992
6993     Arg *A;
6994     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6995         (A = Args.getLastArg(options::OPT_current__version)) ||
6996         (A = Args.getLastArg(options::OPT_install__name)))
6997       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6998                                                        << "-dynamiclib";
6999
7000     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7001     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7002     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7003   } else {
7004     CmdArgs.push_back("-dylib");
7005
7006     Arg *A;
7007     if ((A = Args.getLastArg(options::OPT_bundle)) ||
7008         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7009         (A = Args.getLastArg(options::OPT_client__name)) ||
7010         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7011         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7012         (A = Args.getLastArg(options::OPT_private__bundle)))
7013       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7014                                                       << "-dynamiclib";
7015
7016     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7017                               "-dylib_compatibility_version");
7018     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7019                               "-dylib_current_version");
7020
7021     AddMachOArch(Args, CmdArgs);
7022
7023     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7024                               "-dylib_install_name");
7025   }
7026
7027   Args.AddLastArg(CmdArgs, options::OPT_all__load);
7028   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7029   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7030   if (MachOTC.isTargetIOSBased())
7031     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7032   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7033   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7034   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7035   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7036   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7037   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7038   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7039   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7040   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7041   Args.AddAllArgs(CmdArgs, options::OPT_init);
7042
7043   // Add the deployment target.
7044   MachOTC.addMinVersionArgs(Args, CmdArgs);
7045
7046   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7047   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7048   Args.AddLastArg(CmdArgs, options::OPT_single__module);
7049   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7050   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7051
7052   if (const Arg *A =
7053           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7054                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
7055     if (A->getOption().matches(options::OPT_fpie) ||
7056         A->getOption().matches(options::OPT_fPIE))
7057       CmdArgs.push_back("-pie");
7058     else
7059       CmdArgs.push_back("-no_pie");
7060   }
7061
7062   Args.AddLastArg(CmdArgs, options::OPT_prebind);
7063   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7064   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7065   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7066   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7067   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7068   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7069   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7070   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7071   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7072   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7073   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7074   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7075   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7076   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7077   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7078
7079   // Give --sysroot= preference, over the Apple specific behavior to also use
7080   // --isysroot as the syslibroot.
7081   StringRef sysroot = C.getSysRoot();
7082   if (sysroot != "") {
7083     CmdArgs.push_back("-syslibroot");
7084     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7085   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7086     CmdArgs.push_back("-syslibroot");
7087     CmdArgs.push_back(A->getValue());
7088   }
7089
7090   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7091   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7092   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7093   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7094   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7095   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7096   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7097   Args.AddAllArgs(CmdArgs, options::OPT_y);
7098   Args.AddLastArg(CmdArgs, options::OPT_w);
7099   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7100   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7101   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7102   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7103   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7104   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7105   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7106   Args.AddLastArg(CmdArgs, options::OPT_whyload);
7107   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7108   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7109   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7110   Args.AddLastArg(CmdArgs, options::OPT_Mach);
7111 }
7112
7113 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7114                                   const InputInfo &Output,
7115                                   const InputInfoList &Inputs,
7116                                   const ArgList &Args,
7117                                   const char *LinkingOutput) const {
7118   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7119
7120   // If the number of arguments surpasses the system limits, we will encode the
7121   // input files in a separate file, shortening the command line. To this end,
7122   // build a list of input file names that can be passed via a file with the
7123   // -filelist linker option.
7124   llvm::opt::ArgStringList InputFileList;
7125
7126   // The logic here is derived from gcc's behavior; most of which
7127   // comes from specs (starting with link_command). Consult gcc for
7128   // more information.
7129   ArgStringList CmdArgs;
7130
7131   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7132   if (Args.hasArg(options::OPT_ccc_arcmt_check,
7133                   options::OPT_ccc_arcmt_migrate)) {
7134     for (const auto &Arg : Args)
7135       Arg->claim();
7136     const char *Exec =
7137         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7138     CmdArgs.push_back(Output.getFilename());
7139     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7140     return;
7141   }
7142
7143   // I'm not sure why this particular decomposition exists in gcc, but
7144   // we follow suite for ease of comparison.
7145   AddLinkArgs(C, Args, CmdArgs, Inputs);
7146
7147   // It seems that the 'e' option is completely ignored for dynamic executables
7148   // (the default), and with static executables, the last one wins, as expected.
7149   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7150                             options::OPT_Z_Flag, options::OPT_u_Group,
7151                             options::OPT_e, options::OPT_r});
7152
7153   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7154   // members of static archive libraries which implement Objective-C classes or
7155   // categories.
7156   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7157     CmdArgs.push_back("-ObjC");
7158
7159   CmdArgs.push_back("-o");
7160   CmdArgs.push_back(Output.getFilename());
7161
7162   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7163     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7164
7165   // SafeStack requires its own runtime libraries
7166   // These libraries should be linked first, to make sure the
7167   // __safestack_init constructor executes before everything else
7168   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7169     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7170                                           "libclang_rt.safestack_osx.a",
7171                                           /*AlwaysLink=*/true);
7172   }
7173
7174   Args.AddAllArgs(CmdArgs, options::OPT_L);
7175
7176   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7177   // Build the input file for -filelist (list of linker input files) in case we
7178   // need it later
7179   for (const auto &II : Inputs) {
7180     if (!II.isFilename()) {
7181       // This is a linker input argument.
7182       // We cannot mix input arguments and file names in a -filelist input, thus
7183       // we prematurely stop our list (remaining files shall be passed as
7184       // arguments).
7185       if (InputFileList.size() > 0)
7186         break;
7187
7188       continue;
7189     }
7190
7191     InputFileList.push_back(II.getFilename());
7192   }
7193
7194   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7195     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7196
7197   if (isObjCRuntimeLinked(Args) &&
7198       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7199     // We use arclite library for both ARC and subscripting support.
7200     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7201
7202     CmdArgs.push_back("-framework");
7203     CmdArgs.push_back("Foundation");
7204     // Link libobj.
7205     CmdArgs.push_back("-lobjc");
7206   }
7207
7208   if (LinkingOutput) {
7209     CmdArgs.push_back("-arch_multiple");
7210     CmdArgs.push_back("-final_output");
7211     CmdArgs.push_back(LinkingOutput);
7212   }
7213
7214   if (Args.hasArg(options::OPT_fnested_functions))
7215     CmdArgs.push_back("-allow_stack_execute");
7216
7217   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7218
7219   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7220     if (getToolChain().getDriver().CCCIsCXX())
7221       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7222
7223     // link_ssp spec is empty.
7224
7225     // Let the tool chain choose which runtime library to link.
7226     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7227   }
7228
7229   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7230     // endfile_spec is empty.
7231   }
7232
7233   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7234   Args.AddAllArgs(CmdArgs, options::OPT_F);
7235
7236   // -iframework should be forwarded as -F.
7237   for (const Arg *A : Args.filtered(options::OPT_iframework))
7238     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7239
7240   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7241     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7242       if (A->getValue() == StringRef("Accelerate")) {
7243         CmdArgs.push_back("-framework");
7244         CmdArgs.push_back("Accelerate");
7245       }
7246     }
7247   }
7248
7249   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7250   std::unique_ptr<Command> Cmd =
7251       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7252   Cmd->setInputFileList(std::move(InputFileList));
7253   C.addCommand(std::move(Cmd));
7254 }
7255
7256 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7257                                 const InputInfo &Output,
7258                                 const InputInfoList &Inputs,
7259                                 const ArgList &Args,
7260                                 const char *LinkingOutput) const {
7261   ArgStringList CmdArgs;
7262
7263   CmdArgs.push_back("-create");
7264   assert(Output.isFilename() && "Unexpected lipo output.");
7265
7266   CmdArgs.push_back("-output");
7267   CmdArgs.push_back(Output.getFilename());
7268
7269   for (const auto &II : Inputs) {
7270     assert(II.isFilename() && "Unexpected lipo input.");
7271     CmdArgs.push_back(II.getFilename());
7272   }
7273
7274   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7275   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7276 }
7277
7278 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7279                                     const InputInfo &Output,
7280                                     const InputInfoList &Inputs,
7281                                     const ArgList &Args,
7282                                     const char *LinkingOutput) const {
7283   ArgStringList CmdArgs;
7284
7285   CmdArgs.push_back("-o");
7286   CmdArgs.push_back(Output.getFilename());
7287
7288   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7289   const InputInfo &Input = Inputs[0];
7290   assert(Input.isFilename() && "Unexpected dsymutil input.");
7291   CmdArgs.push_back(Input.getFilename());
7292
7293   const char *Exec =
7294       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7295   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7296 }
7297
7298 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7299                                        const InputInfo &Output,
7300                                        const InputInfoList &Inputs,
7301                                        const ArgList &Args,
7302                                        const char *LinkingOutput) const {
7303   ArgStringList CmdArgs;
7304   CmdArgs.push_back("--verify");
7305   CmdArgs.push_back("--debug-info");
7306   CmdArgs.push_back("--eh-frame");
7307   CmdArgs.push_back("--quiet");
7308
7309   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7310   const InputInfo &Input = Inputs[0];
7311   assert(Input.isFilename() && "Unexpected verify input");
7312
7313   // Grabbing the output of the earlier dsymutil run.
7314   CmdArgs.push_back(Input.getFilename());
7315
7316   const char *Exec =
7317       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7318   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7319 }
7320
7321 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7322                                       const InputInfo &Output,
7323                                       const InputInfoList &Inputs,
7324                                       const ArgList &Args,
7325                                       const char *LinkingOutput) const {
7326   claimNoWarnArgs(Args);
7327   ArgStringList CmdArgs;
7328
7329   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7330
7331   CmdArgs.push_back("-o");
7332   CmdArgs.push_back(Output.getFilename());
7333
7334   for (const auto &II : Inputs)
7335     CmdArgs.push_back(II.getFilename());
7336
7337   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7338   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7339 }
7340
7341 void solaris::Linker::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   // Demangle C++ names in errors
7349   CmdArgs.push_back("-C");
7350
7351   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7352     CmdArgs.push_back("-e");
7353     CmdArgs.push_back("_start");
7354   }
7355
7356   if (Args.hasArg(options::OPT_static)) {
7357     CmdArgs.push_back("-Bstatic");
7358     CmdArgs.push_back("-dn");
7359   } else {
7360     CmdArgs.push_back("-Bdynamic");
7361     if (Args.hasArg(options::OPT_shared)) {
7362       CmdArgs.push_back("-shared");
7363     } else {
7364       CmdArgs.push_back("--dynamic-linker");
7365       CmdArgs.push_back(
7366           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7367     }
7368   }
7369
7370   if (Output.isFilename()) {
7371     CmdArgs.push_back("-o");
7372     CmdArgs.push_back(Output.getFilename());
7373   } else {
7374     assert(Output.isNothing() && "Invalid output.");
7375   }
7376
7377   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7378     if (!Args.hasArg(options::OPT_shared))
7379       CmdArgs.push_back(
7380           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7381
7382     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7383     CmdArgs.push_back(
7384         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7385     CmdArgs.push_back(
7386         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7387   }
7388
7389   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7390
7391   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7392                             options::OPT_e, options::OPT_r});
7393
7394   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7395
7396   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7397     if (getToolChain().getDriver().CCCIsCXX())
7398       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7399     CmdArgs.push_back("-lgcc_s");
7400     CmdArgs.push_back("-lc");
7401     if (!Args.hasArg(options::OPT_shared)) {
7402       CmdArgs.push_back("-lgcc");
7403       CmdArgs.push_back("-lm");
7404     }
7405   }
7406
7407   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7408     CmdArgs.push_back(
7409         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7410   }
7411   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7412
7413   getToolChain().addProfileRTLibs(Args, CmdArgs);
7414
7415   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7416   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7417 }
7418
7419 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7420                                       const InputInfo &Output,
7421                                       const InputInfoList &Inputs,
7422                                       const ArgList &Args,
7423                                       const char *LinkingOutput) const {
7424   claimNoWarnArgs(Args);
7425   ArgStringList CmdArgs;
7426
7427   switch (getToolChain().getArch()) {
7428   case llvm::Triple::x86:
7429     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7430     // instruct as in the base system to assemble 32-bit code.
7431     CmdArgs.push_back("--32");
7432     break;
7433
7434   case llvm::Triple::ppc:
7435     CmdArgs.push_back("-mppc");
7436     CmdArgs.push_back("-many");
7437     break;
7438
7439   case llvm::Triple::sparc:
7440   case llvm::Triple::sparcel: {
7441     CmdArgs.push_back("-32");
7442     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7443     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7444     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7445     break;
7446   }
7447
7448   case llvm::Triple::sparcv9: {
7449     CmdArgs.push_back("-64");
7450     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7451     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7452     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7453     break;
7454   }
7455
7456   case llvm::Triple::mips64:
7457   case llvm::Triple::mips64el: {
7458     StringRef CPUName;
7459     StringRef ABIName;
7460     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7461
7462     CmdArgs.push_back("-mabi");
7463     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7464
7465     if (getToolChain().getArch() == llvm::Triple::mips64)
7466       CmdArgs.push_back("-EB");
7467     else
7468       CmdArgs.push_back("-EL");
7469
7470     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7471     break;
7472   }
7473
7474   default:
7475     break;
7476   }
7477
7478   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7479
7480   CmdArgs.push_back("-o");
7481   CmdArgs.push_back(Output.getFilename());
7482
7483   for (const auto &II : Inputs)
7484     CmdArgs.push_back(II.getFilename());
7485
7486   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7487   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7488 }
7489
7490 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7491                                    const InputInfo &Output,
7492                                    const InputInfoList &Inputs,
7493                                    const ArgList &Args,
7494                                    const char *LinkingOutput) const {
7495   const Driver &D = getToolChain().getDriver();
7496   ArgStringList CmdArgs;
7497
7498   // Silence warning for "clang -g foo.o -o foo"
7499   Args.ClaimAllArgs(options::OPT_g_Group);
7500   // and "clang -emit-llvm foo.o -o foo"
7501   Args.ClaimAllArgs(options::OPT_emit_llvm);
7502   // and for "clang -w foo.o -o foo". Other warning options are already
7503   // handled somewhere else.
7504   Args.ClaimAllArgs(options::OPT_w);
7505
7506   if (getToolChain().getArch() == llvm::Triple::mips64)
7507     CmdArgs.push_back("-EB");
7508   else if (getToolChain().getArch() == llvm::Triple::mips64el)
7509     CmdArgs.push_back("-EL");
7510
7511   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7512     CmdArgs.push_back("-e");
7513     CmdArgs.push_back("__start");
7514   }
7515
7516   if (Args.hasArg(options::OPT_static)) {
7517     CmdArgs.push_back("-Bstatic");
7518   } else {
7519     if (Args.hasArg(options::OPT_rdynamic))
7520       CmdArgs.push_back("-export-dynamic");
7521     CmdArgs.push_back("--eh-frame-hdr");
7522     CmdArgs.push_back("-Bdynamic");
7523     if (Args.hasArg(options::OPT_shared)) {
7524       CmdArgs.push_back("-shared");
7525     } else {
7526       CmdArgs.push_back("-dynamic-linker");
7527       CmdArgs.push_back("/usr/libexec/ld.so");
7528     }
7529   }
7530
7531   if (Args.hasArg(options::OPT_nopie))
7532     CmdArgs.push_back("-nopie");
7533
7534   if (Output.isFilename()) {
7535     CmdArgs.push_back("-o");
7536     CmdArgs.push_back(Output.getFilename());
7537   } else {
7538     assert(Output.isNothing() && "Invalid output.");
7539   }
7540
7541   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7542     if (!Args.hasArg(options::OPT_shared)) {
7543       if (Args.hasArg(options::OPT_pg))
7544         CmdArgs.push_back(
7545             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7546       else
7547         CmdArgs.push_back(
7548             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7549       CmdArgs.push_back(
7550           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7551     } else {
7552       CmdArgs.push_back(
7553           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7554     }
7555   }
7556
7557   std::string Triple = getToolChain().getTripleString();
7558   if (Triple.substr(0, 6) == "x86_64")
7559     Triple.replace(0, 6, "amd64");
7560   CmdArgs.push_back(
7561       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7562
7563   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7564                             options::OPT_e, options::OPT_s, options::OPT_t,
7565                             options::OPT_Z_Flag, options::OPT_r});
7566
7567   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7568
7569   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7570     if (D.CCCIsCXX()) {
7571       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7572       if (Args.hasArg(options::OPT_pg))
7573         CmdArgs.push_back("-lm_p");
7574       else
7575         CmdArgs.push_back("-lm");
7576     }
7577
7578     // FIXME: For some reason GCC passes -lgcc before adding
7579     // the default system libraries. Just mimic this for now.
7580     CmdArgs.push_back("-lgcc");
7581
7582     if (Args.hasArg(options::OPT_pthread)) {
7583       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7584         CmdArgs.push_back("-lpthread_p");
7585       else
7586         CmdArgs.push_back("-lpthread");
7587     }
7588
7589     if (!Args.hasArg(options::OPT_shared)) {
7590       if (Args.hasArg(options::OPT_pg))
7591         CmdArgs.push_back("-lc_p");
7592       else
7593         CmdArgs.push_back("-lc");
7594     }
7595
7596     CmdArgs.push_back("-lgcc");
7597   }
7598
7599   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7600     if (!Args.hasArg(options::OPT_shared))
7601       CmdArgs.push_back(
7602           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7603     else
7604       CmdArgs.push_back(
7605           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7606   }
7607
7608   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7609   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7610 }
7611
7612 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7613                                      const InputInfo &Output,
7614                                      const InputInfoList &Inputs,
7615                                      const ArgList &Args,
7616                                      const char *LinkingOutput) const {
7617   claimNoWarnArgs(Args);
7618   ArgStringList CmdArgs;
7619
7620   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7621
7622   CmdArgs.push_back("-o");
7623   CmdArgs.push_back(Output.getFilename());
7624
7625   for (const auto &II : Inputs)
7626     CmdArgs.push_back(II.getFilename());
7627
7628   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7629   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7630 }
7631
7632 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7633                                   const InputInfo &Output,
7634                                   const InputInfoList &Inputs,
7635                                   const ArgList &Args,
7636                                   const char *LinkingOutput) const {
7637   const Driver &D = getToolChain().getDriver();
7638   ArgStringList CmdArgs;
7639
7640   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7641     CmdArgs.push_back("-e");
7642     CmdArgs.push_back("__start");
7643   }
7644
7645   if (Args.hasArg(options::OPT_static)) {
7646     CmdArgs.push_back("-Bstatic");
7647   } else {
7648     if (Args.hasArg(options::OPT_rdynamic))
7649       CmdArgs.push_back("-export-dynamic");
7650     CmdArgs.push_back("--eh-frame-hdr");
7651     CmdArgs.push_back("-Bdynamic");
7652     if (Args.hasArg(options::OPT_shared)) {
7653       CmdArgs.push_back("-shared");
7654     } else {
7655       CmdArgs.push_back("-dynamic-linker");
7656       CmdArgs.push_back("/usr/libexec/ld.so");
7657     }
7658   }
7659
7660   if (Output.isFilename()) {
7661     CmdArgs.push_back("-o");
7662     CmdArgs.push_back(Output.getFilename());
7663   } else {
7664     assert(Output.isNothing() && "Invalid output.");
7665   }
7666
7667   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7668     if (!Args.hasArg(options::OPT_shared)) {
7669       if (Args.hasArg(options::OPT_pg))
7670         CmdArgs.push_back(
7671             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7672       else
7673         CmdArgs.push_back(
7674             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7675       CmdArgs.push_back(
7676           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7677     } else {
7678       CmdArgs.push_back(
7679           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7680     }
7681   }
7682
7683   Args.AddAllArgs(CmdArgs,
7684                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7685
7686   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7687
7688   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7689     if (D.CCCIsCXX()) {
7690       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7691       if (Args.hasArg(options::OPT_pg))
7692         CmdArgs.push_back("-lm_p");
7693       else
7694         CmdArgs.push_back("-lm");
7695     }
7696
7697     if (Args.hasArg(options::OPT_pthread)) {
7698       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7699         CmdArgs.push_back("-lpthread_p");
7700       else
7701         CmdArgs.push_back("-lpthread");
7702     }
7703
7704     if (!Args.hasArg(options::OPT_shared)) {
7705       if (Args.hasArg(options::OPT_pg))
7706         CmdArgs.push_back("-lc_p");
7707       else
7708         CmdArgs.push_back("-lc");
7709     }
7710
7711     StringRef MyArch;
7712     switch (getToolChain().getArch()) {
7713     case llvm::Triple::arm:
7714       MyArch = "arm";
7715       break;
7716     case llvm::Triple::x86:
7717       MyArch = "i386";
7718       break;
7719     case llvm::Triple::x86_64:
7720       MyArch = "amd64";
7721       break;
7722     default:
7723       llvm_unreachable("Unsupported architecture");
7724     }
7725     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7726   }
7727
7728   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7729     if (!Args.hasArg(options::OPT_shared))
7730       CmdArgs.push_back(
7731           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7732     else
7733       CmdArgs.push_back(
7734           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7735   }
7736
7737   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7738   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7739 }
7740
7741 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7742                                       const InputInfo &Output,
7743                                       const InputInfoList &Inputs,
7744                                       const ArgList &Args,
7745                                       const char *LinkingOutput) const {
7746   claimNoWarnArgs(Args);
7747   ArgStringList CmdArgs;
7748
7749   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7750   // instruct as in the base system to assemble 32-bit code.
7751   switch (getToolChain().getArch()) {
7752   default:
7753     break;
7754   case llvm::Triple::x86:
7755     CmdArgs.push_back("--32");
7756     break;
7757   case llvm::Triple::ppc:
7758     CmdArgs.push_back("-a32");
7759     break;
7760   case llvm::Triple::mips:
7761   case llvm::Triple::mipsel:
7762   case llvm::Triple::mips64:
7763   case llvm::Triple::mips64el: {
7764     StringRef CPUName;
7765     StringRef ABIName;
7766     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7767
7768     CmdArgs.push_back("-march");
7769     CmdArgs.push_back(CPUName.data());
7770
7771     CmdArgs.push_back("-mabi");
7772     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7773
7774     if (getToolChain().getArch() == llvm::Triple::mips ||
7775         getToolChain().getArch() == llvm::Triple::mips64)
7776       CmdArgs.push_back("-EB");
7777     else
7778       CmdArgs.push_back("-EL");
7779
7780     if (Arg *A = Args.getLastArg(options::OPT_G)) {
7781       StringRef v = A->getValue();
7782       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7783       A->claim();
7784     }
7785
7786     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7787     break;
7788   }
7789   case llvm::Triple::arm:
7790   case llvm::Triple::armeb:
7791   case llvm::Triple::thumb:
7792   case llvm::Triple::thumbeb: {
7793     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7794
7795     if (ABI == arm::FloatABI::Hard)
7796       CmdArgs.push_back("-mfpu=vfp");
7797     else
7798       CmdArgs.push_back("-mfpu=softvfp");
7799
7800     switch (getToolChain().getTriple().getEnvironment()) {
7801     case llvm::Triple::GNUEABIHF:
7802     case llvm::Triple::GNUEABI:
7803     case llvm::Triple::EABI:
7804       CmdArgs.push_back("-meabi=5");
7805       break;
7806
7807     default:
7808       CmdArgs.push_back("-matpcs");
7809     }
7810     break;
7811   }
7812   case llvm::Triple::sparc:
7813   case llvm::Triple::sparcel:
7814   case llvm::Triple::sparcv9: {
7815     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7816     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7817     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7818     break;
7819   }
7820   }
7821
7822   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7823
7824   CmdArgs.push_back("-o");
7825   CmdArgs.push_back(Output.getFilename());
7826
7827   for (const auto &II : Inputs)
7828     CmdArgs.push_back(II.getFilename());
7829
7830   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7831   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7832 }
7833
7834 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7835                                    const InputInfo &Output,
7836                                    const InputInfoList &Inputs,
7837                                    const ArgList &Args,
7838                                    const char *LinkingOutput) const {
7839   const toolchains::FreeBSD &ToolChain =
7840       static_cast<const toolchains::FreeBSD &>(getToolChain());
7841   const Driver &D = ToolChain.getDriver();
7842   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7843   const bool IsPIE =
7844       !Args.hasArg(options::OPT_shared) &&
7845       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7846   ArgStringList CmdArgs;
7847
7848   // Silence warning for "clang -g foo.o -o foo"
7849   Args.ClaimAllArgs(options::OPT_g_Group);
7850   // and "clang -emit-llvm foo.o -o foo"
7851   Args.ClaimAllArgs(options::OPT_emit_llvm);
7852   // and for "clang -w foo.o -o foo". Other warning options are already
7853   // handled somewhere else.
7854   Args.ClaimAllArgs(options::OPT_w);
7855
7856   if (!D.SysRoot.empty())
7857     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7858
7859   if (IsPIE)
7860     CmdArgs.push_back("-pie");
7861
7862   if (Args.hasArg(options::OPT_static)) {
7863     CmdArgs.push_back("-Bstatic");
7864   } else {
7865     if (Args.hasArg(options::OPT_rdynamic))
7866       CmdArgs.push_back("-export-dynamic");
7867     CmdArgs.push_back("--eh-frame-hdr");
7868     if (Args.hasArg(options::OPT_shared)) {
7869       CmdArgs.push_back("-Bshareable");
7870     } else {
7871       CmdArgs.push_back("-dynamic-linker");
7872       CmdArgs.push_back("/libexec/ld-elf.so.1");
7873     }
7874     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7875       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7876           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7877         CmdArgs.push_back("--hash-style=both");
7878       }
7879     }
7880     CmdArgs.push_back("--enable-new-dtags");
7881   }
7882
7883   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7884   // instruct ld in the base system to link 32-bit code.
7885   if (Arch == llvm::Triple::x86) {
7886     CmdArgs.push_back("-m");
7887     CmdArgs.push_back("elf_i386_fbsd");
7888   }
7889
7890   if (Arch == llvm::Triple::ppc) {
7891     CmdArgs.push_back("-m");
7892     CmdArgs.push_back("elf32ppc_fbsd");
7893   }
7894
7895   if (Arg *A = Args.getLastArg(options::OPT_G)) {
7896     if (ToolChain.getArch() == llvm::Triple::mips ||
7897       ToolChain.getArch() == llvm::Triple::mipsel ||
7898       ToolChain.getArch() == llvm::Triple::mips64 ||
7899       ToolChain.getArch() == llvm::Triple::mips64el) {
7900       StringRef v = A->getValue();
7901       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7902       A->claim();
7903     }
7904   }
7905
7906   if (Output.isFilename()) {
7907     CmdArgs.push_back("-o");
7908     CmdArgs.push_back(Output.getFilename());
7909   } else {
7910     assert(Output.isNothing() && "Invalid output.");
7911   }
7912
7913   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7914     const char *crt1 = nullptr;
7915     if (!Args.hasArg(options::OPT_shared)) {
7916       if (Args.hasArg(options::OPT_pg))
7917         crt1 = "gcrt1.o";
7918       else if (IsPIE)
7919         crt1 = "Scrt1.o";
7920       else
7921         crt1 = "crt1.o";
7922     }
7923     if (crt1)
7924       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7925
7926     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7927
7928     const char *crtbegin = nullptr;
7929     if (Args.hasArg(options::OPT_static))
7930       crtbegin = "crtbeginT.o";
7931     else if (Args.hasArg(options::OPT_shared) || IsPIE)
7932       crtbegin = "crtbeginS.o";
7933     else
7934       crtbegin = "crtbegin.o";
7935
7936     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7937   }
7938
7939   Args.AddAllArgs(CmdArgs, options::OPT_L);
7940   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7941   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7942   Args.AddAllArgs(CmdArgs, options::OPT_e);
7943   Args.AddAllArgs(CmdArgs, options::OPT_s);
7944   Args.AddAllArgs(CmdArgs, options::OPT_t);
7945   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7946   Args.AddAllArgs(CmdArgs, options::OPT_r);
7947
7948   if (D.isUsingLTO())
7949     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7950
7951   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7952   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7953
7954   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7955     addOpenMPRuntime(CmdArgs, ToolChain, Args);
7956     if (D.CCCIsCXX()) {
7957       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7958       if (Args.hasArg(options::OPT_pg))
7959         CmdArgs.push_back("-lm_p");
7960       else
7961         CmdArgs.push_back("-lm");
7962     }
7963     if (NeedsSanitizerDeps)
7964       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7965     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7966     // the default system libraries. Just mimic this for now.
7967     if (Args.hasArg(options::OPT_pg))
7968       CmdArgs.push_back("-lgcc_p");
7969     else
7970       CmdArgs.push_back("-lgcc");
7971     if (Args.hasArg(options::OPT_static)) {
7972       CmdArgs.push_back("-lgcc_eh");
7973     } else if (Args.hasArg(options::OPT_pg)) {
7974       CmdArgs.push_back("-lgcc_eh_p");
7975     } else {
7976       CmdArgs.push_back("--as-needed");
7977       CmdArgs.push_back("-lgcc_s");
7978       CmdArgs.push_back("--no-as-needed");
7979     }
7980
7981     if (Args.hasArg(options::OPT_pthread)) {
7982       if (Args.hasArg(options::OPT_pg))
7983         CmdArgs.push_back("-lpthread_p");
7984       else
7985         CmdArgs.push_back("-lpthread");
7986     }
7987
7988     if (Args.hasArg(options::OPT_pg)) {
7989       if (Args.hasArg(options::OPT_shared))
7990         CmdArgs.push_back("-lc");
7991       else
7992         CmdArgs.push_back("-lc_p");
7993       CmdArgs.push_back("-lgcc_p");
7994     } else {
7995       CmdArgs.push_back("-lc");
7996       CmdArgs.push_back("-lgcc");
7997     }
7998
7999     if (Args.hasArg(options::OPT_static)) {
8000       CmdArgs.push_back("-lgcc_eh");
8001     } else if (Args.hasArg(options::OPT_pg)) {
8002       CmdArgs.push_back("-lgcc_eh_p");
8003     } else {
8004       CmdArgs.push_back("--as-needed");
8005       CmdArgs.push_back("-lgcc_s");
8006       CmdArgs.push_back("--no-as-needed");
8007     }
8008   }
8009
8010   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8011     if (Args.hasArg(options::OPT_shared) || IsPIE)
8012       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8013     else
8014       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8015     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8016   }
8017
8018   ToolChain.addProfileRTLibs(Args, CmdArgs);
8019
8020   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8021   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8022 }
8023
8024 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8025                                      const InputInfo &Output,
8026                                      const InputInfoList &Inputs,
8027                                      const ArgList &Args,
8028                                      const char *LinkingOutput) const {
8029   claimNoWarnArgs(Args);
8030   ArgStringList CmdArgs;
8031
8032   // GNU as needs different flags for creating the correct output format
8033   // on architectures with different ABIs or optional feature sets.
8034   switch (getToolChain().getArch()) {
8035   case llvm::Triple::x86:
8036     CmdArgs.push_back("--32");
8037     break;
8038   case llvm::Triple::arm:
8039   case llvm::Triple::armeb:
8040   case llvm::Triple::thumb:
8041   case llvm::Triple::thumbeb: {
8042     StringRef MArch, MCPU;
8043     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8044     std::string Arch =
8045         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8046     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8047     break;
8048   }
8049
8050   case llvm::Triple::mips:
8051   case llvm::Triple::mipsel:
8052   case llvm::Triple::mips64:
8053   case llvm::Triple::mips64el: {
8054     StringRef CPUName;
8055     StringRef ABIName;
8056     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8057
8058     CmdArgs.push_back("-march");
8059     CmdArgs.push_back(CPUName.data());
8060
8061     CmdArgs.push_back("-mabi");
8062     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8063
8064     if (getToolChain().getArch() == llvm::Triple::mips ||
8065         getToolChain().getArch() == llvm::Triple::mips64)
8066       CmdArgs.push_back("-EB");
8067     else
8068       CmdArgs.push_back("-EL");
8069
8070     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8071     break;
8072   }
8073
8074   case llvm::Triple::sparc:
8075   case llvm::Triple::sparcel: {
8076     CmdArgs.push_back("-32");
8077     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8078     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8079     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8080     break;
8081   }
8082
8083   case llvm::Triple::sparcv9: {
8084     CmdArgs.push_back("-64");
8085     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8086     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8087     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8088     break;
8089   }
8090
8091   default:
8092     break;
8093   }
8094
8095   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8096
8097   CmdArgs.push_back("-o");
8098   CmdArgs.push_back(Output.getFilename());
8099
8100   for (const auto &II : Inputs)
8101     CmdArgs.push_back(II.getFilename());
8102
8103   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8104   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8105 }
8106
8107 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8108                                   const InputInfo &Output,
8109                                   const InputInfoList &Inputs,
8110                                   const ArgList &Args,
8111                                   const char *LinkingOutput) const {
8112   const Driver &D = getToolChain().getDriver();
8113   ArgStringList CmdArgs;
8114
8115   if (!D.SysRoot.empty())
8116     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8117
8118   CmdArgs.push_back("--eh-frame-hdr");
8119   if (Args.hasArg(options::OPT_static)) {
8120     CmdArgs.push_back("-Bstatic");
8121   } else {
8122     if (Args.hasArg(options::OPT_rdynamic))
8123       CmdArgs.push_back("-export-dynamic");
8124     if (Args.hasArg(options::OPT_shared)) {
8125       CmdArgs.push_back("-Bshareable");
8126     } else {
8127       CmdArgs.push_back("-dynamic-linker");
8128       CmdArgs.push_back("/libexec/ld.elf_so");
8129     }
8130   }
8131
8132   // Many NetBSD architectures support more than one ABI.
8133   // Determine the correct emulation for ld.
8134   switch (getToolChain().getArch()) {
8135   case llvm::Triple::x86:
8136     CmdArgs.push_back("-m");
8137     CmdArgs.push_back("elf_i386");
8138     break;
8139   case llvm::Triple::arm:
8140   case llvm::Triple::thumb:
8141     CmdArgs.push_back("-m");
8142     switch (getToolChain().getTriple().getEnvironment()) {
8143     case llvm::Triple::EABI:
8144     case llvm::Triple::GNUEABI:
8145       CmdArgs.push_back("armelf_nbsd_eabi");
8146       break;
8147     case llvm::Triple::EABIHF:
8148     case llvm::Triple::GNUEABIHF:
8149       CmdArgs.push_back("armelf_nbsd_eabihf");
8150       break;
8151     default:
8152       CmdArgs.push_back("armelf_nbsd");
8153       break;
8154     }
8155     break;
8156   case llvm::Triple::armeb:
8157   case llvm::Triple::thumbeb:
8158     arm::appendEBLinkFlags(
8159         Args, CmdArgs,
8160         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8161     CmdArgs.push_back("-m");
8162     switch (getToolChain().getTriple().getEnvironment()) {
8163     case llvm::Triple::EABI:
8164     case llvm::Triple::GNUEABI:
8165       CmdArgs.push_back("armelfb_nbsd_eabi");
8166       break;
8167     case llvm::Triple::EABIHF:
8168     case llvm::Triple::GNUEABIHF:
8169       CmdArgs.push_back("armelfb_nbsd_eabihf");
8170       break;
8171     default:
8172       CmdArgs.push_back("armelfb_nbsd");
8173       break;
8174     }
8175     break;
8176   case llvm::Triple::mips64:
8177   case llvm::Triple::mips64el:
8178     if (mips::hasMipsAbiArg(Args, "32")) {
8179       CmdArgs.push_back("-m");
8180       if (getToolChain().getArch() == llvm::Triple::mips64)
8181         CmdArgs.push_back("elf32btsmip");
8182       else
8183         CmdArgs.push_back("elf32ltsmip");
8184     } else if (mips::hasMipsAbiArg(Args, "64")) {
8185       CmdArgs.push_back("-m");
8186       if (getToolChain().getArch() == llvm::Triple::mips64)
8187         CmdArgs.push_back("elf64btsmip");
8188       else
8189         CmdArgs.push_back("elf64ltsmip");
8190     }
8191     break;
8192   case llvm::Triple::ppc:
8193     CmdArgs.push_back("-m");
8194     CmdArgs.push_back("elf32ppc_nbsd");
8195     break;
8196
8197   case llvm::Triple::ppc64:
8198   case llvm::Triple::ppc64le:
8199     CmdArgs.push_back("-m");
8200     CmdArgs.push_back("elf64ppc");
8201     break;
8202
8203   case llvm::Triple::sparc:
8204     CmdArgs.push_back("-m");
8205     CmdArgs.push_back("elf32_sparc");
8206     break;
8207
8208   case llvm::Triple::sparcv9:
8209     CmdArgs.push_back("-m");
8210     CmdArgs.push_back("elf64_sparc");
8211     break;
8212
8213   default:
8214     break;
8215   }
8216
8217   if (Output.isFilename()) {
8218     CmdArgs.push_back("-o");
8219     CmdArgs.push_back(Output.getFilename());
8220   } else {
8221     assert(Output.isNothing() && "Invalid output.");
8222   }
8223
8224   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8225     if (!Args.hasArg(options::OPT_shared)) {
8226       CmdArgs.push_back(
8227           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8228       CmdArgs.push_back(
8229           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8230       CmdArgs.push_back(
8231           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8232     } else {
8233       CmdArgs.push_back(
8234           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8235       CmdArgs.push_back(
8236           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8237     }
8238   }
8239
8240   Args.AddAllArgs(CmdArgs, options::OPT_L);
8241   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8242   Args.AddAllArgs(CmdArgs, options::OPT_e);
8243   Args.AddAllArgs(CmdArgs, options::OPT_s);
8244   Args.AddAllArgs(CmdArgs, options::OPT_t);
8245   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8246   Args.AddAllArgs(CmdArgs, options::OPT_r);
8247
8248   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8249
8250   unsigned Major, Minor, Micro;
8251   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8252   bool useLibgcc = true;
8253   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8254     switch (getToolChain().getArch()) {
8255     case llvm::Triple::aarch64:
8256     case llvm::Triple::arm:
8257     case llvm::Triple::armeb:
8258     case llvm::Triple::thumb:
8259     case llvm::Triple::thumbeb:
8260     case llvm::Triple::ppc:
8261     case llvm::Triple::ppc64:
8262     case llvm::Triple::ppc64le:
8263     case llvm::Triple::x86:
8264     case llvm::Triple::x86_64:
8265       useLibgcc = false;
8266       break;
8267     default:
8268       break;
8269     }
8270   }
8271
8272   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8273     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8274     if (D.CCCIsCXX()) {
8275       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8276       CmdArgs.push_back("-lm");
8277     }
8278     if (Args.hasArg(options::OPT_pthread))
8279       CmdArgs.push_back("-lpthread");
8280     CmdArgs.push_back("-lc");
8281
8282     if (useLibgcc) {
8283       if (Args.hasArg(options::OPT_static)) {
8284         // libgcc_eh depends on libc, so resolve as much as possible,
8285         // pull in any new requirements from libc and then get the rest
8286         // of libgcc.
8287         CmdArgs.push_back("-lgcc_eh");
8288         CmdArgs.push_back("-lc");
8289         CmdArgs.push_back("-lgcc");
8290       } else {
8291         CmdArgs.push_back("-lgcc");
8292         CmdArgs.push_back("--as-needed");
8293         CmdArgs.push_back("-lgcc_s");
8294         CmdArgs.push_back("--no-as-needed");
8295       }
8296     }
8297   }
8298
8299   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8300     if (!Args.hasArg(options::OPT_shared))
8301       CmdArgs.push_back(
8302           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8303     else
8304       CmdArgs.push_back(
8305           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8306     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8307   }
8308
8309   getToolChain().addProfileRTLibs(Args, CmdArgs);
8310
8311   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8312   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8313 }
8314
8315 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8316                                        const InputInfo &Output,
8317                                        const InputInfoList &Inputs,
8318                                        const ArgList &Args,
8319                                        const char *LinkingOutput) const {
8320   claimNoWarnArgs(Args);
8321
8322   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8323   llvm::Triple Triple = llvm::Triple(TripleStr);
8324
8325   ArgStringList CmdArgs;
8326
8327   llvm::Reloc::Model RelocationModel;
8328   unsigned PICLevel;
8329   bool IsPIE;
8330   std::tie(RelocationModel, PICLevel, IsPIE) =
8331       ParsePICArgs(getToolChain(), Triple, Args);
8332
8333   switch (getToolChain().getArch()) {
8334   default:
8335     break;
8336   // Add --32/--64 to make sure we get the format we want.
8337   // This is incomplete
8338   case llvm::Triple::x86:
8339     CmdArgs.push_back("--32");
8340     break;
8341   case llvm::Triple::x86_64:
8342     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8343       CmdArgs.push_back("--x32");
8344     else
8345       CmdArgs.push_back("--64");
8346     break;
8347   case llvm::Triple::ppc:
8348     CmdArgs.push_back("-a32");
8349     CmdArgs.push_back("-mppc");
8350     CmdArgs.push_back("-many");
8351     break;
8352   case llvm::Triple::ppc64:
8353     CmdArgs.push_back("-a64");
8354     CmdArgs.push_back("-mppc64");
8355     CmdArgs.push_back("-many");
8356     break;
8357   case llvm::Triple::ppc64le:
8358     CmdArgs.push_back("-a64");
8359     CmdArgs.push_back("-mppc64");
8360     CmdArgs.push_back("-many");
8361     CmdArgs.push_back("-mlittle-endian");
8362     break;
8363   case llvm::Triple::sparc:
8364   case llvm::Triple::sparcel: {
8365     CmdArgs.push_back("-32");
8366     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8367     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8368     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8369     break;
8370   }
8371   case llvm::Triple::sparcv9: {
8372     CmdArgs.push_back("-64");
8373     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8374     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8375     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8376     break;
8377   }
8378   case llvm::Triple::arm:
8379   case llvm::Triple::armeb:
8380   case llvm::Triple::thumb:
8381   case llvm::Triple::thumbeb: {
8382     const llvm::Triple &Triple2 = getToolChain().getTriple();
8383     switch (Triple2.getSubArch()) {
8384     case llvm::Triple::ARMSubArch_v7:
8385       CmdArgs.push_back("-mfpu=neon");
8386       break;
8387     case llvm::Triple::ARMSubArch_v8:
8388       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8389       break;
8390     default:
8391       break;
8392     }
8393
8394     switch (arm::getARMFloatABI(getToolChain(), Args)) {
8395     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8396     case arm::FloatABI::Soft:
8397       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8398       break;
8399     case arm::FloatABI::SoftFP:
8400       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8401       break;
8402     case arm::FloatABI::Hard:
8403       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8404       break;
8405     }
8406
8407     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8408
8409     // FIXME: remove krait check when GNU tools support krait cpu
8410     // for now replace it with -march=armv7-a  to avoid a lower
8411     // march from being picked in the absence of a cpu flag.
8412     Arg *A;
8413     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8414         StringRef(A->getValue()).lower() == "krait")
8415       CmdArgs.push_back("-march=armv7-a");
8416     else
8417       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8418     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8419     break;
8420   }
8421   case llvm::Triple::mips:
8422   case llvm::Triple::mipsel:
8423   case llvm::Triple::mips64:
8424   case llvm::Triple::mips64el: {
8425     StringRef CPUName;
8426     StringRef ABIName;
8427     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8428     ABIName = getGnuCompatibleMipsABIName(ABIName);
8429
8430     CmdArgs.push_back("-march");
8431     CmdArgs.push_back(CPUName.data());
8432
8433     CmdArgs.push_back("-mabi");
8434     CmdArgs.push_back(ABIName.data());
8435
8436     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8437     // or -mshared (not implemented) is in effect.
8438     if (RelocationModel == llvm::Reloc::Static)
8439       CmdArgs.push_back("-mno-shared");
8440
8441     // LLVM doesn't support -mplt yet and acts as if it is always given.
8442     // However, -mplt has no effect with the N64 ABI.
8443     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8444
8445     if (getToolChain().getArch() == llvm::Triple::mips ||
8446         getToolChain().getArch() == llvm::Triple::mips64)
8447       CmdArgs.push_back("-EB");
8448     else
8449       CmdArgs.push_back("-EL");
8450
8451     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8452       if (StringRef(A->getValue()) == "2008")
8453         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8454     }
8455
8456     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8457     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8458                                  options::OPT_mfp64)) {
8459       A->claim();
8460       A->render(Args, CmdArgs);
8461     } else if (mips::shouldUseFPXX(
8462                    Args, getToolChain().getTriple(), CPUName, ABIName,
8463                    getMipsFloatABI(getToolChain().getDriver(), Args)))
8464       CmdArgs.push_back("-mfpxx");
8465
8466     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8467     // -mno-mips16 is actually -no-mips16.
8468     if (Arg *A =
8469             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8470       if (A->getOption().matches(options::OPT_mips16)) {
8471         A->claim();
8472         A->render(Args, CmdArgs);
8473       } else {
8474         A->claim();
8475         CmdArgs.push_back("-no-mips16");
8476       }
8477     }
8478
8479     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8480                     options::OPT_mno_micromips);
8481     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8482     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8483
8484     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8485       // Do not use AddLastArg because not all versions of MIPS assembler
8486       // support -mmsa / -mno-msa options.
8487       if (A->getOption().matches(options::OPT_mmsa))
8488         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8489     }
8490
8491     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8492                     options::OPT_msoft_float);
8493
8494     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8495                     options::OPT_msingle_float);
8496
8497     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8498                     options::OPT_mno_odd_spreg);
8499
8500     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8501     break;
8502   }
8503   case llvm::Triple::systemz: {
8504     // Always pass an -march option, since our default of z10 is later
8505     // than the GNU assembler's default.
8506     StringRef CPUName = getSystemZTargetCPU(Args);
8507     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8508     break;
8509   }
8510   }
8511
8512   Args.AddAllArgs(CmdArgs, options::OPT_I);
8513   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8514
8515   CmdArgs.push_back("-o");
8516   CmdArgs.push_back(Output.getFilename());
8517
8518   for (const auto &II : Inputs)
8519     CmdArgs.push_back(II.getFilename());
8520
8521   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8522   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8523
8524   // Handle the debug info splitting at object creation time if we're
8525   // creating an object.
8526   // TODO: Currently only works on linux with newer objcopy.
8527   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8528       getToolChain().getTriple().isOSLinux())
8529     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8530                    SplitDebugName(Args, Inputs[0]));
8531 }
8532
8533 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8534                       ArgStringList &CmdArgs, const ArgList &Args) {
8535   bool isAndroid = Triple.isAndroid();
8536   bool isCygMing = Triple.isOSCygMing();
8537   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8538                       Args.hasArg(options::OPT_static);
8539   if (!D.CCCIsCXX())
8540     CmdArgs.push_back("-lgcc");
8541
8542   if (StaticLibgcc || isAndroid) {
8543     if (D.CCCIsCXX())
8544       CmdArgs.push_back("-lgcc");
8545   } else {
8546     if (!D.CCCIsCXX() && !isCygMing)
8547       CmdArgs.push_back("--as-needed");
8548     CmdArgs.push_back("-lgcc_s");
8549     if (!D.CCCIsCXX() && !isCygMing)
8550       CmdArgs.push_back("--no-as-needed");
8551   }
8552
8553   if (StaticLibgcc && !isAndroid)
8554     CmdArgs.push_back("-lgcc_eh");
8555   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8556     CmdArgs.push_back("-lgcc");
8557
8558   // According to Android ABI, we have to link with libdl if we are
8559   // linking with non-static libgcc.
8560   //
8561   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
8562   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8563   if (isAndroid && !StaticLibgcc)
8564     CmdArgs.push_back("-ldl");
8565 }
8566
8567 static std::string getLinuxDynamicLinker(const ArgList &Args,
8568                                          const toolchains::Linux &ToolChain) {
8569   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8570
8571   if (ToolChain.getTriple().isAndroid()) {
8572     if (ToolChain.getTriple().isArch64Bit())
8573       return "/system/bin/linker64";
8574     else
8575       return "/system/bin/linker";
8576   } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8577              Arch == llvm::Triple::sparcel)
8578     return "/lib/ld-linux.so.2";
8579   else if (Arch == llvm::Triple::aarch64)
8580     return "/lib/ld-linux-aarch64.so.1";
8581   else if (Arch == llvm::Triple::aarch64_be)
8582     return "/lib/ld-linux-aarch64_be.so.1";
8583   else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8584     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8585         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8586       return "/lib/ld-linux-armhf.so.3";
8587     else
8588       return "/lib/ld-linux.so.3";
8589   } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8590     // TODO: check which dynamic linker name.
8591     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8592         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8593       return "/lib/ld-linux-armhf.so.3";
8594     else
8595       return "/lib/ld-linux.so.3";
8596   } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8597              Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8598     std::string LibDir =
8599         "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8600     StringRef LibName;
8601     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8602     if (mips::isUCLibc(Args))
8603       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8604     else if (!ToolChain.getTriple().hasEnvironment()) {
8605       bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8606                 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8607       LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8608     } else
8609       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8610
8611     return (LibDir + "/" + LibName).str();
8612   } else if (Arch == llvm::Triple::ppc)
8613     return "/lib/ld.so.1";
8614   else if (Arch == llvm::Triple::ppc64) {
8615     if (ppc::hasPPCAbiArg(Args, "elfv2"))
8616       return "/lib64/ld64.so.2";
8617     return "/lib64/ld64.so.1";
8618   } else if (Arch == llvm::Triple::ppc64le) {
8619     if (ppc::hasPPCAbiArg(Args, "elfv1"))
8620       return "/lib64/ld64.so.1";
8621     return "/lib64/ld64.so.2";
8622   } else if (Arch == llvm::Triple::systemz)
8623     return "/lib/ld64.so.1";
8624   else if (Arch == llvm::Triple::sparcv9)
8625     return "/lib64/ld-linux.so.2";
8626   else if (Arch == llvm::Triple::x86_64 &&
8627            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8628     return "/libx32/ld-linux-x32.so.2";
8629   else
8630     return "/lib64/ld-linux-x86-64.so.2";
8631 }
8632
8633 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8634                            ArgStringList &CmdArgs, const ArgList &Args) {
8635   // Make use of compiler-rt if --rtlib option is used
8636   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8637
8638   switch (RLT) {
8639   case ToolChain::RLT_CompilerRT:
8640     switch (TC.getTriple().getOS()) {
8641     default:
8642       llvm_unreachable("unsupported OS");
8643     case llvm::Triple::Win32:
8644     case llvm::Triple::Linux:
8645       addClangRT(TC, Args, CmdArgs);
8646       break;
8647     }
8648     break;
8649   case ToolChain::RLT_Libgcc:
8650     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8651     break;
8652   }
8653 }
8654
8655 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8656   switch (T.getArch()) {
8657   case llvm::Triple::x86:
8658     return "elf_i386";
8659   case llvm::Triple::aarch64:
8660     return "aarch64linux";
8661   case llvm::Triple::aarch64_be:
8662     return "aarch64_be_linux";
8663   case llvm::Triple::arm:
8664   case llvm::Triple::thumb:
8665     return "armelf_linux_eabi";
8666   case llvm::Triple::armeb:
8667   case llvm::Triple::thumbeb:
8668     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
8669   case llvm::Triple::ppc:
8670     return "elf32ppclinux";
8671   case llvm::Triple::ppc64:
8672     return "elf64ppc";
8673   case llvm::Triple::ppc64le:
8674     return "elf64lppc";
8675   case llvm::Triple::sparc:
8676   case llvm::Triple::sparcel:
8677     return "elf32_sparc";
8678   case llvm::Triple::sparcv9:
8679     return "elf64_sparc";
8680   case llvm::Triple::mips:
8681     return "elf32btsmip";
8682   case llvm::Triple::mipsel:
8683     return "elf32ltsmip";
8684   case llvm::Triple::mips64:
8685     if (mips::hasMipsAbiArg(Args, "n32"))
8686       return "elf32btsmipn32";
8687     return "elf64btsmip";
8688   case llvm::Triple::mips64el:
8689     if (mips::hasMipsAbiArg(Args, "n32"))
8690       return "elf32ltsmipn32";
8691     return "elf64ltsmip";
8692   case llvm::Triple::systemz:
8693     return "elf64_s390";
8694   case llvm::Triple::x86_64:
8695     if (T.getEnvironment() == llvm::Triple::GNUX32)
8696       return "elf32_x86_64";
8697     return "elf_x86_64";
8698   default:
8699     llvm_unreachable("Unexpected arch");
8700   }
8701 }
8702
8703 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8704                                     const InputInfo &Output,
8705                                     const InputInfoList &Inputs,
8706                                     const ArgList &Args,
8707                                     const char *LinkingOutput) const {
8708   const toolchains::Linux &ToolChain =
8709       static_cast<const toolchains::Linux &>(getToolChain());
8710   const Driver &D = ToolChain.getDriver();
8711
8712   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8713   llvm::Triple Triple = llvm::Triple(TripleStr);
8714
8715   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8716   const bool isAndroid = ToolChain.getTriple().isAndroid();
8717   const bool IsPIE =
8718       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8719       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8720   const bool HasCRTBeginEndFiles =
8721       ToolChain.getTriple().hasEnvironment() ||
8722       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8723
8724   ArgStringList CmdArgs;
8725
8726   // Silence warning for "clang -g foo.o -o foo"
8727   Args.ClaimAllArgs(options::OPT_g_Group);
8728   // and "clang -emit-llvm foo.o -o foo"
8729   Args.ClaimAllArgs(options::OPT_emit_llvm);
8730   // and for "clang -w foo.o -o foo". Other warning options are already
8731   // handled somewhere else.
8732   Args.ClaimAllArgs(options::OPT_w);
8733
8734   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8735   if (llvm::sys::path::filename(Exec) == "lld") {
8736     CmdArgs.push_back("-flavor");
8737     CmdArgs.push_back("old-gnu");
8738     CmdArgs.push_back("-target");
8739     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8740   }
8741
8742   if (!D.SysRoot.empty())
8743     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8744
8745   if (IsPIE)
8746     CmdArgs.push_back("-pie");
8747
8748   if (Args.hasArg(options::OPT_rdynamic))
8749     CmdArgs.push_back("-export-dynamic");
8750
8751   if (Args.hasArg(options::OPT_s))
8752     CmdArgs.push_back("-s");
8753
8754   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8755     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8756
8757   for (const auto &Opt : ToolChain.ExtraOpts)
8758     CmdArgs.push_back(Opt.c_str());
8759
8760   if (!Args.hasArg(options::OPT_static)) {
8761     CmdArgs.push_back("--eh-frame-hdr");
8762   }
8763
8764   CmdArgs.push_back("-m");
8765   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8766
8767   if (Args.hasArg(options::OPT_static)) {
8768     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8769         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8770       CmdArgs.push_back("-Bstatic");
8771     else
8772       CmdArgs.push_back("-static");
8773   } else if (Args.hasArg(options::OPT_shared)) {
8774     CmdArgs.push_back("-shared");
8775   }
8776
8777   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8778       Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8779       (!Args.hasArg(options::OPT_static) &&
8780        !Args.hasArg(options::OPT_shared))) {
8781     CmdArgs.push_back("-dynamic-linker");
8782     CmdArgs.push_back(Args.MakeArgString(
8783         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8784   }
8785
8786   CmdArgs.push_back("-o");
8787   CmdArgs.push_back(Output.getFilename());
8788
8789   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8790     if (!isAndroid) {
8791       const char *crt1 = nullptr;
8792       if (!Args.hasArg(options::OPT_shared)) {
8793         if (Args.hasArg(options::OPT_pg))
8794           crt1 = "gcrt1.o";
8795         else if (IsPIE)
8796           crt1 = "Scrt1.o";
8797         else
8798           crt1 = "crt1.o";
8799       }
8800       if (crt1)
8801         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8802
8803       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8804     }
8805
8806     const char *crtbegin;
8807     if (Args.hasArg(options::OPT_static))
8808       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8809     else if (Args.hasArg(options::OPT_shared))
8810       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8811     else if (IsPIE)
8812       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8813     else
8814       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8815
8816     if (HasCRTBeginEndFiles)
8817       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8818
8819     // Add crtfastmath.o if available and fast math is enabled.
8820     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8821   }
8822
8823   Args.AddAllArgs(CmdArgs, options::OPT_L);
8824   Args.AddAllArgs(CmdArgs, options::OPT_u);
8825
8826   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8827
8828   if (D.isUsingLTO())
8829     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8830
8831   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8832     CmdArgs.push_back("--no-demangle");
8833
8834   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8835   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8836   // The profile runtime also needs access to system libraries.
8837   getToolChain().addProfileRTLibs(Args, CmdArgs);
8838
8839   if (D.CCCIsCXX() &&
8840       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8841     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8842                                !Args.hasArg(options::OPT_static);
8843     if (OnlyLibstdcxxStatic)
8844       CmdArgs.push_back("-Bstatic");
8845     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8846     if (OnlyLibstdcxxStatic)
8847       CmdArgs.push_back("-Bdynamic");
8848     CmdArgs.push_back("-lm");
8849   }
8850   // Silence warnings when linking C code with a C++ '-stdlib' argument.
8851   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8852
8853   if (!Args.hasArg(options::OPT_nostdlib)) {
8854     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8855       if (Args.hasArg(options::OPT_static))
8856         CmdArgs.push_back("--start-group");
8857
8858       if (NeedsSanitizerDeps)
8859         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8860
8861       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8862                          Args.hasArg(options::OPT_pthreads);
8863
8864       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8865                        options::OPT_fno_openmp, false)) {
8866         // OpenMP runtimes implies pthreads when using the GNU toolchain.
8867         // FIXME: Does this really make sense for all GNU toolchains?
8868         WantPthread = true;
8869
8870         // Also link the particular OpenMP runtimes.
8871         switch (getOpenMPRuntime(ToolChain, Args)) {
8872         case OMPRT_OMP:
8873           CmdArgs.push_back("-lomp");
8874           break;
8875         case OMPRT_GOMP:
8876           CmdArgs.push_back("-lgomp");
8877
8878           // FIXME: Exclude this for platforms with libgomp that don't require
8879           // librt. Most modern Linux platforms require it, but some may not.
8880           CmdArgs.push_back("-lrt");
8881           break;
8882         case OMPRT_IOMP5:
8883           CmdArgs.push_back("-liomp5");
8884           break;
8885         case OMPRT_Unknown:
8886           // Already diagnosed.
8887           break;
8888         }
8889       }
8890
8891       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8892
8893       if (WantPthread && !isAndroid)
8894         CmdArgs.push_back("-lpthread");
8895
8896       CmdArgs.push_back("-lc");
8897
8898       if (Args.hasArg(options::OPT_static))
8899         CmdArgs.push_back("--end-group");
8900       else
8901         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8902     }
8903
8904     if (!Args.hasArg(options::OPT_nostartfiles)) {
8905       const char *crtend;
8906       if (Args.hasArg(options::OPT_shared))
8907         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8908       else if (IsPIE)
8909         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8910       else
8911         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8912
8913       if (HasCRTBeginEndFiles)
8914         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8915       if (!isAndroid)
8916         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8917     }
8918   }
8919
8920   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8921 }
8922
8923 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8924 // for the various SFI requirements like register masking. The assembly tool
8925 // inserts the file containing the macros as an input into all the assembly
8926 // jobs.
8927 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8928                                            const InputInfo &Output,
8929                                            const InputInfoList &Inputs,
8930                                            const ArgList &Args,
8931                                            const char *LinkingOutput) const {
8932   const toolchains::NaClToolChain &ToolChain =
8933       static_cast<const toolchains::NaClToolChain &>(getToolChain());
8934   InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8935                        "nacl-arm-macros.s");
8936   InputInfoList NewInputs;
8937   NewInputs.push_back(NaClMacros);
8938   NewInputs.append(Inputs.begin(), Inputs.end());
8939   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8940                                     LinkingOutput);
8941 }
8942
8943 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8944 // we use static by default, do not yet support sanitizers or LTO, and a few
8945 // others. Eventually we can support more of that and hopefully migrate back
8946 // to gnutools::Linker.
8947 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8948                                      const InputInfo &Output,
8949                                      const InputInfoList &Inputs,
8950                                      const ArgList &Args,
8951                                      const char *LinkingOutput) const {
8952
8953   const toolchains::NaClToolChain &ToolChain =
8954       static_cast<const toolchains::NaClToolChain &>(getToolChain());
8955   const Driver &D = ToolChain.getDriver();
8956   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8957   const bool IsStatic =
8958       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8959
8960   ArgStringList CmdArgs;
8961
8962   // Silence warning for "clang -g foo.o -o foo"
8963   Args.ClaimAllArgs(options::OPT_g_Group);
8964   // and "clang -emit-llvm foo.o -o foo"
8965   Args.ClaimAllArgs(options::OPT_emit_llvm);
8966   // and for "clang -w foo.o -o foo". Other warning options are already
8967   // handled somewhere else.
8968   Args.ClaimAllArgs(options::OPT_w);
8969
8970   if (!D.SysRoot.empty())
8971     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8972
8973   if (Args.hasArg(options::OPT_rdynamic))
8974     CmdArgs.push_back("-export-dynamic");
8975
8976   if (Args.hasArg(options::OPT_s))
8977     CmdArgs.push_back("-s");
8978
8979   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
8980   // from there is --build-id, which we do want.
8981   CmdArgs.push_back("--build-id");
8982
8983   if (!IsStatic)
8984     CmdArgs.push_back("--eh-frame-hdr");
8985
8986   CmdArgs.push_back("-m");
8987   if (Arch == llvm::Triple::x86)
8988     CmdArgs.push_back("elf_i386_nacl");
8989   else if (Arch == llvm::Triple::arm)
8990     CmdArgs.push_back("armelf_nacl");
8991   else if (Arch == llvm::Triple::x86_64)
8992     CmdArgs.push_back("elf_x86_64_nacl");
8993   else if (Arch == llvm::Triple::mipsel)
8994     CmdArgs.push_back("mipselelf_nacl");
8995   else
8996     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8997                                               << "Native Client";
8998
8999   if (IsStatic)
9000     CmdArgs.push_back("-static");
9001   else if (Args.hasArg(options::OPT_shared))
9002     CmdArgs.push_back("-shared");
9003
9004   CmdArgs.push_back("-o");
9005   CmdArgs.push_back(Output.getFilename());
9006   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9007     if (!Args.hasArg(options::OPT_shared))
9008       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9009     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9010
9011     const char *crtbegin;
9012     if (IsStatic)
9013       crtbegin = "crtbeginT.o";
9014     else if (Args.hasArg(options::OPT_shared))
9015       crtbegin = "crtbeginS.o";
9016     else
9017       crtbegin = "crtbegin.o";
9018     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9019   }
9020
9021   Args.AddAllArgs(CmdArgs, options::OPT_L);
9022   Args.AddAllArgs(CmdArgs, options::OPT_u);
9023
9024   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9025
9026   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9027     CmdArgs.push_back("--no-demangle");
9028
9029   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9030
9031   if (D.CCCIsCXX() &&
9032       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9033     bool OnlyLibstdcxxStatic =
9034         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9035     if (OnlyLibstdcxxStatic)
9036       CmdArgs.push_back("-Bstatic");
9037     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9038     if (OnlyLibstdcxxStatic)
9039       CmdArgs.push_back("-Bdynamic");
9040     CmdArgs.push_back("-lm");
9041   }
9042
9043   if (!Args.hasArg(options::OPT_nostdlib)) {
9044     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9045       // Always use groups, since it has no effect on dynamic libraries.
9046       CmdArgs.push_back("--start-group");
9047       CmdArgs.push_back("-lc");
9048       // NaCl's libc++ currently requires libpthread, so just always include it
9049       // in the group for C++.
9050       if (Args.hasArg(options::OPT_pthread) ||
9051           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9052         // Gold, used by Mips, handles nested groups differently than ld, and
9053         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9054         // which is not a desired behaviour here.
9055         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9056         if (getToolChain().getArch() == llvm::Triple::mipsel)
9057           CmdArgs.push_back("-lnacl");
9058
9059         CmdArgs.push_back("-lpthread");
9060       }
9061
9062       CmdArgs.push_back("-lgcc");
9063       CmdArgs.push_back("--as-needed");
9064       if (IsStatic)
9065         CmdArgs.push_back("-lgcc_eh");
9066       else
9067         CmdArgs.push_back("-lgcc_s");
9068       CmdArgs.push_back("--no-as-needed");
9069
9070       // Mips needs to create and use pnacl_legacy library that contains
9071       // definitions from bitcode/pnaclmm.c and definitions for
9072       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9073       if (getToolChain().getArch() == llvm::Triple::mipsel)
9074         CmdArgs.push_back("-lpnacl_legacy");
9075
9076       CmdArgs.push_back("--end-group");
9077     }
9078
9079     if (!Args.hasArg(options::OPT_nostartfiles)) {
9080       const char *crtend;
9081       if (Args.hasArg(options::OPT_shared))
9082         crtend = "crtendS.o";
9083       else
9084         crtend = "crtend.o";
9085
9086       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9087       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9088     }
9089   }
9090
9091   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9092   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9093 }
9094
9095 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9096                                     const InputInfo &Output,
9097                                     const InputInfoList &Inputs,
9098                                     const ArgList &Args,
9099                                     const char *LinkingOutput) const {
9100   claimNoWarnArgs(Args);
9101   ArgStringList CmdArgs;
9102
9103   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9104
9105   CmdArgs.push_back("-o");
9106   CmdArgs.push_back(Output.getFilename());
9107
9108   for (const auto &II : Inputs)
9109     CmdArgs.push_back(II.getFilename());
9110
9111   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9112   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9113 }
9114
9115 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9116                                  const InputInfo &Output,
9117                                  const InputInfoList &Inputs,
9118                                  const ArgList &Args,
9119                                  const char *LinkingOutput) const {
9120   const Driver &D = getToolChain().getDriver();
9121   ArgStringList CmdArgs;
9122
9123   if (Output.isFilename()) {
9124     CmdArgs.push_back("-o");
9125     CmdArgs.push_back(Output.getFilename());
9126   } else {
9127     assert(Output.isNothing() && "Invalid output.");
9128   }
9129
9130   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9131     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9132     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9133     CmdArgs.push_back(
9134         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9135     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9136   }
9137
9138   Args.AddAllArgs(CmdArgs,
9139                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9140
9141   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9142
9143   getToolChain().addProfileRTLibs(Args, CmdArgs);
9144
9145   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9146     if (D.CCCIsCXX()) {
9147       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9148       CmdArgs.push_back("-lm");
9149     }
9150   }
9151
9152   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9153     if (Args.hasArg(options::OPT_pthread))
9154       CmdArgs.push_back("-lpthread");
9155     CmdArgs.push_back("-lc");
9156     CmdArgs.push_back("-lCompilerRT-Generic");
9157     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9158     CmdArgs.push_back(
9159         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9160   }
9161
9162   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9163   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9164 }
9165
9166 /// DragonFly Tools
9167
9168 // For now, DragonFly Assemble does just about the same as for
9169 // FreeBSD, but this may change soon.
9170 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9171                                         const InputInfo &Output,
9172                                         const InputInfoList &Inputs,
9173                                         const ArgList &Args,
9174                                         const char *LinkingOutput) const {
9175   claimNoWarnArgs(Args);
9176   ArgStringList CmdArgs;
9177
9178   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9179   // instruct as in the base system to assemble 32-bit code.
9180   if (getToolChain().getArch() == llvm::Triple::x86)
9181     CmdArgs.push_back("--32");
9182
9183   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9184
9185   CmdArgs.push_back("-o");
9186   CmdArgs.push_back(Output.getFilename());
9187
9188   for (const auto &II : Inputs)
9189     CmdArgs.push_back(II.getFilename());
9190
9191   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9192   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9193 }
9194
9195 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9196                                      const InputInfo &Output,
9197                                      const InputInfoList &Inputs,
9198                                      const ArgList &Args,
9199                                      const char *LinkingOutput) const {
9200   const Driver &D = getToolChain().getDriver();
9201   ArgStringList CmdArgs;
9202
9203   if (!D.SysRoot.empty())
9204     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9205
9206   CmdArgs.push_back("--eh-frame-hdr");
9207   if (Args.hasArg(options::OPT_static)) {
9208     CmdArgs.push_back("-Bstatic");
9209   } else {
9210     if (Args.hasArg(options::OPT_rdynamic))
9211       CmdArgs.push_back("-export-dynamic");
9212     if (Args.hasArg(options::OPT_shared))
9213       CmdArgs.push_back("-Bshareable");
9214     else {
9215       CmdArgs.push_back("-dynamic-linker");
9216       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9217     }
9218     CmdArgs.push_back("--hash-style=gnu");
9219     CmdArgs.push_back("--enable-new-dtags");
9220   }
9221
9222   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9223   // instruct ld in the base system to link 32-bit code.
9224   if (getToolChain().getArch() == llvm::Triple::x86) {
9225     CmdArgs.push_back("-m");
9226     CmdArgs.push_back("elf_i386");
9227   }
9228
9229   if (Output.isFilename()) {
9230     CmdArgs.push_back("-o");
9231     CmdArgs.push_back(Output.getFilename());
9232   } else {
9233     assert(Output.isNothing() && "Invalid output.");
9234   }
9235
9236   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9237     if (!Args.hasArg(options::OPT_shared)) {
9238       if (Args.hasArg(options::OPT_pg))
9239         CmdArgs.push_back(
9240             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9241       else {
9242         if (Args.hasArg(options::OPT_pie))
9243           CmdArgs.push_back(
9244               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9245         else
9246           CmdArgs.push_back(
9247               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9248       }
9249     }
9250     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9251     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9252       CmdArgs.push_back(
9253           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9254     else
9255       CmdArgs.push_back(
9256           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9257   }
9258
9259   Args.AddAllArgs(CmdArgs,
9260                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9261
9262   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9263
9264   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9265     CmdArgs.push_back("-L/usr/lib/gcc50");
9266
9267     if (!Args.hasArg(options::OPT_static)) {
9268       CmdArgs.push_back("-rpath");
9269       CmdArgs.push_back("/usr/lib/gcc50");
9270     }
9271
9272     if (D.CCCIsCXX()) {
9273       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9274       CmdArgs.push_back("-lm");
9275     }
9276
9277     if (Args.hasArg(options::OPT_pthread))
9278       CmdArgs.push_back("-lpthread");
9279
9280     if (!Args.hasArg(options::OPT_nolibc)) {
9281       CmdArgs.push_back("-lc");
9282     }
9283
9284     if (Args.hasArg(options::OPT_static) ||
9285         Args.hasArg(options::OPT_static_libgcc)) {
9286         CmdArgs.push_back("-lgcc");
9287         CmdArgs.push_back("-lgcc_eh");
9288     } else {
9289       if (Args.hasArg(options::OPT_shared_libgcc)) {
9290           CmdArgs.push_back("-lgcc_pic");
9291           if (!Args.hasArg(options::OPT_shared))
9292             CmdArgs.push_back("-lgcc");
9293       } else {
9294           CmdArgs.push_back("-lgcc");
9295           CmdArgs.push_back("--as-needed");
9296           CmdArgs.push_back("-lgcc_pic");
9297           CmdArgs.push_back("--no-as-needed");
9298       }
9299     }
9300   }
9301
9302   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9303     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9304       CmdArgs.push_back(
9305           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9306     else
9307       CmdArgs.push_back(
9308           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9309     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9310   }
9311
9312   getToolChain().addProfileRTLibs(Args, CmdArgs);
9313
9314   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9315   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9316 }
9317
9318 // Try to find Exe from a Visual Studio distribution.  This first tries to find
9319 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9320 // making sure that whatever executable that's found is not a same-named exe
9321 // from clang itself to prevent clang from falling back to itself.
9322 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9323                                               const char *Exe,
9324                                               const char *ClangProgramPath) {
9325   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9326   std::string visualStudioBinDir;
9327   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9328                                          visualStudioBinDir)) {
9329     SmallString<128> FilePath(visualStudioBinDir);
9330     llvm::sys::path::append(FilePath, Exe);
9331     if (llvm::sys::fs::can_execute(FilePath.c_str()))
9332       return FilePath.str();
9333   }
9334
9335   return Exe;
9336 }
9337
9338 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9339                                         const InputInfo &Output,
9340                                         const InputInfoList &Inputs,
9341                                         const ArgList &Args,
9342                                         const char *LinkingOutput) const {
9343   ArgStringList CmdArgs;
9344   const ToolChain &TC = getToolChain();
9345
9346   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9347   if (Output.isFilename())
9348     CmdArgs.push_back(
9349         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9350
9351   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9352       !C.getDriver().IsCLMode())
9353     CmdArgs.push_back("-defaultlib:libcmt");
9354
9355   if (!llvm::sys::Process::GetEnv("LIB")) {
9356     // If the VC environment hasn't been configured (perhaps because the user
9357     // did not run vcvarsall), try to build a consistent link environment.  If
9358     // the environment variable is set however, assume the user knows what
9359     // they're doing.
9360     std::string VisualStudioDir;
9361     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9362     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9363       SmallString<128> LibDir(VisualStudioDir);
9364       llvm::sys::path::append(LibDir, "VC", "lib");
9365       switch (MSVC.getArch()) {
9366       case llvm::Triple::x86:
9367         // x86 just puts the libraries directly in lib
9368         break;
9369       case llvm::Triple::x86_64:
9370         llvm::sys::path::append(LibDir, "amd64");
9371         break;
9372       case llvm::Triple::arm:
9373         llvm::sys::path::append(LibDir, "arm");
9374         break;
9375       default:
9376         break;
9377       }
9378       CmdArgs.push_back(
9379           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9380
9381       if (MSVC.useUniversalCRT(VisualStudioDir)) {
9382         std::string UniversalCRTLibPath;
9383         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9384           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9385                                                UniversalCRTLibPath.c_str()));
9386       }
9387     }
9388
9389     std::string WindowsSdkLibPath;
9390     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9391       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9392                                            WindowsSdkLibPath.c_str()));
9393   }
9394
9395   CmdArgs.push_back("-nologo");
9396
9397   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9398     CmdArgs.push_back("-debug");
9399
9400   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9401                          options::OPT_shared);
9402   if (DLL) {
9403     CmdArgs.push_back(Args.MakeArgString("-dll"));
9404
9405     SmallString<128> ImplibName(Output.getFilename());
9406     llvm::sys::path::replace_extension(ImplibName, "lib");
9407     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9408   }
9409
9410   if (TC.getSanitizerArgs().needsAsanRt()) {
9411     CmdArgs.push_back(Args.MakeArgString("-debug"));
9412     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9413     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9414       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9415         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9416       // Make sure the dynamic runtime thunk is not optimized out at link time
9417       // to ensure proper SEH handling.
9418       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9419     } else if (DLL) {
9420       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9421     } else {
9422       for (const auto &Lib : {"asan", "asan_cxx"})
9423         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9424     }
9425   }
9426
9427   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9428
9429   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9430                    options::OPT_fno_openmp, false)) {
9431     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9432     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9433     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9434                                          TC.getDriver().Dir + "/../lib"));
9435     switch (getOpenMPRuntime(getToolChain(), Args)) {
9436     case OMPRT_OMP:
9437       CmdArgs.push_back("-defaultlib:libomp.lib");
9438       break;
9439     case OMPRT_IOMP5:
9440       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9441       break;
9442     case OMPRT_GOMP:
9443       break;
9444     case OMPRT_Unknown:
9445       // Already diagnosed.
9446       break;
9447     }
9448   }
9449
9450   // Add filenames, libraries, and other linker inputs.
9451   for (const auto &Input : Inputs) {
9452     if (Input.isFilename()) {
9453       CmdArgs.push_back(Input.getFilename());
9454       continue;
9455     }
9456
9457     const Arg &A = Input.getInputArg();
9458
9459     // Render -l options differently for the MSVC linker.
9460     if (A.getOption().matches(options::OPT_l)) {
9461       StringRef Lib = A.getValue();
9462       const char *LinkLibArg;
9463       if (Lib.endswith(".lib"))
9464         LinkLibArg = Args.MakeArgString(Lib);
9465       else
9466         LinkLibArg = Args.MakeArgString(Lib + ".lib");
9467       CmdArgs.push_back(LinkLibArg);
9468       continue;
9469     }
9470
9471     // Otherwise, this is some other kind of linker input option like -Wl, -z,
9472     // or -L. Render it, even if MSVC doesn't understand it.
9473     A.renderAsInput(Args, CmdArgs);
9474   }
9475
9476   // We need to special case some linker paths.  In the case of lld, we need to
9477   // translate 'lld' into 'lld-link', and in the case of the regular msvc
9478   // linker, we need to use a special search algorithm.
9479   llvm::SmallString<128> linkPath;
9480   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9481   if (Linker.equals_lower("lld"))
9482     Linker = "lld-link";
9483
9484   if (Linker.equals_lower("link")) {
9485     // If we're using the MSVC linker, it's not sufficient to just use link
9486     // from the program PATH, because other environments like GnuWin32 install
9487     // their own link.exe which may come first.
9488     linkPath = FindVisualStudioExecutable(TC, "link.exe",
9489                                           C.getDriver().getClangProgramPath());
9490   } else {
9491     linkPath = Linker;
9492     llvm::sys::path::replace_extension(linkPath, "exe");
9493     linkPath = TC.GetProgramPath(linkPath.c_str());
9494   }
9495
9496   const char *Exec = Args.MakeArgString(linkPath);
9497   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9498 }
9499
9500 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9501                                           const InputInfo &Output,
9502                                           const InputInfoList &Inputs,
9503                                           const ArgList &Args,
9504                                           const char *LinkingOutput) const {
9505   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9506 }
9507
9508 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9509     Compilation &C, const JobAction &JA, const InputInfo &Output,
9510     const InputInfoList &Inputs, const ArgList &Args,
9511     const char *LinkingOutput) const {
9512   ArgStringList CmdArgs;
9513   CmdArgs.push_back("/nologo");
9514   CmdArgs.push_back("/c");  // Compile only.
9515   CmdArgs.push_back("/W0"); // No warnings.
9516
9517   // The goal is to be able to invoke this tool correctly based on
9518   // any flag accepted by clang-cl.
9519
9520   // These are spelled the same way in clang and cl.exe,.
9521   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9522
9523   // Optimization level.
9524   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9525     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9526                                                                       : "/Oi-");
9527   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9528     if (A->getOption().getID() == options::OPT_O0) {
9529       CmdArgs.push_back("/Od");
9530     } else {
9531       CmdArgs.push_back("/Og");
9532
9533       StringRef OptLevel = A->getValue();
9534       if (OptLevel == "s" || OptLevel == "z")
9535         CmdArgs.push_back("/Os");
9536       else
9537         CmdArgs.push_back("/Ot");
9538
9539       CmdArgs.push_back("/Ob2");
9540     }
9541   }
9542   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9543                                options::OPT_fno_omit_frame_pointer))
9544     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9545                           ? "/Oy"
9546                           : "/Oy-");
9547   if (!Args.hasArg(options::OPT_fwritable_strings))
9548     CmdArgs.push_back("/GF");
9549
9550   // Flags for which clang-cl has an alias.
9551   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9552
9553   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9554                    /*default=*/false))
9555     CmdArgs.push_back("/GR-");
9556   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9557                                options::OPT_fno_function_sections))
9558     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9559                           ? "/Gy"
9560                           : "/Gy-");
9561   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9562                                options::OPT_fno_data_sections))
9563     CmdArgs.push_back(
9564         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9565   if (Args.hasArg(options::OPT_fsyntax_only))
9566     CmdArgs.push_back("/Zs");
9567   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9568                   options::OPT__SLASH_Z7))
9569     CmdArgs.push_back("/Z7");
9570
9571   std::vector<std::string> Includes =
9572       Args.getAllArgValues(options::OPT_include);
9573   for (const auto &Include : Includes)
9574     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9575
9576   // Flags that can simply be passed through.
9577   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9578   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9579   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9580   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9581
9582   // The order of these flags is relevant, so pick the last one.
9583   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9584                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9585     A->render(Args, CmdArgs);
9586
9587   // Input filename.
9588   assert(Inputs.size() == 1);
9589   const InputInfo &II = Inputs[0];
9590   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9591   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9592   if (II.isFilename())
9593     CmdArgs.push_back(II.getFilename());
9594   else
9595     II.getInputArg().renderAsInput(Args, CmdArgs);
9596
9597   // Output filename.
9598   assert(Output.getType() == types::TY_Object);
9599   const char *Fo =
9600       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9601   CmdArgs.push_back(Fo);
9602
9603   const Driver &D = getToolChain().getDriver();
9604   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9605                                                 D.getClangProgramPath());
9606   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9607                                     CmdArgs, Inputs);
9608 }
9609
9610 /// MinGW Tools
9611 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9612                                     const InputInfo &Output,
9613                                     const InputInfoList &Inputs,
9614                                     const ArgList &Args,
9615                                     const char *LinkingOutput) const {
9616   claimNoWarnArgs(Args);
9617   ArgStringList CmdArgs;
9618
9619   if (getToolChain().getArch() == llvm::Triple::x86) {
9620     CmdArgs.push_back("--32");
9621   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9622     CmdArgs.push_back("--64");
9623   }
9624
9625   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9626
9627   CmdArgs.push_back("-o");
9628   CmdArgs.push_back(Output.getFilename());
9629
9630   for (const auto &II : Inputs)
9631     CmdArgs.push_back(II.getFilename());
9632
9633   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9634   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9635
9636   if (Args.hasArg(options::OPT_gsplit_dwarf))
9637     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9638                    SplitDebugName(Args, Inputs[0]));
9639 }
9640
9641 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9642                               ArgStringList &CmdArgs) const {
9643   if (Args.hasArg(options::OPT_mthreads))
9644     CmdArgs.push_back("-lmingwthrd");
9645   CmdArgs.push_back("-lmingw32");
9646
9647   // Make use of compiler-rt if --rtlib option is used
9648   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9649   if (RLT == ToolChain::RLT_Libgcc) {
9650     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9651                   Args.hasArg(options::OPT_static);
9652     bool Shared = Args.hasArg(options::OPT_shared);
9653     bool CXX = getToolChain().getDriver().CCCIsCXX();
9654
9655     if (Static || (!CXX && !Shared)) {
9656       CmdArgs.push_back("-lgcc");
9657       CmdArgs.push_back("-lgcc_eh");
9658     } else {
9659       CmdArgs.push_back("-lgcc_s");
9660       CmdArgs.push_back("-lgcc");
9661     }
9662   } else {
9663     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9664   }
9665
9666   CmdArgs.push_back("-lmoldname");
9667   CmdArgs.push_back("-lmingwex");
9668   CmdArgs.push_back("-lmsvcrt");
9669 }
9670
9671 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9672                                  const InputInfo &Output,
9673                                  const InputInfoList &Inputs,
9674                                  const ArgList &Args,
9675                                  const char *LinkingOutput) const {
9676   const ToolChain &TC = getToolChain();
9677   const Driver &D = TC.getDriver();
9678   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9679
9680   ArgStringList CmdArgs;
9681
9682   // Silence warning for "clang -g foo.o -o foo"
9683   Args.ClaimAllArgs(options::OPT_g_Group);
9684   // and "clang -emit-llvm foo.o -o foo"
9685   Args.ClaimAllArgs(options::OPT_emit_llvm);
9686   // and for "clang -w foo.o -o foo". Other warning options are already
9687   // handled somewhere else.
9688   Args.ClaimAllArgs(options::OPT_w);
9689
9690   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9691   if (LinkerName.equals_lower("lld")) {
9692     CmdArgs.push_back("-flavor");
9693     CmdArgs.push_back("gnu");
9694   } else if (!LinkerName.equals_lower("ld")) {
9695     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9696   }
9697
9698   if (!D.SysRoot.empty())
9699     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9700
9701   if (Args.hasArg(options::OPT_s))
9702     CmdArgs.push_back("-s");
9703
9704   CmdArgs.push_back("-m");
9705   if (TC.getArch() == llvm::Triple::x86)
9706     CmdArgs.push_back("i386pe");
9707   if (TC.getArch() == llvm::Triple::x86_64)
9708     CmdArgs.push_back("i386pep");
9709   if (TC.getArch() == llvm::Triple::arm)
9710     CmdArgs.push_back("thumb2pe");
9711
9712   if (Args.hasArg(options::OPT_mwindows)) {
9713     CmdArgs.push_back("--subsystem");
9714     CmdArgs.push_back("windows");
9715   } else if (Args.hasArg(options::OPT_mconsole)) {
9716     CmdArgs.push_back("--subsystem");
9717     CmdArgs.push_back("console");
9718   }
9719
9720   if (Args.hasArg(options::OPT_static))
9721     CmdArgs.push_back("-Bstatic");
9722   else {
9723     if (Args.hasArg(options::OPT_mdll))
9724       CmdArgs.push_back("--dll");
9725     else if (Args.hasArg(options::OPT_shared))
9726       CmdArgs.push_back("--shared");
9727     CmdArgs.push_back("-Bdynamic");
9728     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9729       CmdArgs.push_back("-e");
9730       if (TC.getArch() == llvm::Triple::x86)
9731         CmdArgs.push_back("_DllMainCRTStartup@12");
9732       else
9733         CmdArgs.push_back("DllMainCRTStartup");
9734       CmdArgs.push_back("--enable-auto-image-base");
9735     }
9736   }
9737
9738   CmdArgs.push_back("-o");
9739   CmdArgs.push_back(Output.getFilename());
9740
9741   Args.AddAllArgs(CmdArgs, options::OPT_e);
9742   // FIXME: add -N, -n flags
9743   Args.AddLastArg(CmdArgs, options::OPT_r);
9744   Args.AddLastArg(CmdArgs, options::OPT_s);
9745   Args.AddLastArg(CmdArgs, options::OPT_t);
9746   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9747   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9748
9749   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9750     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9751       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9752     } else {
9753       if (Args.hasArg(options::OPT_municode))
9754         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9755       else
9756         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9757     }
9758     if (Args.hasArg(options::OPT_pg))
9759       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9760     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9761   }
9762
9763   Args.AddAllArgs(CmdArgs, options::OPT_L);
9764   TC.AddFilePathLibArgs(Args, CmdArgs);
9765   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9766
9767   // TODO: Add ASan stuff here
9768
9769   // TODO: Add profile stuff here
9770
9771   if (D.CCCIsCXX() &&
9772       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9773     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9774                                !Args.hasArg(options::OPT_static);
9775     if (OnlyLibstdcxxStatic)
9776       CmdArgs.push_back("-Bstatic");
9777     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9778     if (OnlyLibstdcxxStatic)
9779       CmdArgs.push_back("-Bdynamic");
9780   }
9781
9782   if (!Args.hasArg(options::OPT_nostdlib)) {
9783     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9784       if (Args.hasArg(options::OPT_static))
9785         CmdArgs.push_back("--start-group");
9786
9787       if (Args.hasArg(options::OPT_fstack_protector) ||
9788           Args.hasArg(options::OPT_fstack_protector_strong) ||
9789           Args.hasArg(options::OPT_fstack_protector_all)) {
9790         CmdArgs.push_back("-lssp_nonshared");
9791         CmdArgs.push_back("-lssp");
9792       }
9793       if (Args.hasArg(options::OPT_fopenmp))
9794         CmdArgs.push_back("-lgomp");
9795
9796       AddLibGCC(Args, CmdArgs);
9797
9798       if (Args.hasArg(options::OPT_pg))
9799         CmdArgs.push_back("-lgmon");
9800
9801       if (Args.hasArg(options::OPT_pthread))
9802         CmdArgs.push_back("-lpthread");
9803
9804       // add system libraries
9805       if (Args.hasArg(options::OPT_mwindows)) {
9806         CmdArgs.push_back("-lgdi32");
9807         CmdArgs.push_back("-lcomdlg32");
9808       }
9809       CmdArgs.push_back("-ladvapi32");
9810       CmdArgs.push_back("-lshell32");
9811       CmdArgs.push_back("-luser32");
9812       CmdArgs.push_back("-lkernel32");
9813
9814       if (Args.hasArg(options::OPT_static))
9815         CmdArgs.push_back("--end-group");
9816       else if (!LinkerName.equals_lower("lld"))
9817         AddLibGCC(Args, CmdArgs);
9818     }
9819
9820     if (!Args.hasArg(options::OPT_nostartfiles)) {
9821       // Add crtfastmath.o if available and fast math is enabled.
9822       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9823
9824       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9825     }
9826   }
9827   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9828   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9829 }
9830
9831 /// XCore Tools
9832 // We pass assemble and link construction to the xcc tool.
9833
9834 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9835                                     const InputInfo &Output,
9836                                     const InputInfoList &Inputs,
9837                                     const ArgList &Args,
9838                                     const char *LinkingOutput) const {
9839   claimNoWarnArgs(Args);
9840   ArgStringList CmdArgs;
9841
9842   CmdArgs.push_back("-o");
9843   CmdArgs.push_back(Output.getFilename());
9844
9845   CmdArgs.push_back("-c");
9846
9847   if (Args.hasArg(options::OPT_v))
9848     CmdArgs.push_back("-v");
9849
9850   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9851     if (!A->getOption().matches(options::OPT_g0))
9852       CmdArgs.push_back("-g");
9853
9854   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9855                    false))
9856     CmdArgs.push_back("-fverbose-asm");
9857
9858   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9859
9860   for (const auto &II : Inputs)
9861     CmdArgs.push_back(II.getFilename());
9862
9863   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9864   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9865 }
9866
9867 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9868                                  const InputInfo &Output,
9869                                  const InputInfoList &Inputs,
9870                                  const ArgList &Args,
9871                                  const char *LinkingOutput) const {
9872   ArgStringList CmdArgs;
9873
9874   if (Output.isFilename()) {
9875     CmdArgs.push_back("-o");
9876     CmdArgs.push_back(Output.getFilename());
9877   } else {
9878     assert(Output.isNothing() && "Invalid output.");
9879   }
9880
9881   if (Args.hasArg(options::OPT_v))
9882     CmdArgs.push_back("-v");
9883
9884   // Pass -fexceptions through to the linker if it was present.
9885   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9886                    false))
9887     CmdArgs.push_back("-fexceptions");
9888
9889   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9890
9891   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9892   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9893 }
9894
9895 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9896                                            const InputInfo &Output,
9897                                            const InputInfoList &Inputs,
9898                                            const ArgList &Args,
9899                                            const char *LinkingOutput) const {
9900   claimNoWarnArgs(Args);
9901   const auto &TC =
9902       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9903   ArgStringList CmdArgs;
9904   const char *Exec;
9905
9906   switch (TC.getArch()) {
9907   default:
9908     llvm_unreachable("unsupported architecture");
9909   case llvm::Triple::arm:
9910   case llvm::Triple::thumb:
9911     break;
9912   case llvm::Triple::x86:
9913     CmdArgs.push_back("--32");
9914     break;
9915   case llvm::Triple::x86_64:
9916     CmdArgs.push_back("--64");
9917     break;
9918   }
9919
9920   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9921
9922   CmdArgs.push_back("-o");
9923   CmdArgs.push_back(Output.getFilename());
9924
9925   for (const auto &Input : Inputs)
9926     CmdArgs.push_back(Input.getFilename());
9927
9928   const std::string Assembler = TC.GetProgramPath("as");
9929   Exec = Args.MakeArgString(Assembler);
9930
9931   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9932 }
9933
9934 void CrossWindows::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   const auto &TC =
9940       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9941   const llvm::Triple &T = TC.getTriple();
9942   const Driver &D = TC.getDriver();
9943   SmallString<128> EntryPoint;
9944   ArgStringList CmdArgs;
9945   const char *Exec;
9946
9947   // Silence warning for "clang -g foo.o -o foo"
9948   Args.ClaimAllArgs(options::OPT_g_Group);
9949   // and "clang -emit-llvm foo.o -o foo"
9950   Args.ClaimAllArgs(options::OPT_emit_llvm);
9951   // and for "clang -w foo.o -o foo"
9952   Args.ClaimAllArgs(options::OPT_w);
9953   // Other warning options are already handled somewhere else.
9954
9955   if (!D.SysRoot.empty())
9956     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9957
9958   if (Args.hasArg(options::OPT_pie))
9959     CmdArgs.push_back("-pie");
9960   if (Args.hasArg(options::OPT_rdynamic))
9961     CmdArgs.push_back("-export-dynamic");
9962   if (Args.hasArg(options::OPT_s))
9963     CmdArgs.push_back("--strip-all");
9964
9965   CmdArgs.push_back("-m");
9966   switch (TC.getArch()) {
9967   default:
9968     llvm_unreachable("unsupported architecture");
9969   case llvm::Triple::arm:
9970   case llvm::Triple::thumb:
9971     // FIXME: this is incorrect for WinCE
9972     CmdArgs.push_back("thumb2pe");
9973     break;
9974   case llvm::Triple::x86:
9975     CmdArgs.push_back("i386pe");
9976     EntryPoint.append("_");
9977     break;
9978   case llvm::Triple::x86_64:
9979     CmdArgs.push_back("i386pep");
9980     break;
9981   }
9982
9983   if (Args.hasArg(options::OPT_shared)) {
9984     switch (T.getArch()) {
9985     default:
9986       llvm_unreachable("unsupported architecture");
9987     case llvm::Triple::arm:
9988     case llvm::Triple::thumb:
9989     case llvm::Triple::x86_64:
9990       EntryPoint.append("_DllMainCRTStartup");
9991       break;
9992     case llvm::Triple::x86:
9993       EntryPoint.append("_DllMainCRTStartup@12");
9994       break;
9995     }
9996
9997     CmdArgs.push_back("-shared");
9998     CmdArgs.push_back("-Bdynamic");
9999
10000     CmdArgs.push_back("--enable-auto-image-base");
10001
10002     CmdArgs.push_back("--entry");
10003     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10004   } else {
10005     EntryPoint.append("mainCRTStartup");
10006
10007     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10008                                                        : "-Bdynamic");
10009
10010     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10011       CmdArgs.push_back("--entry");
10012       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10013     }
10014
10015     // FIXME: handle subsystem
10016   }
10017
10018   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10019   CmdArgs.push_back("--allow-multiple-definition");
10020
10021   CmdArgs.push_back("-o");
10022   CmdArgs.push_back(Output.getFilename());
10023
10024   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10025     SmallString<261> ImpLib(Output.getFilename());
10026     llvm::sys::path::replace_extension(ImpLib, ".lib");
10027
10028     CmdArgs.push_back("--out-implib");
10029     CmdArgs.push_back(Args.MakeArgString(ImpLib));
10030   }
10031
10032   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10033     const std::string CRTPath(D.SysRoot + "/usr/lib/");
10034     const char *CRTBegin;
10035
10036     CRTBegin =
10037         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10038     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10039   }
10040
10041   Args.AddAllArgs(CmdArgs, options::OPT_L);
10042   TC.AddFilePathLibArgs(Args, CmdArgs);
10043   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10044
10045   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10046       !Args.hasArg(options::OPT_nodefaultlibs)) {
10047     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10048                      !Args.hasArg(options::OPT_static);
10049     if (StaticCXX)
10050       CmdArgs.push_back("-Bstatic");
10051     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10052     if (StaticCXX)
10053       CmdArgs.push_back("-Bdynamic");
10054   }
10055
10056   if (!Args.hasArg(options::OPT_nostdlib)) {
10057     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10058       // TODO handle /MT[d] /MD[d]
10059       CmdArgs.push_back("-lmsvcrt");
10060       AddRunTimeLibs(TC, D, CmdArgs, Args);
10061     }
10062   }
10063
10064   if (TC.getSanitizerArgs().needsAsanRt()) {
10065     // TODO handle /MT[d] /MD[d]
10066     if (Args.hasArg(options::OPT_shared)) {
10067       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10068     } else {
10069       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10070         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10071         // Make sure the dynamic runtime thunk is not optimized out at link time
10072         // to ensure proper SEH handling.
10073         CmdArgs.push_back(Args.MakeArgString("--undefined"));
10074         CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10075                                                  ? "___asan_seh_interceptor"
10076                                                  : "__asan_seh_interceptor"));
10077     }
10078   }
10079
10080   Exec = Args.MakeArgString(TC.GetLinkerPath());
10081
10082   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10083 }
10084
10085 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10086                                           const InputInfo &Output,
10087                                           const InputInfoList &Inputs,
10088                                           const ArgList &Args,
10089                                           const char *LinkingOutput) const {
10090   ArgStringList CmdArgs;
10091   assert(Inputs.size() == 1);
10092   const InputInfo &II = Inputs[0];
10093   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10094          II.getType() == types::TY_PP_CXX);
10095
10096   if (JA.getKind() == Action::PreprocessJobClass) {
10097     Args.ClaimAllArgs();
10098     CmdArgs.push_back("-E");
10099   } else {
10100     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10101     CmdArgs.push_back("-S");
10102     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10103   }
10104   CmdArgs.push_back("-mcpu=myriad2");
10105   CmdArgs.push_back("-DMYRIAD2");
10106
10107   // Append all -I, -iquote, -isystem paths, defines/undefines,
10108   // 'f' flags, optimize flags, and warning options.
10109   // These are spelled the same way in clang and moviCompile.
10110   Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10111                             options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10112                             options::OPT_f_Group, options::OPT_f_clang_Group,
10113                             options::OPT_g_Group, options::OPT_M_Group,
10114                             options::OPT_O_Group, options::OPT_W_Group});
10115
10116   // If we're producing a dependency file, and assembly is the final action,
10117   // then the name of the target in the dependency file should be the '.o'
10118   // file, not the '.s' file produced by this step. For example, instead of
10119   //  /tmp/mumble.s: mumble.c .../someheader.h
10120   // the filename on the lefthand side should be "mumble.o"
10121   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10122       C.getActions().size() == 1 &&
10123       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10124     Arg *A = Args.getLastArg(options::OPT_o);
10125     if (A) {
10126       CmdArgs.push_back("-MT");
10127       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10128     }
10129   }
10130
10131   CmdArgs.push_back(II.getFilename());
10132   CmdArgs.push_back("-o");
10133   CmdArgs.push_back(Output.getFilename());
10134
10135   std::string Exec =
10136       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10137   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10138                                           CmdArgs, Inputs));
10139 }
10140
10141 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10142                                            const InputInfo &Output,
10143                                            const InputInfoList &Inputs,
10144                                            const ArgList &Args,
10145                                            const char *LinkingOutput) const {
10146   ArgStringList CmdArgs;
10147
10148   assert(Inputs.size() == 1);
10149   const InputInfo &II = Inputs[0];
10150   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10151   assert(Output.getType() == types::TY_Object);
10152
10153   CmdArgs.push_back("-no6thSlotCompression");
10154   CmdArgs.push_back("-cv:myriad2"); // Chip Version
10155   CmdArgs.push_back("-noSPrefixing");
10156   CmdArgs.push_back("-a"); // Mystery option.
10157   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10158   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10159     A->claim();
10160     CmdArgs.push_back(
10161         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10162   }
10163   CmdArgs.push_back("-elf"); // Output format.
10164   CmdArgs.push_back(II.getFilename());
10165   CmdArgs.push_back(
10166       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10167
10168   std::string Exec =
10169       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10170   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10171                                           CmdArgs, Inputs));
10172 }
10173
10174 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10175                                          const InputInfo &Output,
10176                                          const InputInfoList &Inputs,
10177                                          const ArgList &Args,
10178                                          const char *LinkingOutput) const {
10179   const auto &TC =
10180       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10181   const llvm::Triple &T = TC.getTriple();
10182   ArgStringList CmdArgs;
10183   bool UseStartfiles =
10184       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10185   bool UseDefaultLibs =
10186       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10187
10188   if (T.getArch() == llvm::Triple::sparc)
10189     CmdArgs.push_back("-EB");
10190   else // SHAVE assumes little-endian, and sparcel is expressly so.
10191     CmdArgs.push_back("-EL");
10192
10193   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10194   // but we never pass through a --sysroot option and various other bits.
10195   // For example, there are no sanitizers (yet) nor gold linker.
10196
10197   // Eat some arguments that may be present but have no effect.
10198   Args.ClaimAllArgs(options::OPT_g_Group);
10199   Args.ClaimAllArgs(options::OPT_w);
10200   Args.ClaimAllArgs(options::OPT_static_libgcc);
10201
10202   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10203     CmdArgs.push_back("-s");
10204
10205   CmdArgs.push_back("-o");
10206   CmdArgs.push_back(Output.getFilename());
10207
10208   if (UseStartfiles) {
10209     // If you want startfiles, it means you want the builtin crti and crtbegin,
10210     // but not crt0. Myriad link commands provide their own crt0.o as needed.
10211     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10212     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10213   }
10214
10215   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10216                             options::OPT_e, options::OPT_s, options::OPT_t,
10217                             options::OPT_Z_Flag, options::OPT_r});
10218
10219   TC.AddFilePathLibArgs(Args, CmdArgs);
10220
10221   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10222
10223   if (UseDefaultLibs) {
10224     if (C.getDriver().CCCIsCXX())
10225       CmdArgs.push_back("-lstdc++");
10226     if (T.getOS() == llvm::Triple::RTEMS) {
10227       CmdArgs.push_back("--start-group");
10228       CmdArgs.push_back("-lc");
10229       // You must provide your own "-L" option to enable finding these.
10230       CmdArgs.push_back("-lrtemscpu");
10231       CmdArgs.push_back("-lrtemsbsp");
10232       CmdArgs.push_back("--end-group");
10233     } else {
10234       CmdArgs.push_back("-lc");
10235     }
10236     CmdArgs.push_back("-lgcc");
10237   }
10238   if (UseStartfiles) {
10239     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10240     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10241   }
10242
10243   std::string Exec =
10244       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10245   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10246                                           CmdArgs, Inputs));
10247 }
10248
10249 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10250                                     const InputInfo &Output,
10251                                     const InputInfoList &Inputs,
10252                                     const ArgList &Args,
10253                                     const char *LinkingOutput) const {
10254   claimNoWarnArgs(Args);
10255   ArgStringList CmdArgs;
10256
10257   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10258
10259   CmdArgs.push_back("-o");
10260   CmdArgs.push_back(Output.getFilename());
10261
10262   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10263   const InputInfo &Input = Inputs[0];
10264   assert(Input.isFilename() && "Invalid input.");
10265   CmdArgs.push_back(Input.getFilename());
10266
10267   const char *Exec =
10268       Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10269   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10270 }
10271
10272 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10273   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10274   if (SanArgs.needsUbsanRt()) {
10275     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10276   }
10277   if (SanArgs.needsAsanRt()) {
10278     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10279   }
10280 }
10281
10282 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10283                                 const JobAction &JA, const InputInfo &Output,
10284                                 const InputInfoList &Inputs,
10285                                 const ArgList &Args,
10286                                 const char *LinkingOutput) {
10287   const toolchains::FreeBSD &ToolChain =
10288       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10289   const Driver &D = ToolChain.getDriver();
10290   ArgStringList CmdArgs;
10291
10292   // Silence warning for "clang -g foo.o -o foo"
10293   Args.ClaimAllArgs(options::OPT_g_Group);
10294   // and "clang -emit-llvm foo.o -o foo"
10295   Args.ClaimAllArgs(options::OPT_emit_llvm);
10296   // and for "clang -w foo.o -o foo". Other warning options are already
10297   // handled somewhere else.
10298   Args.ClaimAllArgs(options::OPT_w);
10299
10300   if (!D.SysRoot.empty())
10301     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10302
10303   if (Args.hasArg(options::OPT_pie))
10304     CmdArgs.push_back("-pie");
10305
10306   if (Args.hasArg(options::OPT_rdynamic))
10307     CmdArgs.push_back("-export-dynamic");
10308   if (Args.hasArg(options::OPT_shared))
10309     CmdArgs.push_back("--oformat=so");
10310
10311   if (Output.isFilename()) {
10312     CmdArgs.push_back("-o");
10313     CmdArgs.push_back(Output.getFilename());
10314   } else {
10315     assert(Output.isNothing() && "Invalid output.");
10316   }
10317
10318   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10319
10320   Args.AddAllArgs(CmdArgs, options::OPT_L);
10321   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10322   Args.AddAllArgs(CmdArgs, options::OPT_e);
10323   Args.AddAllArgs(CmdArgs, options::OPT_s);
10324   Args.AddAllArgs(CmdArgs, options::OPT_t);
10325   Args.AddAllArgs(CmdArgs, options::OPT_r);
10326
10327   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10328     CmdArgs.push_back("--no-demangle");
10329
10330   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10331
10332   if (Args.hasArg(options::OPT_pthread)) {
10333     CmdArgs.push_back("-lpthread");
10334   }
10335
10336   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10337
10338   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10339 }
10340
10341 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10342                                  const JobAction &JA, const InputInfo &Output,
10343                                  const InputInfoList &Inputs,
10344                                  const ArgList &Args,
10345                                  const char *LinkingOutput) {
10346   const toolchains::FreeBSD &ToolChain =
10347       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10348   const Driver &D = ToolChain.getDriver();
10349   ArgStringList CmdArgs;
10350
10351   // Silence warning for "clang -g foo.o -o foo"
10352   Args.ClaimAllArgs(options::OPT_g_Group);
10353   // and "clang -emit-llvm foo.o -o foo"
10354   Args.ClaimAllArgs(options::OPT_emit_llvm);
10355   // and for "clang -w foo.o -o foo". Other warning options are already
10356   // handled somewhere else.
10357   Args.ClaimAllArgs(options::OPT_w);
10358
10359   if (!D.SysRoot.empty())
10360     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10361
10362   if (Args.hasArg(options::OPT_pie))
10363     CmdArgs.push_back("-pie");
10364
10365   if (Args.hasArg(options::OPT_static)) {
10366     CmdArgs.push_back("-Bstatic");
10367   } else {
10368     if (Args.hasArg(options::OPT_rdynamic))
10369       CmdArgs.push_back("-export-dynamic");
10370     CmdArgs.push_back("--eh-frame-hdr");
10371     if (Args.hasArg(options::OPT_shared)) {
10372       CmdArgs.push_back("-Bshareable");
10373     } else {
10374       CmdArgs.push_back("-dynamic-linker");
10375       CmdArgs.push_back("/libexec/ld-elf.so.1");
10376     }
10377     CmdArgs.push_back("--enable-new-dtags");
10378   }
10379
10380   if (Output.isFilename()) {
10381     CmdArgs.push_back("-o");
10382     CmdArgs.push_back(Output.getFilename());
10383   } else {
10384     assert(Output.isNothing() && "Invalid output.");
10385   }
10386
10387   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10388
10389   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10390     const char *crt1 = nullptr;
10391     if (!Args.hasArg(options::OPT_shared)) {
10392       if (Args.hasArg(options::OPT_pg))
10393         crt1 = "gcrt1.o";
10394       else if (Args.hasArg(options::OPT_pie))
10395         crt1 = "Scrt1.o";
10396       else
10397         crt1 = "crt1.o";
10398     }
10399     if (crt1)
10400       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10401
10402     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10403
10404     const char *crtbegin = nullptr;
10405     if (Args.hasArg(options::OPT_static))
10406       crtbegin = "crtbeginT.o";
10407     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10408       crtbegin = "crtbeginS.o";
10409     else
10410       crtbegin = "crtbegin.o";
10411
10412     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10413   }
10414
10415   Args.AddAllArgs(CmdArgs, options::OPT_L);
10416   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10417   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10418   Args.AddAllArgs(CmdArgs, options::OPT_e);
10419   Args.AddAllArgs(CmdArgs, options::OPT_s);
10420   Args.AddAllArgs(CmdArgs, options::OPT_t);
10421   Args.AddAllArgs(CmdArgs, options::OPT_r);
10422
10423   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10424     CmdArgs.push_back("--no-demangle");
10425
10426   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10427
10428   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10429     // For PS4, we always want to pass libm, libstdc++ and libkernel
10430     // libraries for both C and C++ compilations.
10431     CmdArgs.push_back("-lkernel");
10432     if (D.CCCIsCXX()) {
10433       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10434       if (Args.hasArg(options::OPT_pg))
10435         CmdArgs.push_back("-lm_p");
10436       else
10437         CmdArgs.push_back("-lm");
10438     }
10439     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10440     // the default system libraries. Just mimic this for now.
10441     if (Args.hasArg(options::OPT_pg))
10442       CmdArgs.push_back("-lgcc_p");
10443     else
10444       CmdArgs.push_back("-lcompiler_rt");
10445     if (Args.hasArg(options::OPT_static)) {
10446       CmdArgs.push_back("-lstdc++");
10447     } else if (Args.hasArg(options::OPT_pg)) {
10448       CmdArgs.push_back("-lgcc_eh_p");
10449     } else {
10450       CmdArgs.push_back("--as-needed");
10451       CmdArgs.push_back("-lstdc++");
10452       CmdArgs.push_back("--no-as-needed");
10453     }
10454
10455     if (Args.hasArg(options::OPT_pthread)) {
10456       if (Args.hasArg(options::OPT_pg))
10457         CmdArgs.push_back("-lpthread_p");
10458       else
10459         CmdArgs.push_back("-lpthread");
10460     }
10461
10462     if (Args.hasArg(options::OPT_pg)) {
10463       if (Args.hasArg(options::OPT_shared))
10464         CmdArgs.push_back("-lc");
10465       else {
10466         if (Args.hasArg(options::OPT_static)) {
10467           CmdArgs.push_back("--start-group");
10468           CmdArgs.push_back("-lc_p");
10469           CmdArgs.push_back("-lpthread_p");
10470           CmdArgs.push_back("--end-group");
10471         } else {
10472           CmdArgs.push_back("-lc_p");
10473         }
10474       }
10475       CmdArgs.push_back("-lgcc_p");
10476     } else {
10477       if (Args.hasArg(options::OPT_static)) {
10478         CmdArgs.push_back("--start-group");
10479         CmdArgs.push_back("-lc");
10480         CmdArgs.push_back("-lpthread");
10481         CmdArgs.push_back("--end-group");
10482       } else {
10483         CmdArgs.push_back("-lc");
10484       }
10485       CmdArgs.push_back("-lcompiler_rt");
10486     }
10487
10488     if (Args.hasArg(options::OPT_static)) {
10489       CmdArgs.push_back("-lstdc++");
10490     } else if (Args.hasArg(options::OPT_pg)) {
10491       CmdArgs.push_back("-lgcc_eh_p");
10492     } else {
10493       CmdArgs.push_back("--as-needed");
10494       CmdArgs.push_back("-lstdc++");
10495       CmdArgs.push_back("--no-as-needed");
10496     }
10497   }
10498
10499   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10500     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10501       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10502     else
10503       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10504     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10505   }
10506
10507   const char *Exec =
10508 #ifdef LLVM_ON_WIN32
10509       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10510 #else
10511       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10512 #endif
10513
10514   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10515 }
10516
10517 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10518                                 const InputInfo &Output,
10519                                 const InputInfoList &Inputs,
10520                                 const ArgList &Args,
10521                                 const char *LinkingOutput) const {
10522   const toolchains::FreeBSD &ToolChain =
10523       static_cast<const toolchains::FreeBSD &>(getToolChain());
10524   const Driver &D = ToolChain.getDriver();
10525   bool PS4Linker;
10526   StringRef LinkerOptName;
10527   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10528     LinkerOptName = A->getValue();
10529     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10530       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10531   }
10532
10533   if (LinkerOptName == "gold")
10534     PS4Linker = false;
10535   else if (LinkerOptName == "ps4")
10536     PS4Linker = true;
10537   else
10538     PS4Linker = !Args.hasArg(options::OPT_shared);
10539
10540   if (PS4Linker)
10541     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10542   else
10543     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10544 }