]> granicus.if.org Git - clang/blob - lib/Driver/Tools.cpp
LTO via the gold plugin needs to be told about debugger tuning.
[clang] / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
45
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56                                       std::vector<const char *> &Features,
57                                       OptSpecifier Group) {
58   for (const Arg *A : Args.filtered(Group)) {
59     StringRef Name = A->getOption().getName();
60     A->claim();
61
62     // Skip over "-m".
63     assert(Name.startswith("m") && "Invalid feature name.");
64     Name = Name.substr(1);
65
66     bool IsNegative = Name.startswith("no-");
67     if (IsNegative)
68       Name = Name.substr(3);
69     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
70   }
71 }
72
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74                                          const llvm::Triple &Triple) {
75   if (Triple.getArch() == llvm::Triple::sparcv9) {
76     return llvm::StringSwitch<const char *>(Name)
77           .Case("niagara", "-Av9b")
78           .Case("niagara2", "-Av9b")
79           .Case("niagara3", "-Av9d")
80           .Case("niagara4", "-Av9d")
81           .Default("-Av9");
82   } else {
83     return llvm::StringSwitch<const char *>(Name)
84           .Case("v8", "-Av8")
85           .Case("supersparc", "-Av8")
86           .Case("sparclite", "-Asparclite")
87           .Case("f934", "-Asparclite")
88           .Case("hypersparc", "-Av8")
89           .Case("sparclite86x", "-Asparclite")
90           .Case("sparclet", "-Asparclet")
91           .Case("tsc701", "-Asparclet")
92           .Case("v9", "-Av8plus")
93           .Case("ultrasparc", "-Av8plus")
94           .Case("ultrasparc3", "-Av8plus")
95           .Case("niagara", "-Av8plusb")
96           .Case("niagara2", "-Av8plusb")
97           .Case("niagara3", "-Av8plusd")
98           .Case("niagara4", "-Av8plusd")
99           .Default("-Av8");
100   }
101 }
102
103 /// CheckPreprocessingOptions - Perform some validation of preprocessing
104 /// arguments that is shared with gcc.
105 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
106   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
107     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
108         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
109       D.Diag(diag::err_drv_argument_only_allowed_with)
110           << A->getBaseArg().getAsString(Args)
111           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
112     }
113   }
114 }
115
116 /// CheckCodeGenerationOptions - Perform some validation of code generation
117 /// arguments that is shared with gcc.
118 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
119   // In gcc, only ARM checks this, but it seems reasonable to check universally.
120   if (Args.hasArg(options::OPT_static))
121     if (const Arg *A =
122             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
123       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
124                                                       << "-static";
125 }
126
127 // Add backslashes to escape spaces and other backslashes.
128 // This is used for the space-separated argument list specified with
129 // the -dwarf-debug-flags option.
130 static void EscapeSpacesAndBackslashes(const char *Arg,
131                                        SmallVectorImpl<char> &Res) {
132   for (; *Arg; ++Arg) {
133     switch (*Arg) {
134     default:
135       break;
136     case ' ':
137     case '\\':
138       Res.push_back('\\');
139       break;
140     }
141     Res.push_back(*Arg);
142   }
143 }
144
145 // Quote target names for inclusion in GNU Make dependency files.
146 // Only the characters '$', '#', ' ', '\t' are quoted.
147 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
148   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
149     switch (Target[i]) {
150     case ' ':
151     case '\t':
152       // Escape the preceding backslashes
153       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
154         Res.push_back('\\');
155
156       // Escape the space/tab
157       Res.push_back('\\');
158       break;
159     case '$':
160       Res.push_back('$');
161       break;
162     case '#':
163       Res.push_back('\\');
164       break;
165     default:
166       break;
167     }
168
169     Res.push_back(Target[i]);
170   }
171 }
172
173 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
174                              const char *ArgName, const char *EnvVar) {
175   const char *DirList = ::getenv(EnvVar);
176   bool CombinedArg = false;
177
178   if (!DirList)
179     return; // Nothing to do.
180
181   StringRef Name(ArgName);
182   if (Name.equals("-I") || Name.equals("-L"))
183     CombinedArg = true;
184
185   StringRef Dirs(DirList);
186   if (Dirs.empty()) // Empty string should not add '.'.
187     return;
188
189   StringRef::size_type Delim;
190   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
191     if (Delim == 0) { // Leading colon.
192       if (CombinedArg) {
193         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
194       } else {
195         CmdArgs.push_back(ArgName);
196         CmdArgs.push_back(".");
197       }
198     } else {
199       if (CombinedArg) {
200         CmdArgs.push_back(
201             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
202       } else {
203         CmdArgs.push_back(ArgName);
204         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
205       }
206     }
207     Dirs = Dirs.substr(Delim + 1);
208   }
209
210   if (Dirs.empty()) { // Trailing colon.
211     if (CombinedArg) {
212       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
213     } else {
214       CmdArgs.push_back(ArgName);
215       CmdArgs.push_back(".");
216     }
217   } else { // Add the last path.
218     if (CombinedArg) {
219       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
220     } else {
221       CmdArgs.push_back(ArgName);
222       CmdArgs.push_back(Args.MakeArgString(Dirs));
223     }
224   }
225 }
226
227 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
228                             const ArgList &Args, ArgStringList &CmdArgs) {
229   const Driver &D = TC.getDriver();
230
231   // Add extra linker input arguments which are not treated as inputs
232   // (constructed via -Xarch_).
233   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
234
235   for (const auto &II : Inputs) {
236     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
237       // Don't try to pass LLVM inputs unless we have native support.
238       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
239
240     // Add filenames immediately.
241     if (II.isFilename()) {
242       CmdArgs.push_back(II.getFilename());
243       continue;
244     }
245
246     // Otherwise, this is a linker input argument.
247     const Arg &A = II.getInputArg();
248
249     // Handle reserved library options.
250     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
251       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
252     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
253       TC.AddCCKextLibArgs(Args, CmdArgs);
254     else if (A.getOption().matches(options::OPT_z)) {
255       // Pass -z prefix for gcc linker compatibility.
256       A.claim();
257       A.render(Args, CmdArgs);
258     } else {
259       A.renderAsInput(Args, CmdArgs);
260     }
261   }
262
263   // LIBRARY_PATH - included following the user specified library paths.
264   //                and only supported on native toolchains.
265   if (!TC.isCrossCompiling())
266     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
267 }
268
269 /// \brief Determine whether Objective-C automated reference counting is
270 /// enabled.
271 static bool isObjCAutoRefCount(const ArgList &Args) {
272   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
273 }
274
275 /// \brief Determine whether we are linking the ObjC runtime.
276 static bool isObjCRuntimeLinked(const ArgList &Args) {
277   if (isObjCAutoRefCount(Args)) {
278     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
279     return true;
280   }
281   return Args.hasArg(options::OPT_fobjc_link_runtime);
282 }
283
284 static bool forwardToGCC(const Option &O) {
285   // Don't forward inputs from the original command line.  They are added from
286   // InputInfoList.
287   return O.getKind() != Option::InputClass &&
288          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
289 }
290
291 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
292                                     const Driver &D, const ArgList &Args,
293                                     ArgStringList &CmdArgs,
294                                     const InputInfo &Output,
295                                     const InputInfoList &Inputs,
296                                     const ToolChain *AuxToolChain) const {
297   Arg *A;
298
299   CheckPreprocessingOptions(D, Args);
300
301   Args.AddLastArg(CmdArgs, options::OPT_C);
302   Args.AddLastArg(CmdArgs, options::OPT_CC);
303
304   // Handle dependency file generation.
305   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
306       (A = Args.getLastArg(options::OPT_MD)) ||
307       (A = Args.getLastArg(options::OPT_MMD))) {
308     // Determine the output location.
309     const char *DepFile;
310     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
311       DepFile = MF->getValue();
312       C.addFailureResultFile(DepFile, &JA);
313     } else if (Output.getType() == types::TY_Dependencies) {
314       DepFile = Output.getFilename();
315     } else if (A->getOption().matches(options::OPT_M) ||
316                A->getOption().matches(options::OPT_MM)) {
317       DepFile = "-";
318     } else {
319       DepFile = getDependencyFileName(Args, Inputs);
320       C.addFailureResultFile(DepFile, &JA);
321     }
322     CmdArgs.push_back("-dependency-file");
323     CmdArgs.push_back(DepFile);
324
325     // Add a default target if one wasn't specified.
326     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
327       const char *DepTarget;
328
329       // If user provided -o, that is the dependency target, except
330       // when we are only generating a dependency file.
331       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
332       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
333         DepTarget = OutputOpt->getValue();
334       } else {
335         // Otherwise derive from the base input.
336         //
337         // FIXME: This should use the computed output file location.
338         SmallString<128> P(Inputs[0].getBaseInput());
339         llvm::sys::path::replace_extension(P, "o");
340         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
341       }
342
343       CmdArgs.push_back("-MT");
344       SmallString<128> Quoted;
345       QuoteTarget(DepTarget, Quoted);
346       CmdArgs.push_back(Args.MakeArgString(Quoted));
347     }
348
349     if (A->getOption().matches(options::OPT_M) ||
350         A->getOption().matches(options::OPT_MD))
351       CmdArgs.push_back("-sys-header-deps");
352     if ((isa<PrecompileJobAction>(JA) &&
353          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
354         Args.hasArg(options::OPT_fmodule_file_deps))
355       CmdArgs.push_back("-module-file-deps");
356   }
357
358   if (Args.hasArg(options::OPT_MG)) {
359     if (!A || A->getOption().matches(options::OPT_MD) ||
360         A->getOption().matches(options::OPT_MMD))
361       D.Diag(diag::err_drv_mg_requires_m_or_mm);
362     CmdArgs.push_back("-MG");
363   }
364
365   Args.AddLastArg(CmdArgs, options::OPT_MP);
366   Args.AddLastArg(CmdArgs, options::OPT_MV);
367
368   // Convert all -MQ <target> args to -MT <quoted target>
369   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
370     A->claim();
371
372     if (A->getOption().matches(options::OPT_MQ)) {
373       CmdArgs.push_back("-MT");
374       SmallString<128> Quoted;
375       QuoteTarget(A->getValue(), Quoted);
376       CmdArgs.push_back(Args.MakeArgString(Quoted));
377
378       // -MT flag - no change
379     } else {
380       A->render(Args, CmdArgs);
381     }
382   }
383
384   // Add -i* options, and automatically translate to
385   // -include-pch/-include-pth for transparent PCH support. It's
386   // wonky, but we include looking for .gch so we can support seamless
387   // replacement into a build system already set up to be generating
388   // .gch files.
389   bool RenderedImplicitInclude = false;
390   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
391     if (A->getOption().matches(options::OPT_include)) {
392       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
393       RenderedImplicitInclude = true;
394
395       // Use PCH if the user requested it.
396       bool UsePCH = D.CCCUsePCH;
397
398       bool FoundPTH = false;
399       bool FoundPCH = false;
400       SmallString<128> P(A->getValue());
401       // We want the files to have a name like foo.h.pch. Add a dummy extension
402       // so that replace_extension does the right thing.
403       P += ".dummy";
404       if (UsePCH) {
405         llvm::sys::path::replace_extension(P, "pch");
406         if (llvm::sys::fs::exists(P))
407           FoundPCH = true;
408       }
409
410       if (!FoundPCH) {
411         llvm::sys::path::replace_extension(P, "pth");
412         if (llvm::sys::fs::exists(P))
413           FoundPTH = true;
414       }
415
416       if (!FoundPCH && !FoundPTH) {
417         llvm::sys::path::replace_extension(P, "gch");
418         if (llvm::sys::fs::exists(P)) {
419           FoundPCH = UsePCH;
420           FoundPTH = !UsePCH;
421         }
422       }
423
424       if (FoundPCH || FoundPTH) {
425         if (IsFirstImplicitInclude) {
426           A->claim();
427           if (UsePCH)
428             CmdArgs.push_back("-include-pch");
429           else
430             CmdArgs.push_back("-include-pth");
431           CmdArgs.push_back(Args.MakeArgString(P));
432           continue;
433         } else {
434           // Ignore the PCH if not first on command line and emit warning.
435           D.Diag(diag::warn_drv_pch_not_first_include) << P
436                                                        << A->getAsString(Args);
437         }
438       }
439     }
440
441     // Not translated, render as usual.
442     A->claim();
443     A->render(Args, CmdArgs);
444   }
445
446   Args.AddAllArgs(CmdArgs,
447                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
448                    options::OPT_F, options::OPT_index_header_map});
449
450   // Add -Wp, and -Xpreprocessor if using the preprocessor.
451
452   // FIXME: There is a very unfortunate problem here, some troubled
453   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
454   // really support that we would have to parse and then translate
455   // those options. :(
456   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
457                        options::OPT_Xpreprocessor);
458
459   // -I- is a deprecated GCC feature, reject it.
460   if (Arg *A = Args.getLastArg(options::OPT_I_))
461     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
462
463   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
464   // -isysroot to the CC1 invocation.
465   StringRef sysroot = C.getSysRoot();
466   if (sysroot != "") {
467     if (!Args.hasArg(options::OPT_isysroot)) {
468       CmdArgs.push_back("-isysroot");
469       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
470     }
471   }
472
473   // Parse additional include paths from environment variables.
474   // FIXME: We should probably sink the logic for handling these from the
475   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
476   // CPATH - included following the user specified includes (but prior to
477   // builtin and standard includes).
478   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
479   // C_INCLUDE_PATH - system includes enabled when compiling C.
480   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
481   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
482   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
483   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
484   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
485   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
486   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
487
488   // Optional AuxToolChain indicates that we need to include headers
489   // for more than one target. If that's the case, add include paths
490   // from AuxToolChain right after include paths of the same kind for
491   // the current target.
492
493   // Add C++ include arguments, if needed.
494   if (types::isCXX(Inputs[0].getType())) {
495     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
496     if (AuxToolChain)
497       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
498   }
499
500   // Add system include arguments.
501   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
502   if (AuxToolChain)
503       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
504
505   // Add CUDA include arguments, if needed.
506   if (types::isCuda(Inputs[0].getType()))
507     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
508 }
509
510 // FIXME: Move to target hook.
511 static bool isSignedCharDefault(const llvm::Triple &Triple) {
512   switch (Triple.getArch()) {
513   default:
514     return true;
515
516   case llvm::Triple::aarch64:
517   case llvm::Triple::aarch64_be:
518   case llvm::Triple::arm:
519   case llvm::Triple::armeb:
520   case llvm::Triple::thumb:
521   case llvm::Triple::thumbeb:
522     if (Triple.isOSDarwin() || Triple.isOSWindows())
523       return true;
524     return false;
525
526   case llvm::Triple::ppc:
527   case llvm::Triple::ppc64:
528     if (Triple.isOSDarwin())
529       return true;
530     return false;
531
532   case llvm::Triple::hexagon:
533   case llvm::Triple::ppc64le:
534   case llvm::Triple::systemz:
535   case llvm::Triple::xcore:
536     return false;
537   }
538 }
539
540 static bool isNoCommonDefault(const llvm::Triple &Triple) {
541   switch (Triple.getArch()) {
542   default:
543     return false;
544
545   case llvm::Triple::xcore:
546   case llvm::Triple::wasm32:
547   case llvm::Triple::wasm64:
548     return true;
549   }
550 }
551
552 // ARM tools start.
553
554 // Get SubArch (vN).
555 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
556   llvm::StringRef Arch = Triple.getArchName();
557   return llvm::ARM::parseArchVersion(Arch);
558 }
559
560 // True if M-profile.
561 static bool isARMMProfile(const llvm::Triple &Triple) {
562   llvm::StringRef Arch = Triple.getArchName();
563   unsigned Profile = llvm::ARM::parseArchProfile(Arch);
564   return Profile == llvm::ARM::PK_M;
565 }
566
567 // Get Arch/CPU from args.
568 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
569                                   llvm::StringRef &CPU, bool FromAs = false) {
570   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
571     CPU = A->getValue();
572   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
573     Arch = A->getValue();
574   if (!FromAs)
575     return;
576
577   for (const Arg *A :
578        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
579     StringRef Value = A->getValue();
580     if (Value.startswith("-mcpu="))
581       CPU = Value.substr(6);
582     if (Value.startswith("-march="))
583       Arch = Value.substr(7);
584   }
585 }
586
587 // Handle -mhwdiv=.
588 // FIXME: Use ARMTargetParser.
589 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
590                                 const ArgList &Args, StringRef HWDiv,
591                                 std::vector<const char *> &Features) {
592   unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
593   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
594     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
595 }
596
597 // Handle -mfpu=.
598 static void getARMFPUFeatures(const Driver &D, const Arg *A,
599                               const ArgList &Args, StringRef FPU,
600                               std::vector<const char *> &Features) {
601   unsigned FPUID = llvm::ARM::parseFPU(FPU);
602   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
603     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
604 }
605
606 // Decode ARM features from string like +[no]featureA+[no]featureB+...
607 static bool DecodeARMFeatures(const Driver &D, StringRef text,
608                               std::vector<const char *> &Features) {
609   SmallVector<StringRef, 8> Split;
610   text.split(Split, StringRef("+"), -1, false);
611
612   for (StringRef Feature : Split) {
613     const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
614     if (FeatureName)
615       Features.push_back(FeatureName);
616     else
617       return false;
618   }
619   return true;
620 }
621
622 // Check if -march is valid by checking if it can be canonicalised and parsed.
623 // getARMArch is used here instead of just checking the -march value in order
624 // to handle -march=native correctly.
625 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
626                              llvm::StringRef ArchName,
627                              std::vector<const char *> &Features,
628                              const llvm::Triple &Triple) {
629   std::pair<StringRef, StringRef> Split = ArchName.split("+");
630
631   std::string MArch = arm::getARMArch(ArchName, Triple);
632   if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
633       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
634     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
635 }
636
637 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
638 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
639                             llvm::StringRef CPUName, llvm::StringRef ArchName,
640                             std::vector<const char *> &Features,
641                             const llvm::Triple &Triple) {
642   std::pair<StringRef, StringRef> Split = CPUName.split("+");
643
644   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
645   if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
646       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
647     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
648 }
649
650 static bool useAAPCSForMachO(const llvm::Triple &T) {
651   // The backend is hardwired to assume AAPCS for M-class processors, ensure
652   // the frontend matches that.
653   return T.getEnvironment() == llvm::Triple::EABI ||
654          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
655 }
656
657 // Select the float ABI as determined by -msoft-float, -mhard-float, and
658 // -mfloat-abi=.
659 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
660   const Driver &D = TC.getDriver();
661   const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
662   auto SubArch = getARMSubArchVersionNumber(Triple);
663   arm::FloatABI ABI = FloatABI::Invalid;
664   if (Arg *A =
665           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
666                           options::OPT_mfloat_abi_EQ)) {
667     if (A->getOption().matches(options::OPT_msoft_float)) {
668       ABI = FloatABI::Soft;
669     } else if (A->getOption().matches(options::OPT_mhard_float)) {
670       ABI = FloatABI::Hard;
671     } else {
672       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
673                 .Case("soft", FloatABI::Soft)
674                 .Case("softfp", FloatABI::SoftFP)
675                 .Case("hard", FloatABI::Hard)
676                 .Default(FloatABI::Invalid);
677       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
678         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
679         ABI = FloatABI::Soft;
680       }
681     }
682
683     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
684     // "apcs-gnu".
685     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
686         ABI == FloatABI::Hard) {
687       D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
688                                                        << Triple.getArchName();
689     }
690   }
691
692   // If unspecified, choose the default based on the platform.
693   if (ABI == FloatABI::Invalid) {
694     switch (Triple.getOS()) {
695     case llvm::Triple::Darwin:
696     case llvm::Triple::MacOSX:
697     case llvm::Triple::IOS:
698     case llvm::Triple::TvOS: {
699       // Darwin defaults to "softfp" for v6 and v7.
700       ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
701       break;
702     }
703     case llvm::Triple::WatchOS:
704       ABI = FloatABI::Hard;
705       break;
706
707     // FIXME: this is invalid for WindowsCE
708     case llvm::Triple::Win32:
709       ABI = FloatABI::Hard;
710       break;
711
712     case llvm::Triple::FreeBSD:
713       switch (Triple.getEnvironment()) {
714       case llvm::Triple::GNUEABIHF:
715         ABI = FloatABI::Hard;
716         break;
717       default:
718         // FreeBSD defaults to soft float
719         ABI = FloatABI::Soft;
720         break;
721       }
722       break;
723
724     default:
725       switch (Triple.getEnvironment()) {
726       case llvm::Triple::GNUEABIHF:
727       case llvm::Triple::EABIHF:
728         ABI = FloatABI::Hard;
729         break;
730       case llvm::Triple::GNUEABI:
731       case llvm::Triple::EABI:
732         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
733         ABI = FloatABI::SoftFP;
734         break;
735       case llvm::Triple::Android:
736         ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
737         break;
738       default:
739         // Assume "soft", but warn the user we are guessing.
740         ABI = FloatABI::Soft;
741         if (Triple.getOS() != llvm::Triple::UnknownOS ||
742             !Triple.isOSBinFormatMachO())
743           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
744         break;
745       }
746     }
747   }
748
749   assert(ABI != FloatABI::Invalid && "must select an ABI");
750   return ABI;
751 }
752
753 static void getARMTargetFeatures(const ToolChain &TC,
754                                  const llvm::Triple &Triple,
755                                  const ArgList &Args,
756                                  std::vector<const char *> &Features,
757                                  bool ForAS) {
758   const Driver &D = TC.getDriver();
759
760   bool KernelOrKext =
761       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
762   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
763   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
764   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
765
766   if (!ForAS) {
767     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
768     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
769     // stripped out by the ARM target. We should probably pass this a new
770     // -target-option, which is handled by the -cc1/-cc1as invocation.
771     //
772     // FIXME2:  For consistency, it would be ideal if we set up the target
773     // machine state the same when using the frontend or the assembler. We don't
774     // currently do that for the assembler, we pass the options directly to the
775     // backend and never even instantiate the frontend TargetInfo. If we did,
776     // and used its handleTargetFeatures hook, then we could ensure the
777     // assembler and the frontend behave the same.
778
779     // Use software floating point operations?
780     if (ABI == arm::FloatABI::Soft)
781       Features.push_back("+soft-float");
782
783     // Use software floating point argument passing?
784     if (ABI != arm::FloatABI::Hard)
785       Features.push_back("+soft-float-abi");
786   } else {
787     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
788     // to the assembler correctly.
789     for (const Arg *A :
790          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
791       StringRef Value = A->getValue();
792       if (Value.startswith("-mfpu=")) {
793         WaFPU = A;
794       } else if (Value.startswith("-mcpu=")) {
795         WaCPU = A;
796       } else if (Value.startswith("-mhwdiv=")) {
797         WaHDiv = A;
798       } else if (Value.startswith("-march=")) {
799         WaArch = A;
800       }
801     }
802   }
803
804   // Check -march. ClangAs gives preference to -Wa,-march=.
805   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
806   StringRef ArchName;
807   if (WaArch) {
808     if (ArchArg)
809       D.Diag(clang::diag::warn_drv_unused_argument)
810           << ArchArg->getAsString(Args);
811     ArchName = StringRef(WaArch->getValue()).substr(7);
812     checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
813     // FIXME: Set Arch.
814     D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
815   } else if (ArchArg) {
816     ArchName = ArchArg->getValue();
817     checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
818   }
819
820   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
821   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
822   StringRef CPUName;
823   if (WaCPU) {
824     if (CPUArg)
825       D.Diag(clang::diag::warn_drv_unused_argument)
826           << CPUArg->getAsString(Args);
827     CPUName = StringRef(WaCPU->getValue()).substr(6);
828     checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
829   } else if (CPUArg) {
830     CPUName = CPUArg->getValue();
831     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
832   }
833
834   // Add CPU features for generic CPUs
835   if (CPUName == "native") {
836     llvm::StringMap<bool> HostFeatures;
837     if (llvm::sys::getHostCPUFeatures(HostFeatures))
838       for (auto &F : HostFeatures)
839         Features.push_back(
840             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
841   }
842
843   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
844   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
845   if (WaFPU) {
846     if (FPUArg)
847       D.Diag(clang::diag::warn_drv_unused_argument)
848           << FPUArg->getAsString(Args);
849     getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
850                       Features);
851   } else if (FPUArg) {
852     getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
853   }
854
855   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
856   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
857   if (WaHDiv) {
858     if (HDivArg)
859       D.Diag(clang::diag::warn_drv_unused_argument)
860           << HDivArg->getAsString(Args);
861     getARMHWDivFeatures(D, WaHDiv, Args,
862                         StringRef(WaHDiv->getValue()).substr(8), Features);
863   } else if (HDivArg)
864     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
865
866   // Setting -msoft-float effectively disables NEON because of the GCC
867   // implementation, although the same isn't true of VFP or VFP3.
868   if (ABI == arm::FloatABI::Soft) {
869     Features.push_back("-neon");
870     // Also need to explicitly disable features which imply NEON.
871     Features.push_back("-crypto");
872   }
873
874   // En/disable crc code generation.
875   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
876     if (A->getOption().matches(options::OPT_mcrc))
877       Features.push_back("+crc");
878     else
879       Features.push_back("-crc");
880   }
881
882   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
883     Features.insert(Features.begin(), "+v8.1a");
884   }
885
886   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
887   // neither options are specified, see if we are compiling for kernel/kext and
888   // decide whether to pass "+long-calls" based on the OS and its version.
889   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
890                                options::OPT_mno_long_calls)) {
891     if (A->getOption().matches(options::OPT_mlong_calls))
892       Features.push_back("+long-calls");
893   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
894              !Triple.isWatchOS()) {
895       Features.push_back("+long-calls");
896   }
897
898   // Kernel code has more strict alignment requirements.
899   if (KernelOrKext)
900     Features.push_back("+strict-align");
901   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
902                                     options::OPT_munaligned_access)) {
903     if (A->getOption().matches(options::OPT_munaligned_access)) {
904       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
905       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
906         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
907     } else
908       Features.push_back("+strict-align");
909   } else {
910     // Assume pre-ARMv6 doesn't support unaligned accesses.
911     //
912     // ARMv6 may or may not support unaligned accesses depending on the
913     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
914     // Darwin and NetBSD targets support unaligned accesses, and others don't.
915     //
916     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
917     // which raises an alignment fault on unaligned accesses. Linux
918     // defaults this bit to 0 and handles it as a system-wide (not
919     // per-process) setting. It is therefore safe to assume that ARMv7+
920     // Linux targets support unaligned accesses. The same goes for NaCl.
921     //
922     // The above behavior is consistent with GCC.
923     int VersionNum = getARMSubArchVersionNumber(Triple);
924     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
925       if (VersionNum < 6 ||
926           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
927         Features.push_back("+strict-align");
928     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
929       if (VersionNum < 7)
930         Features.push_back("+strict-align");
931     } else
932       Features.push_back("+strict-align");
933   }
934
935   // llvm does not support reserving registers in general. There is support
936   // for reserving r9 on ARM though (defined as a platform-specific register
937   // in ARM EABI).
938   if (Args.hasArg(options::OPT_ffixed_r9))
939     Features.push_back("+reserve-r9");
940
941   // The kext linker doesn't know how to deal with movw/movt.
942   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
943     Features.push_back("+no-movt");
944 }
945
946 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
947                              ArgStringList &CmdArgs, bool KernelOrKext) const {
948   // Select the ABI to use.
949   // FIXME: Support -meabi.
950   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
951   const char *ABIName = nullptr;
952   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
953     ABIName = A->getValue();
954   } else if (Triple.isOSBinFormatMachO()) {
955     if (useAAPCSForMachO(Triple)) {
956       ABIName = "aapcs";
957     } else if (Triple.isWatchOS()) {
958       ABIName = "aapcs16";
959     } else {
960       ABIName = "apcs-gnu";
961     }
962   } else if (Triple.isOSWindows()) {
963     // FIXME: this is invalid for WindowsCE
964     ABIName = "aapcs";
965   } else {
966     // Select the default based on the platform.
967     switch (Triple.getEnvironment()) {
968     case llvm::Triple::Android:
969     case llvm::Triple::GNUEABI:
970     case llvm::Triple::GNUEABIHF:
971       ABIName = "aapcs-linux";
972       break;
973     case llvm::Triple::EABIHF:
974     case llvm::Triple::EABI:
975       ABIName = "aapcs";
976       break;
977     default:
978       if (Triple.getOS() == llvm::Triple::NetBSD)
979         ABIName = "apcs-gnu";
980       else
981         ABIName = "aapcs";
982       break;
983     }
984   }
985   CmdArgs.push_back("-target-abi");
986   CmdArgs.push_back(ABIName);
987
988   // Determine floating point ABI from the options & target defaults.
989   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
990   if (ABI == arm::FloatABI::Soft) {
991     // Floating point operations and argument passing are soft.
992     // FIXME: This changes CPP defines, we need -target-soft-float.
993     CmdArgs.push_back("-msoft-float");
994     CmdArgs.push_back("-mfloat-abi");
995     CmdArgs.push_back("soft");
996   } else if (ABI == arm::FloatABI::SoftFP) {
997     // Floating point operations are hard, but argument passing is soft.
998     CmdArgs.push_back("-mfloat-abi");
999     CmdArgs.push_back("soft");
1000   } else {
1001     // Floating point operations and argument passing are hard.
1002     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1003     CmdArgs.push_back("-mfloat-abi");
1004     CmdArgs.push_back("hard");
1005   }
1006
1007   // Forward the -mglobal-merge option for explicit control over the pass.
1008   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1009                                options::OPT_mno_global_merge)) {
1010     CmdArgs.push_back("-backend-option");
1011     if (A->getOption().matches(options::OPT_mno_global_merge))
1012       CmdArgs.push_back("-arm-global-merge=false");
1013     else
1014       CmdArgs.push_back("-arm-global-merge=true");
1015   }
1016
1017   if (!Args.hasFlag(options::OPT_mimplicit_float,
1018                     options::OPT_mno_implicit_float, true))
1019     CmdArgs.push_back("-no-implicit-float");
1020 }
1021 // ARM tools end.
1022
1023 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1024 /// targeting.
1025 static std::string getAArch64TargetCPU(const ArgList &Args) {
1026   Arg *A;
1027   std::string CPU;
1028   // If we have -mtune or -mcpu, use that.
1029   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1030     CPU = StringRef(A->getValue()).lower();
1031   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1032     StringRef Mcpu = A->getValue();
1033     CPU = Mcpu.split("+").first.lower();
1034   }
1035
1036   // Handle CPU name is 'native'.
1037   if (CPU == "native")
1038     return llvm::sys::getHostCPUName();
1039   else if (CPU.size())
1040     return CPU;
1041
1042   // Make sure we pick "cyclone" if -arch is used.
1043   // FIXME: Should this be picked by checking the target triple instead?
1044   if (Args.getLastArg(options::OPT_arch))
1045     return "cyclone";
1046
1047   return "generic";
1048 }
1049
1050 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1051                                  ArgStringList &CmdArgs) const {
1052   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1053   llvm::Triple Triple(TripleStr);
1054
1055   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1056       Args.hasArg(options::OPT_mkernel) ||
1057       Args.hasArg(options::OPT_fapple_kext))
1058     CmdArgs.push_back("-disable-red-zone");
1059
1060   if (!Args.hasFlag(options::OPT_mimplicit_float,
1061                     options::OPT_mno_implicit_float, true))
1062     CmdArgs.push_back("-no-implicit-float");
1063
1064   const char *ABIName = nullptr;
1065   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1066     ABIName = A->getValue();
1067   else if (Triple.isOSDarwin())
1068     ABIName = "darwinpcs";
1069   else
1070     ABIName = "aapcs";
1071
1072   CmdArgs.push_back("-target-abi");
1073   CmdArgs.push_back(ABIName);
1074
1075   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1076                                options::OPT_mno_fix_cortex_a53_835769)) {
1077     CmdArgs.push_back("-backend-option");
1078     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1079       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1080     else
1081       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1082   } else if (Triple.isAndroid()) {
1083     // Enabled A53 errata (835769) workaround by default on android
1084     CmdArgs.push_back("-backend-option");
1085     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1086   }
1087
1088   // Forward the -mglobal-merge option for explicit control over the pass.
1089   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1090                                options::OPT_mno_global_merge)) {
1091     CmdArgs.push_back("-backend-option");
1092     if (A->getOption().matches(options::OPT_mno_global_merge))
1093       CmdArgs.push_back("-aarch64-global-merge=false");
1094     else
1095       CmdArgs.push_back("-aarch64-global-merge=true");
1096   }
1097 }
1098
1099 // Get CPU and ABI names. They are not independent
1100 // so we have to calculate them together.
1101 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1102                             StringRef &CPUName, StringRef &ABIName) {
1103   const char *DefMips32CPU = "mips32r2";
1104   const char *DefMips64CPU = "mips64r2";
1105
1106   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1107   // default for mips64(el)?-img-linux-gnu.
1108   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1109       Triple.getEnvironment() == llvm::Triple::GNU) {
1110     DefMips32CPU = "mips32r6";
1111     DefMips64CPU = "mips64r6";
1112   }
1113
1114   // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1115   if (Triple.isAndroid())
1116     DefMips64CPU = "mips64r6";
1117
1118   // MIPS3 is the default for mips64*-unknown-openbsd.
1119   if (Triple.getOS() == llvm::Triple::OpenBSD)
1120     DefMips64CPU = "mips3";
1121
1122   if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1123     CPUName = A->getValue();
1124
1125   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1126     ABIName = A->getValue();
1127     // Convert a GNU style Mips ABI name to the name
1128     // accepted by LLVM Mips backend.
1129     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1130                   .Case("32", "o32")
1131                   .Case("64", "n64")
1132                   .Default(ABIName);
1133   }
1134
1135   // Setup default CPU and ABI names.
1136   if (CPUName.empty() && ABIName.empty()) {
1137     switch (Triple.getArch()) {
1138     default:
1139       llvm_unreachable("Unexpected triple arch name");
1140     case llvm::Triple::mips:
1141     case llvm::Triple::mipsel:
1142       CPUName = DefMips32CPU;
1143       break;
1144     case llvm::Triple::mips64:
1145     case llvm::Triple::mips64el:
1146       CPUName = DefMips64CPU;
1147       break;
1148     }
1149   }
1150
1151   if (ABIName.empty()) {
1152     // Deduce ABI name from the target triple.
1153     if (Triple.getArch() == llvm::Triple::mips ||
1154         Triple.getArch() == llvm::Triple::mipsel)
1155       ABIName = "o32";
1156     else
1157       ABIName = "n64";
1158   }
1159
1160   if (CPUName.empty()) {
1161     // Deduce CPU name from ABI name.
1162     CPUName = llvm::StringSwitch<const char *>(ABIName)
1163                   .Cases("o32", "eabi", DefMips32CPU)
1164                   .Cases("n32", "n64", DefMips64CPU)
1165                   .Default("");
1166   }
1167
1168   // FIXME: Warn on inconsistent use of -march and -mabi.
1169 }
1170
1171 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1172                                       const llvm::Triple &Triple) {
1173   StringRef CPUName, ABIName;
1174   tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1175   return llvm::StringSwitch<std::string>(ABIName)
1176       .Case("o32", "")
1177       .Case("n32", "32")
1178       .Case("n64", "64");
1179 }
1180
1181 // Convert ABI name to the GNU tools acceptable variant.
1182 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1183   return llvm::StringSwitch<llvm::StringRef>(ABI)
1184       .Case("o32", "32")
1185       .Case("n64", "64")
1186       .Default(ABI);
1187 }
1188
1189 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1190 // and -mfloat-abi=.
1191 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1192   mips::FloatABI ABI = mips::FloatABI::Invalid;
1193   if (Arg *A =
1194           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1195                           options::OPT_mfloat_abi_EQ)) {
1196     if (A->getOption().matches(options::OPT_msoft_float))
1197       ABI = mips::FloatABI::Soft;
1198     else if (A->getOption().matches(options::OPT_mhard_float))
1199       ABI = mips::FloatABI::Hard;
1200     else {
1201       ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1202                 .Case("soft", mips::FloatABI::Soft)
1203                 .Case("hard", mips::FloatABI::Hard)
1204                 .Default(mips::FloatABI::Invalid);
1205       if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1206         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1207         ABI = mips::FloatABI::Hard;
1208       }
1209     }
1210   }
1211
1212   // If unspecified, choose the default based on the platform.
1213   if (ABI == mips::FloatABI::Invalid) {
1214     // Assume "hard", because it's a default value used by gcc.
1215     // When we start to recognize specific target MIPS processors,
1216     // we will be able to select the default more correctly.
1217     ABI = mips::FloatABI::Hard;
1218   }
1219
1220   assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1221   return ABI;
1222 }
1223
1224 static void AddTargetFeature(const ArgList &Args,
1225                              std::vector<const char *> &Features,
1226                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1227                              StringRef FeatureName) {
1228   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1229     if (A->getOption().matches(OnOpt))
1230       Features.push_back(Args.MakeArgString("+" + FeatureName));
1231     else
1232       Features.push_back(Args.MakeArgString("-" + FeatureName));
1233   }
1234 }
1235
1236 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1237                                   const ArgList &Args,
1238                                   std::vector<const char *> &Features) {
1239   StringRef CPUName;
1240   StringRef ABIName;
1241   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1242   ABIName = getGnuCompatibleMipsABIName(ABIName);
1243
1244   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1245                    options::OPT_mabicalls, "noabicalls");
1246
1247   mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1248   if (FloatABI == mips::FloatABI::Soft) {
1249     // FIXME: Note, this is a hack. We need to pass the selected float
1250     // mode to the MipsTargetInfoBase to define appropriate macros there.
1251     // Now it is the only method.
1252     Features.push_back("+soft-float");
1253   }
1254
1255   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1256     StringRef Val = StringRef(A->getValue());
1257     if (Val == "2008") {
1258       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1259         Features.push_back("+nan2008");
1260       else {
1261         Features.push_back("-nan2008");
1262         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1263       }
1264     } else if (Val == "legacy") {
1265       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1266         Features.push_back("-nan2008");
1267       else {
1268         Features.push_back("+nan2008");
1269         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1270       }
1271     } else
1272       D.Diag(diag::err_drv_unsupported_option_argument)
1273           << A->getOption().getName() << Val;
1274   }
1275
1276   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1277                    options::OPT_mdouble_float, "single-float");
1278   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1279                    "mips16");
1280   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1281                    options::OPT_mno_micromips, "micromips");
1282   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1283                    "dsp");
1284   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1285                    "dspr2");
1286   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1287                    "msa");
1288
1289   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1290   // pass -mfpxx
1291   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1292                                options::OPT_mfp64)) {
1293     if (A->getOption().matches(options::OPT_mfp32))
1294       Features.push_back(Args.MakeArgString("-fp64"));
1295     else if (A->getOption().matches(options::OPT_mfpxx)) {
1296       Features.push_back(Args.MakeArgString("+fpxx"));
1297       Features.push_back(Args.MakeArgString("+nooddspreg"));
1298     } else
1299       Features.push_back(Args.MakeArgString("+fp64"));
1300   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1301     Features.push_back(Args.MakeArgString("+fpxx"));
1302     Features.push_back(Args.MakeArgString("+nooddspreg"));
1303   }
1304
1305   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1306                    options::OPT_modd_spreg, "nooddspreg");
1307 }
1308
1309 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1310                               ArgStringList &CmdArgs) const {
1311   const Driver &D = getToolChain().getDriver();
1312   StringRef CPUName;
1313   StringRef ABIName;
1314   const llvm::Triple &Triple = getToolChain().getTriple();
1315   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1316
1317   CmdArgs.push_back("-target-abi");
1318   CmdArgs.push_back(ABIName.data());
1319
1320   mips::FloatABI ABI = getMipsFloatABI(D, Args);
1321   if (ABI == mips::FloatABI::Soft) {
1322     // Floating point operations and argument passing are soft.
1323     CmdArgs.push_back("-msoft-float");
1324     CmdArgs.push_back("-mfloat-abi");
1325     CmdArgs.push_back("soft");
1326   } else {
1327     // Floating point operations and argument passing are hard.
1328     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1329     CmdArgs.push_back("-mfloat-abi");
1330     CmdArgs.push_back("hard");
1331   }
1332
1333   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1334     if (A->getOption().matches(options::OPT_mxgot)) {
1335       CmdArgs.push_back("-mllvm");
1336       CmdArgs.push_back("-mxgot");
1337     }
1338   }
1339
1340   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1341                                options::OPT_mno_ldc1_sdc1)) {
1342     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1343       CmdArgs.push_back("-mllvm");
1344       CmdArgs.push_back("-mno-ldc1-sdc1");
1345     }
1346   }
1347
1348   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1349                                options::OPT_mno_check_zero_division)) {
1350     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1351       CmdArgs.push_back("-mllvm");
1352       CmdArgs.push_back("-mno-check-zero-division");
1353     }
1354   }
1355
1356   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1357     StringRef v = A->getValue();
1358     CmdArgs.push_back("-mllvm");
1359     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1360     A->claim();
1361   }
1362 }
1363
1364 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1365 static std::string getPPCTargetCPU(const ArgList &Args) {
1366   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1367     StringRef CPUName = A->getValue();
1368
1369     if (CPUName == "native") {
1370       std::string CPU = llvm::sys::getHostCPUName();
1371       if (!CPU.empty() && CPU != "generic")
1372         return CPU;
1373       else
1374         return "";
1375     }
1376
1377     return llvm::StringSwitch<const char *>(CPUName)
1378         .Case("common", "generic")
1379         .Case("440", "440")
1380         .Case("440fp", "440")
1381         .Case("450", "450")
1382         .Case("601", "601")
1383         .Case("602", "602")
1384         .Case("603", "603")
1385         .Case("603e", "603e")
1386         .Case("603ev", "603ev")
1387         .Case("604", "604")
1388         .Case("604e", "604e")
1389         .Case("620", "620")
1390         .Case("630", "pwr3")
1391         .Case("G3", "g3")
1392         .Case("7400", "7400")
1393         .Case("G4", "g4")
1394         .Case("7450", "7450")
1395         .Case("G4+", "g4+")
1396         .Case("750", "750")
1397         .Case("970", "970")
1398         .Case("G5", "g5")
1399         .Case("a2", "a2")
1400         .Case("a2q", "a2q")
1401         .Case("e500mc", "e500mc")
1402         .Case("e5500", "e5500")
1403         .Case("power3", "pwr3")
1404         .Case("power4", "pwr4")
1405         .Case("power5", "pwr5")
1406         .Case("power5x", "pwr5x")
1407         .Case("power6", "pwr6")
1408         .Case("power6x", "pwr6x")
1409         .Case("power7", "pwr7")
1410         .Case("power8", "pwr8")
1411         .Case("pwr3", "pwr3")
1412         .Case("pwr4", "pwr4")
1413         .Case("pwr5", "pwr5")
1414         .Case("pwr5x", "pwr5x")
1415         .Case("pwr6", "pwr6")
1416         .Case("pwr6x", "pwr6x")
1417         .Case("pwr7", "pwr7")
1418         .Case("pwr8", "pwr8")
1419         .Case("powerpc", "ppc")
1420         .Case("powerpc64", "ppc64")
1421         .Case("powerpc64le", "ppc64le")
1422         .Default("");
1423   }
1424
1425   return "";
1426 }
1427
1428 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1429                                  const ArgList &Args,
1430                                  std::vector<const char *> &Features) {
1431   handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1432
1433   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1434   if (FloatABI == ppc::FloatABI::Soft &&
1435       !(Triple.getArch() == llvm::Triple::ppc64 ||
1436         Triple.getArch() == llvm::Triple::ppc64le))
1437     Features.push_back("+soft-float");
1438   else if (FloatABI == ppc::FloatABI::Soft &&
1439            (Triple.getArch() == llvm::Triple::ppc64 ||
1440             Triple.getArch() == llvm::Triple::ppc64le))
1441     D.Diag(diag::err_drv_invalid_mfloat_abi)
1442         << "soft float is not supported for ppc64";
1443
1444   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1445   AddTargetFeature(Args, Features, options::OPT_faltivec,
1446                    options::OPT_fno_altivec, "altivec");
1447 }
1448
1449 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1450   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1451   if (Arg *A =
1452           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1453                           options::OPT_mfloat_abi_EQ)) {
1454     if (A->getOption().matches(options::OPT_msoft_float))
1455       ABI = ppc::FloatABI::Soft;
1456     else if (A->getOption().matches(options::OPT_mhard_float))
1457       ABI = ppc::FloatABI::Hard;
1458     else {
1459       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1460                 .Case("soft", ppc::FloatABI::Soft)
1461                 .Case("hard", ppc::FloatABI::Hard)
1462                 .Default(ppc::FloatABI::Invalid);
1463       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1464         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1465         ABI = ppc::FloatABI::Hard;
1466       }
1467     }
1468   }
1469
1470   // If unspecified, choose the default based on the platform.
1471   if (ABI == ppc::FloatABI::Invalid) {
1472     ABI = ppc::FloatABI::Hard;
1473   }
1474
1475   return ABI;
1476 }
1477
1478 void Clang::AddPPCTargetArgs(const ArgList &Args,
1479                              ArgStringList &CmdArgs) const {
1480   // Select the ABI to use.
1481   const char *ABIName = nullptr;
1482   if (getToolChain().getTriple().isOSLinux())
1483     switch (getToolChain().getArch()) {
1484     case llvm::Triple::ppc64: {
1485       // When targeting a processor that supports QPX, or if QPX is
1486       // specifically enabled, default to using the ABI that supports QPX (so
1487       // long as it is not specifically disabled).
1488       bool HasQPX = false;
1489       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1490         HasQPX = A->getValue() == StringRef("a2q");
1491       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1492       if (HasQPX) {
1493         ABIName = "elfv1-qpx";
1494         break;
1495       }
1496
1497       ABIName = "elfv1";
1498       break;
1499     }
1500     case llvm::Triple::ppc64le:
1501       ABIName = "elfv2";
1502       break;
1503     default:
1504       break;
1505     }
1506
1507   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1508     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1509     // the option if given as we don't have backend support for any targets
1510     // that don't use the altivec abi.
1511     if (StringRef(A->getValue()) != "altivec")
1512       ABIName = A->getValue();
1513
1514   ppc::FloatABI FloatABI =
1515       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1516
1517   if (FloatABI == ppc::FloatABI::Soft) {
1518     // Floating point operations and argument passing are soft.
1519     CmdArgs.push_back("-msoft-float");
1520     CmdArgs.push_back("-mfloat-abi");
1521     CmdArgs.push_back("soft");
1522   } else {
1523     // Floating point operations and argument passing are hard.
1524     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1525     CmdArgs.push_back("-mfloat-abi");
1526     CmdArgs.push_back("hard");
1527   }
1528
1529   if (ABIName) {
1530     CmdArgs.push_back("-target-abi");
1531     CmdArgs.push_back(ABIName);
1532   }
1533 }
1534
1535 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1536   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1537   return A && (A->getValue() == StringRef(Value));
1538 }
1539
1540 /// Get the (LLVM) name of the R600 gpu we are targeting.
1541 static std::string getR600TargetGPU(const ArgList &Args) {
1542   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1543     const char *GPUName = A->getValue();
1544     return llvm::StringSwitch<const char *>(GPUName)
1545         .Cases("rv630", "rv635", "r600")
1546         .Cases("rv610", "rv620", "rs780", "rs880")
1547         .Case("rv740", "rv770")
1548         .Case("palm", "cedar")
1549         .Cases("sumo", "sumo2", "sumo")
1550         .Case("hemlock", "cypress")
1551         .Case("aruba", "cayman")
1552         .Default(GPUName);
1553   }
1554   return "";
1555 }
1556
1557 void Clang::AddSparcTargetArgs(const ArgList &Args,
1558                                ArgStringList &CmdArgs) const {
1559   const Driver &D = getToolChain().getDriver();
1560   std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1561
1562   bool SoftFloatABI = false;
1563   if (Arg *A =
1564           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1565     if (A->getOption().matches(options::OPT_msoft_float))
1566       SoftFloatABI = true;
1567   }
1568
1569   // Only the hard-float ABI on Sparc is standardized, and it is the
1570   // default. GCC also supports a nonstandard soft-float ABI mode, and
1571   // perhaps LLVM should implement that, too. However, since llvm
1572   // currently does not support Sparc soft-float, at all, display an
1573   // error if it's requested.
1574   if (SoftFloatABI) {
1575     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1576                                                      << Triple;
1577   }
1578 }
1579
1580 static const char *getSystemZTargetCPU(const ArgList &Args) {
1581   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1582     return A->getValue();
1583   return "z10";
1584 }
1585
1586 static void getSystemZTargetFeatures(const ArgList &Args,
1587                                      std::vector<const char *> &Features) {
1588   // -m(no-)htm overrides use of the transactional-execution facility.
1589   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1590     if (A->getOption().matches(options::OPT_mhtm))
1591       Features.push_back("+transactional-execution");
1592     else
1593       Features.push_back("-transactional-execution");
1594   }
1595   // -m(no-)vx overrides use of the vector facility.
1596   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1597     if (A->getOption().matches(options::OPT_mvx))
1598       Features.push_back("+vector");
1599     else
1600       Features.push_back("-vector");
1601   }
1602 }
1603
1604 static const char *getX86TargetCPU(const ArgList &Args,
1605                                    const llvm::Triple &Triple) {
1606   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1607     if (StringRef(A->getValue()) != "native") {
1608       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1609         return "core-avx2";
1610
1611       return A->getValue();
1612     }
1613
1614     // FIXME: Reject attempts to use -march=native unless the target matches
1615     // the host.
1616     //
1617     // FIXME: We should also incorporate the detected target features for use
1618     // with -native.
1619     std::string CPU = llvm::sys::getHostCPUName();
1620     if (!CPU.empty() && CPU != "generic")
1621       return Args.MakeArgString(CPU);
1622   }
1623
1624   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1625     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1626     StringRef Arch = A->getValue();
1627     const char *CPU;
1628     if (Triple.getArch() == llvm::Triple::x86) {
1629       CPU = llvm::StringSwitch<const char *>(Arch)
1630                 .Case("IA32", "i386")
1631                 .Case("SSE", "pentium3")
1632                 .Case("SSE2", "pentium4")
1633                 .Case("AVX", "sandybridge")
1634                 .Case("AVX2", "haswell")
1635                 .Default(nullptr);
1636     } else {
1637       CPU = llvm::StringSwitch<const char *>(Arch)
1638                 .Case("AVX", "sandybridge")
1639                 .Case("AVX2", "haswell")
1640                 .Default(nullptr);
1641     }
1642     if (CPU)
1643       return CPU;
1644   }
1645
1646   // Select the default CPU if none was given (or detection failed).
1647
1648   if (Triple.getArch() != llvm::Triple::x86_64 &&
1649       Triple.getArch() != llvm::Triple::x86)
1650     return nullptr; // This routine is only handling x86 targets.
1651
1652   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1653
1654   // FIXME: Need target hooks.
1655   if (Triple.isOSDarwin()) {
1656     if (Triple.getArchName() == "x86_64h")
1657       return "core-avx2";
1658     return Is64Bit ? "core2" : "yonah";
1659   }
1660
1661   // Set up default CPU name for PS4 compilers.
1662   if (Triple.isPS4CPU())
1663     return "btver2";
1664
1665   // On Android use targets compatible with gcc
1666   if (Triple.isAndroid())
1667     return Is64Bit ? "x86-64" : "i686";
1668
1669   // Everything else goes to x86-64 in 64-bit mode.
1670   if (Is64Bit)
1671     return "x86-64";
1672
1673   switch (Triple.getOS()) {
1674   case llvm::Triple::FreeBSD:
1675   case llvm::Triple::NetBSD:
1676   case llvm::Triple::OpenBSD:
1677     return "i486";
1678   case llvm::Triple::Haiku:
1679     return "i586";
1680   case llvm::Triple::Bitrig:
1681     return "i686";
1682   default:
1683     // Fallback to p4.
1684     return "pentium4";
1685   }
1686 }
1687
1688 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1689 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1690   // If we have -mcpu=, use that.
1691   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1692     StringRef CPU = A->getValue();
1693
1694 #ifdef __wasm__
1695     // Handle "native" by examining the host. "native" isn't meaningful when
1696     // cross compiling, so only support this when the host is also WebAssembly.
1697     if (CPU == "native")
1698       return llvm::sys::getHostCPUName();
1699 #endif
1700
1701     return CPU;
1702   }
1703
1704   return "generic";
1705 }
1706
1707 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1708                               bool FromAs = false) {
1709   switch (T.getArch()) {
1710   default:
1711     return "";
1712
1713   case llvm::Triple::aarch64:
1714   case llvm::Triple::aarch64_be:
1715     return getAArch64TargetCPU(Args);
1716
1717   case llvm::Triple::arm:
1718   case llvm::Triple::armeb:
1719   case llvm::Triple::thumb:
1720   case llvm::Triple::thumbeb: {
1721     StringRef MArch, MCPU;
1722     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1723     return arm::getARMTargetCPU(MCPU, MArch, T);
1724   }
1725   case llvm::Triple::mips:
1726   case llvm::Triple::mipsel:
1727   case llvm::Triple::mips64:
1728   case llvm::Triple::mips64el: {
1729     StringRef CPUName;
1730     StringRef ABIName;
1731     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1732     return CPUName;
1733   }
1734
1735   case llvm::Triple::nvptx:
1736   case llvm::Triple::nvptx64:
1737     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1738       return A->getValue();
1739     return "";
1740
1741   case llvm::Triple::ppc:
1742   case llvm::Triple::ppc64:
1743   case llvm::Triple::ppc64le: {
1744     std::string TargetCPUName = getPPCTargetCPU(Args);
1745     // LLVM may default to generating code for the native CPU,
1746     // but, like gcc, we default to a more generic option for
1747     // each architecture. (except on Darwin)
1748     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1749       if (T.getArch() == llvm::Triple::ppc64)
1750         TargetCPUName = "ppc64";
1751       else if (T.getArch() == llvm::Triple::ppc64le)
1752         TargetCPUName = "ppc64le";
1753       else
1754         TargetCPUName = "ppc";
1755     }
1756     return TargetCPUName;
1757   }
1758
1759   case llvm::Triple::sparc:
1760   case llvm::Triple::sparcel:
1761   case llvm::Triple::sparcv9:
1762     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763       return A->getValue();
1764     return "";
1765
1766   case llvm::Triple::x86:
1767   case llvm::Triple::x86_64:
1768     return getX86TargetCPU(Args, T);
1769
1770   case llvm::Triple::hexagon:
1771     return "hexagon" +
1772            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1773
1774   case llvm::Triple::systemz:
1775     return getSystemZTargetCPU(Args);
1776
1777   case llvm::Triple::r600:
1778   case llvm::Triple::amdgcn:
1779     return getR600TargetGPU(Args);
1780
1781   case llvm::Triple::wasm32:
1782   case llvm::Triple::wasm64:
1783     return getWebAssemblyTargetCPU(Args);
1784   }
1785 }
1786
1787 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1788                           ArgStringList &CmdArgs, bool IsThinLTO) {
1789   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1790   // as gold requires -plugin to come before any -plugin-opt that -Wl might
1791   // forward.
1792   CmdArgs.push_back("-plugin");
1793   std::string Plugin =
1794       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1795   CmdArgs.push_back(Args.MakeArgString(Plugin));
1796
1797   // Try to pass driver level flags relevant to LTO code generation down to
1798   // the plugin.
1799
1800   // Handle flags for selecting CPU variants.
1801   std::string CPU = getCPUName(Args, ToolChain.getTriple());
1802   if (!CPU.empty())
1803     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1804
1805   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1806     StringRef OOpt;
1807     if (A->getOption().matches(options::OPT_O4) ||
1808         A->getOption().matches(options::OPT_Ofast))
1809       OOpt = "3";
1810     else if (A->getOption().matches(options::OPT_O))
1811       OOpt = A->getValue();
1812     else if (A->getOption().matches(options::OPT_O0))
1813       OOpt = "0";
1814     if (!OOpt.empty())
1815       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
1816   }
1817
1818   if (IsThinLTO)
1819     CmdArgs.push_back("-plugin-opt=thinlto");
1820
1821   // If an explicit debugger tuning argument appeared, pass it along.
1822   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
1823                                options::OPT_ggdbN_Group)) {
1824     if (A->getOption().matches(options::OPT_glldb))
1825       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
1826     else if (A->getOption().matches(options::OPT_gsce))
1827       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
1828     else
1829       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
1830   }
1831 }
1832
1833 /// This is a helper function for validating the optional refinement step
1834 /// parameter in reciprocal argument strings. Return false if there is an error
1835 /// parsing the refinement step. Otherwise, return true and set the Position
1836 /// of the refinement step in the input string.
1837 static bool getRefinementStep(StringRef In, const Driver &D,
1838                               const Arg &A, size_t &Position) {
1839   const char RefinementStepToken = ':';
1840   Position = In.find(RefinementStepToken);
1841   if (Position != StringRef::npos) {
1842     StringRef Option = A.getOption().getName();
1843     StringRef RefStep = In.substr(Position + 1);
1844     // Allow exactly one numeric character for the additional refinement
1845     // step parameter. This is reasonable for all currently-supported
1846     // operations and architectures because we would expect that a larger value
1847     // of refinement steps would cause the estimate "optimization" to
1848     // under-perform the native operation. Also, if the estimate does not
1849     // converge quickly, it probably will not ever converge, so further
1850     // refinement steps will not produce a better answer.
1851     if (RefStep.size() != 1) {
1852       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1853       return false;
1854     }
1855     char RefStepChar = RefStep[0];
1856     if (RefStepChar < '0' || RefStepChar > '9') {
1857       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1858       return false;
1859     }
1860   }
1861   return true;
1862 }
1863
1864 /// The -mrecip flag requires processing of many optional parameters.
1865 static void ParseMRecip(const Driver &D, const ArgList &Args,
1866                         ArgStringList &OutStrings) {
1867   StringRef DisabledPrefixIn = "!";
1868   StringRef DisabledPrefixOut = "!";
1869   StringRef EnabledPrefixOut = "";
1870   StringRef Out = "-mrecip=";
1871
1872   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1873   if (!A)
1874     return;
1875
1876   unsigned NumOptions = A->getNumValues();
1877   if (NumOptions == 0) {
1878     // No option is the same as "all".
1879     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1880     return;
1881   }
1882
1883   // Pass through "all", "none", or "default" with an optional refinement step.
1884   if (NumOptions == 1) {
1885     StringRef Val = A->getValue(0);
1886     size_t RefStepLoc;
1887     if (!getRefinementStep(Val, D, *A, RefStepLoc))
1888       return;
1889     StringRef ValBase = Val.slice(0, RefStepLoc);
1890     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1891       OutStrings.push_back(Args.MakeArgString(Out + Val));
1892       return;
1893     }
1894   }
1895
1896   // Each reciprocal type may be enabled or disabled individually.
1897   // Check each input value for validity, concatenate them all back together,
1898   // and pass through.
1899
1900   llvm::StringMap<bool> OptionStrings;
1901   OptionStrings.insert(std::make_pair("divd", false));
1902   OptionStrings.insert(std::make_pair("divf", false));
1903   OptionStrings.insert(std::make_pair("vec-divd", false));
1904   OptionStrings.insert(std::make_pair("vec-divf", false));
1905   OptionStrings.insert(std::make_pair("sqrtd", false));
1906   OptionStrings.insert(std::make_pair("sqrtf", false));
1907   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1908   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1909
1910   for (unsigned i = 0; i != NumOptions; ++i) {
1911     StringRef Val = A->getValue(i);
1912
1913     bool IsDisabled = Val.startswith(DisabledPrefixIn);
1914     // Ignore the disablement token for string matching.
1915     if (IsDisabled)
1916       Val = Val.substr(1);
1917
1918     size_t RefStep;
1919     if (!getRefinementStep(Val, D, *A, RefStep))
1920       return;
1921
1922     StringRef ValBase = Val.slice(0, RefStep);
1923     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1924     if (OptionIter == OptionStrings.end()) {
1925       // Try again specifying float suffix.
1926       OptionIter = OptionStrings.find(ValBase.str() + 'f');
1927       if (OptionIter == OptionStrings.end()) {
1928         // The input name did not match any known option string.
1929         D.Diag(diag::err_drv_unknown_argument) << Val;
1930         return;
1931       }
1932       // The option was specified without a float or double suffix.
1933       // Make sure that the double entry was not already specified.
1934       // The float entry will be checked below.
1935       if (OptionStrings[ValBase.str() + 'd']) {
1936         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1937         return;
1938       }
1939     }
1940
1941     if (OptionIter->second == true) {
1942       // Duplicate option specified.
1943       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1944       return;
1945     }
1946
1947     // Mark the matched option as found. Do not allow duplicate specifiers.
1948     OptionIter->second = true;
1949
1950     // If the precision was not specified, also mark the double entry as found.
1951     if (ValBase.back() != 'f' && ValBase.back() != 'd')
1952       OptionStrings[ValBase.str() + 'd'] = true;
1953
1954     // Build the output string.
1955     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1956     Out = Args.MakeArgString(Out + Prefix + Val);
1957     if (i != NumOptions - 1)
1958       Out = Args.MakeArgString(Out + ",");
1959   }
1960
1961   OutStrings.push_back(Args.MakeArgString(Out));
1962 }
1963
1964 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1965                                  const ArgList &Args,
1966                                  std::vector<const char *> &Features) {
1967   // If -march=native, autodetect the feature list.
1968   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1969     if (StringRef(A->getValue()) == "native") {
1970       llvm::StringMap<bool> HostFeatures;
1971       if (llvm::sys::getHostCPUFeatures(HostFeatures))
1972         for (auto &F : HostFeatures)
1973           Features.push_back(
1974               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1975     }
1976   }
1977
1978   if (Triple.getArchName() == "x86_64h") {
1979     // x86_64h implies quite a few of the more modern subtarget features
1980     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1981     Features.push_back("-rdrnd");
1982     Features.push_back("-aes");
1983     Features.push_back("-pclmul");
1984     Features.push_back("-rtm");
1985     Features.push_back("-hle");
1986     Features.push_back("-fsgsbase");
1987   }
1988
1989   const llvm::Triple::ArchType ArchType = Triple.getArch();
1990   // Add features to be compatible with gcc for Android.
1991   if (Triple.isAndroid()) {
1992     if (ArchType == llvm::Triple::x86_64) {
1993       Features.push_back("+sse4.2");
1994       Features.push_back("+popcnt");
1995     } else
1996       Features.push_back("+ssse3");
1997   }
1998
1999   // Set features according to the -arch flag on MSVC.
2000   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2001     StringRef Arch = A->getValue();
2002     bool ArchUsed = false;
2003     // First, look for flags that are shared in x86 and x86-64.
2004     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2005       if (Arch == "AVX" || Arch == "AVX2") {
2006         ArchUsed = true;
2007         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2008       }
2009     }
2010     // Then, look for x86-specific flags.
2011     if (ArchType == llvm::Triple::x86) {
2012       if (Arch == "IA32") {
2013         ArchUsed = true;
2014       } else if (Arch == "SSE" || Arch == "SSE2") {
2015         ArchUsed = true;
2016         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2017       }
2018     }
2019     if (!ArchUsed)
2020       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2021   }
2022
2023   // Now add any that the user explicitly requested on the command line,
2024   // which may override the defaults.
2025   handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2026 }
2027
2028 void Clang::AddX86TargetArgs(const ArgList &Args,
2029                              ArgStringList &CmdArgs) const {
2030   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2031       Args.hasArg(options::OPT_mkernel) ||
2032       Args.hasArg(options::OPT_fapple_kext))
2033     CmdArgs.push_back("-disable-red-zone");
2034
2035   // Default to avoid implicit floating-point for kernel/kext code, but allow
2036   // that to be overridden with -mno-soft-float.
2037   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2038                           Args.hasArg(options::OPT_fapple_kext));
2039   if (Arg *A = Args.getLastArg(
2040           options::OPT_msoft_float, options::OPT_mno_soft_float,
2041           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2042     const Option &O = A->getOption();
2043     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2044                        O.matches(options::OPT_msoft_float));
2045   }
2046   if (NoImplicitFloat)
2047     CmdArgs.push_back("-no-implicit-float");
2048
2049   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2050     StringRef Value = A->getValue();
2051     if (Value == "intel" || Value == "att") {
2052       CmdArgs.push_back("-mllvm");
2053       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2054     } else {
2055       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2056           << A->getOption().getName() << Value;
2057     }
2058   }
2059 }
2060
2061 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2062                                  ArgStringList &CmdArgs) const {
2063   CmdArgs.push_back("-mqdsp6-compat");
2064   CmdArgs.push_back("-Wreturn-type");
2065
2066   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2067     std::string N = llvm::utostr(G.getValue());
2068     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2069     CmdArgs.push_back("-mllvm");
2070     CmdArgs.push_back(Args.MakeArgString(Opt));
2071   }
2072
2073   if (!Args.hasArg(options::OPT_fno_short_enums))
2074     CmdArgs.push_back("-fshort-enums");
2075   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2076     CmdArgs.push_back("-mllvm");
2077     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2078   }
2079   CmdArgs.push_back("-mllvm");
2080   CmdArgs.push_back("-machine-sink-split=0");
2081 }
2082
2083 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2084                                      ArgStringList &CmdArgs) const {
2085   // Default to "hidden" visibility.
2086   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2087                    options::OPT_fvisibility_ms_compat)) {
2088     CmdArgs.push_back("-fvisibility");
2089     CmdArgs.push_back("hidden");
2090   }
2091 }
2092
2093 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2094 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2095                                   std::vector<const char *> &Features) {
2096   SmallVector<StringRef, 8> Split;
2097   text.split(Split, StringRef("+"), -1, false);
2098
2099   for (StringRef Feature : Split) {
2100     const char *result = llvm::StringSwitch<const char *>(Feature)
2101                              .Case("fp", "+fp-armv8")
2102                              .Case("simd", "+neon")
2103                              .Case("crc", "+crc")
2104                              .Case("crypto", "+crypto")
2105                              .Case("fp16", "+fullfp16")
2106                              .Case("profile", "+spe")
2107                              .Case("nofp", "-fp-armv8")
2108                              .Case("nosimd", "-neon")
2109                              .Case("nocrc", "-crc")
2110                              .Case("nocrypto", "-crypto")
2111                              .Case("nofp16", "-fullfp16")
2112                              .Case("noprofile", "-spe")
2113                              .Default(nullptr);
2114     if (result)
2115       Features.push_back(result);
2116     else if (Feature == "neon" || Feature == "noneon")
2117       D.Diag(diag::err_drv_no_neon_modifier);
2118     else
2119       return false;
2120   }
2121   return true;
2122 }
2123
2124 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2125 // decode CPU and feature.
2126 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2127                               std::vector<const char *> &Features) {
2128   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2129   CPU = Split.first;
2130   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2131       CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1") {
2132     Features.push_back("+neon");
2133     Features.push_back("+crc");
2134     Features.push_back("+crypto");
2135   } else if (CPU == "generic") {
2136     Features.push_back("+neon");
2137   } else {
2138     return false;
2139   }
2140
2141   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2142     return false;
2143
2144   return true;
2145 }
2146
2147 static bool
2148 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2149                                 const ArgList &Args,
2150                                 std::vector<const char *> &Features) {
2151   std::string MarchLowerCase = March.lower();
2152   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2153
2154   if (Split.first == "armv8-a" || Split.first == "armv8a") {
2155     // ok, no additional features.
2156   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2157     Features.push_back("+v8.1a");
2158   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2159     Features.push_back("+v8.2a");
2160   } else {
2161     return false;
2162   }
2163
2164   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2165     return false;
2166
2167   return true;
2168 }
2169
2170 static bool
2171 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2172                                const ArgList &Args,
2173                                std::vector<const char *> &Features) {
2174   StringRef CPU;
2175   std::string McpuLowerCase = Mcpu.lower();
2176   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2177     return false;
2178
2179   return true;
2180 }
2181
2182 static bool
2183 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2184                                      const ArgList &Args,
2185                                      std::vector<const char *> &Features) {
2186   std::string MtuneLowerCase = Mtune.lower();
2187   // Handle CPU name is 'native'.
2188   if (MtuneLowerCase == "native")
2189     MtuneLowerCase = llvm::sys::getHostCPUName();
2190   if (MtuneLowerCase == "cyclone") {
2191     Features.push_back("+zcm");
2192     Features.push_back("+zcz");
2193   }
2194   return true;
2195 }
2196
2197 static bool
2198 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2199                                     const ArgList &Args,
2200                                     std::vector<const char *> &Features) {
2201   StringRef CPU;
2202   std::vector<const char *> DecodedFeature;
2203   std::string McpuLowerCase = Mcpu.lower();
2204   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2205     return false;
2206
2207   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2208 }
2209
2210 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2211                                      std::vector<const char *> &Features) {
2212   Arg *A;
2213   bool success = true;
2214   // Enable NEON by default.
2215   Features.push_back("+neon");
2216   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2217     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2218   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2219     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2220   else if (Args.hasArg(options::OPT_arch))
2221     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2222                                              Features);
2223
2224   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2225     success =
2226         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2227   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2228     success =
2229         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2230   else if (Args.hasArg(options::OPT_arch))
2231     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2232                                                   Args, Features);
2233
2234   if (!success)
2235     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2236
2237   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2238     Features.push_back("-fp-armv8");
2239     Features.push_back("-crypto");
2240     Features.push_back("-neon");
2241   }
2242
2243   // En/disable crc
2244   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2245     if (A->getOption().matches(options::OPT_mcrc))
2246       Features.push_back("+crc");
2247     else
2248       Features.push_back("-crc");
2249   }
2250
2251   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2252                                options::OPT_munaligned_access))
2253     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2254       Features.push_back("+strict-align");
2255
2256   if (Args.hasArg(options::OPT_ffixed_x18))
2257     Features.push_back("+reserve-x18");
2258 }
2259
2260 static void getHexagonTargetFeatures(const ArgList &Args,
2261                                      std::vector<const char *> &Features) {
2262   bool HasHVX = false, HasHVXD = false;
2263
2264   // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2265   // doing dependent option handling here rather than in initFeatureMap or a
2266   // similar handler.
2267   for (auto &A : Args) {
2268     auto &Opt = A->getOption();
2269     if (Opt.matches(options::OPT_mhexagon_hvx))
2270       HasHVX = true;
2271     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2272       HasHVXD = HasHVX = false;
2273     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2274       HasHVXD = HasHVX = true;
2275     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2276       HasHVXD = false;
2277     else
2278       continue;
2279     A->claim();
2280   }
2281
2282   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
2283   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2284 }
2285
2286 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2287                                          std::vector<const char *> &Features) {
2288   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2289 }
2290
2291 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2292                               const ArgList &Args, ArgStringList &CmdArgs,
2293                               bool ForAS) {
2294   const Driver &D = TC.getDriver();
2295   std::vector<const char *> Features;
2296   switch (Triple.getArch()) {
2297   default:
2298     break;
2299   case llvm::Triple::mips:
2300   case llvm::Triple::mipsel:
2301   case llvm::Triple::mips64:
2302   case llvm::Triple::mips64el:
2303     getMIPSTargetFeatures(D, Triple, Args, Features);
2304     break;
2305
2306   case llvm::Triple::arm:
2307   case llvm::Triple::armeb:
2308   case llvm::Triple::thumb:
2309   case llvm::Triple::thumbeb:
2310     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2311     break;
2312
2313   case llvm::Triple::ppc:
2314   case llvm::Triple::ppc64:
2315   case llvm::Triple::ppc64le:
2316     getPPCTargetFeatures(D, Triple, Args, Features);
2317     break;
2318   case llvm::Triple::systemz:
2319     getSystemZTargetFeatures(Args, Features);
2320     break;
2321   case llvm::Triple::aarch64:
2322   case llvm::Triple::aarch64_be:
2323     getAArch64TargetFeatures(D, Args, Features);
2324     break;
2325   case llvm::Triple::x86:
2326   case llvm::Triple::x86_64:
2327     getX86TargetFeatures(D, Triple, Args, Features);
2328     break;
2329   case llvm::Triple::hexagon:
2330     getHexagonTargetFeatures(Args, Features);
2331     break;
2332   case llvm::Triple::wasm32:
2333   case llvm::Triple::wasm64:
2334     getWebAssemblyTargetFeatures(Args, Features);
2335     break;
2336   }
2337
2338   // Find the last of each feature.
2339   llvm::StringMap<unsigned> LastOpt;
2340   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2341     const char *Name = Features[I];
2342     assert(Name[0] == '-' || Name[0] == '+');
2343     LastOpt[Name + 1] = I;
2344   }
2345
2346   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2347     // If this feature was overridden, ignore it.
2348     const char *Name = Features[I];
2349     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2350     assert(LastI != LastOpt.end());
2351     unsigned Last = LastI->second;
2352     if (Last != I)
2353       continue;
2354
2355     CmdArgs.push_back("-target-feature");
2356     CmdArgs.push_back(Name);
2357   }
2358 }
2359
2360 static bool
2361 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2362                                           const llvm::Triple &Triple) {
2363   // We use the zero-cost exception tables for Objective-C if the non-fragile
2364   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2365   // later.
2366   if (runtime.isNonFragile())
2367     return true;
2368
2369   if (!Triple.isMacOSX())
2370     return false;
2371
2372   return (!Triple.isMacOSXVersionLT(10, 5) &&
2373           (Triple.getArch() == llvm::Triple::x86_64 ||
2374            Triple.getArch() == llvm::Triple::arm));
2375 }
2376
2377 /// Adds exception related arguments to the driver command arguments. There's a
2378 /// master flag, -fexceptions and also language specific flags to enable/disable
2379 /// C++ and Objective-C exceptions. This makes it possible to for example
2380 /// disable C++ exceptions but enable Objective-C exceptions.
2381 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2382                              const ToolChain &TC, bool KernelOrKext,
2383                              const ObjCRuntime &objcRuntime,
2384                              ArgStringList &CmdArgs) {
2385   const Driver &D = TC.getDriver();
2386   const llvm::Triple &Triple = TC.getTriple();
2387
2388   if (KernelOrKext) {
2389     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2390     // arguments now to avoid warnings about unused arguments.
2391     Args.ClaimAllArgs(options::OPT_fexceptions);
2392     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2393     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2394     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2395     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2396     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2397     return;
2398   }
2399
2400   // See if the user explicitly enabled exceptions.
2401   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2402                          false);
2403
2404   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2405   // is not necessarily sensible, but follows GCC.
2406   if (types::isObjC(InputType) &&
2407       Args.hasFlag(options::OPT_fobjc_exceptions,
2408                    options::OPT_fno_objc_exceptions, true)) {
2409     CmdArgs.push_back("-fobjc-exceptions");
2410
2411     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2412   }
2413
2414   if (types::isCXX(InputType)) {
2415     // Disable C++ EH by default on XCore, PS4, and MSVC.
2416     // FIXME: Remove MSVC from this list once things work.
2417     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2418                                 !Triple.isPS4CPU() &&
2419                                 !Triple.isWindowsMSVCEnvironment();
2420     Arg *ExceptionArg = Args.getLastArg(
2421         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2422         options::OPT_fexceptions, options::OPT_fno_exceptions);
2423     if (ExceptionArg)
2424       CXXExceptionsEnabled =
2425           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2426           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2427
2428     if (CXXExceptionsEnabled) {
2429       if (Triple.isPS4CPU()) {
2430         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2431         assert(ExceptionArg &&
2432                "On the PS4 exceptions should only be enabled if passing "
2433                "an argument");
2434         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2435           const Arg *RTTIArg = TC.getRTTIArg();
2436           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2437           D.Diag(diag::err_drv_argument_not_allowed_with)
2438               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2439         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2440           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2441       } else
2442         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2443
2444       CmdArgs.push_back("-fcxx-exceptions");
2445
2446       EH = true;
2447     }
2448   }
2449
2450   if (EH)
2451     CmdArgs.push_back("-fexceptions");
2452 }
2453
2454 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2455   bool Default = true;
2456   if (TC.getTriple().isOSDarwin()) {
2457     // The native darwin assembler doesn't support the linker_option directives,
2458     // so we disable them if we think the .s file will be passed to it.
2459     Default = TC.useIntegratedAs();
2460   }
2461   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2462                        Default);
2463 }
2464
2465 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2466                                         const ToolChain &TC) {
2467   bool UseDwarfDirectory =
2468       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2469                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2470   return !UseDwarfDirectory;
2471 }
2472
2473 /// \brief Check whether the given input tree contains any compilation actions.
2474 static bool ContainsCompileAction(const Action *A) {
2475   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2476     return true;
2477
2478   for (const auto &Act : *A)
2479     if (ContainsCompileAction(Act))
2480       return true;
2481
2482   return false;
2483 }
2484
2485 /// \brief Check if -relax-all should be passed to the internal assembler.
2486 /// This is done by default when compiling non-assembler source with -O0.
2487 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2488   bool RelaxDefault = true;
2489
2490   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2491     RelaxDefault = A->getOption().matches(options::OPT_O0);
2492
2493   if (RelaxDefault) {
2494     RelaxDefault = false;
2495     for (const auto &Act : C.getActions()) {
2496       if (ContainsCompileAction(Act)) {
2497         RelaxDefault = true;
2498         break;
2499       }
2500     }
2501   }
2502
2503   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2504                       RelaxDefault);
2505 }
2506
2507 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2508 // to the corresponding DebugInfoKind.
2509 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2510   assert(A.getOption().matches(options::OPT_gN_Group) &&
2511          "Not a -g option that specifies a debug-info level");
2512   if (A.getOption().matches(options::OPT_g0) ||
2513       A.getOption().matches(options::OPT_ggdb0))
2514     return CodeGenOptions::NoDebugInfo;
2515   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2516       A.getOption().matches(options::OPT_ggdb1))
2517     return CodeGenOptions::DebugLineTablesOnly;
2518   return CodeGenOptions::LimitedDebugInfo;
2519 }
2520
2521 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2522 // on mismatch. The StringRef input (rather than an Arg) allows
2523 // for use by the "-Xassembler" option parser.
2524 static unsigned DwarfVersionNum(StringRef ArgValue) {
2525   return llvm::StringSwitch<unsigned>(ArgValue)
2526       .Case("-gdwarf-2", 2)
2527       .Case("-gdwarf-3", 3)
2528       .Case("-gdwarf-4", 4)
2529       .Case("-gdwarf-5", 5)
2530       .Default(0);
2531 }
2532
2533 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2534                                     CodeGenOptions::DebugInfoKind DebugInfoKind,
2535                                     unsigned DwarfVersion,
2536                                     llvm::DebuggerKind DebuggerTuning) {
2537   switch (DebugInfoKind) {
2538   case CodeGenOptions::DebugLineTablesOnly:
2539     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2540     break;
2541   case CodeGenOptions::LimitedDebugInfo:
2542     CmdArgs.push_back("-debug-info-kind=limited");
2543     break;
2544   case CodeGenOptions::FullDebugInfo:
2545     CmdArgs.push_back("-debug-info-kind=standalone");
2546     break;
2547   default:
2548     break;
2549   }
2550   if (DwarfVersion > 0)
2551     CmdArgs.push_back(
2552         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2553   switch (DebuggerTuning) {
2554   case llvm::DebuggerKind::GDB:
2555     CmdArgs.push_back("-debugger-tuning=gdb");
2556     break;
2557   case llvm::DebuggerKind::LLDB:
2558     CmdArgs.push_back("-debugger-tuning=lldb");
2559     break;
2560   case llvm::DebuggerKind::SCE:
2561     CmdArgs.push_back("-debugger-tuning=sce");
2562     break;
2563   default:
2564     break;
2565   }
2566 }
2567
2568 static void CollectArgsForIntegratedAssembler(Compilation &C,
2569                                               const ArgList &Args,
2570                                               ArgStringList &CmdArgs,
2571                                               const Driver &D) {
2572   if (UseRelaxAll(C, Args))
2573     CmdArgs.push_back("-mrelax-all");
2574
2575   // Only default to -mincremental-linker-compatible if we think we are
2576   // targeting the MSVC linker.
2577   bool DefaultIncrementalLinkerCompatible =
2578       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2579   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2580                    options::OPT_mno_incremental_linker_compatible,
2581                    DefaultIncrementalLinkerCompatible))
2582     CmdArgs.push_back("-mincremental-linker-compatible");
2583
2584   // When passing -I arguments to the assembler we sometimes need to
2585   // unconditionally take the next argument.  For example, when parsing
2586   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2587   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2588   // arg after parsing the '-I' arg.
2589   bool TakeNextArg = false;
2590
2591   // When using an integrated assembler, translate -Wa, and -Xassembler
2592   // options.
2593   bool CompressDebugSections = false;
2594   const char *MipsTargetFeature = nullptr;
2595   for (const Arg *A :
2596        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2597     A->claim();
2598
2599     for (StringRef Value : A->getValues()) {
2600       if (TakeNextArg) {
2601         CmdArgs.push_back(Value.data());
2602         TakeNextArg = false;
2603         continue;
2604       }
2605
2606       switch (C.getDefaultToolChain().getArch()) {
2607       default:
2608         break;
2609       case llvm::Triple::mips:
2610       case llvm::Triple::mipsel:
2611       case llvm::Triple::mips64:
2612       case llvm::Triple::mips64el:
2613         if (Value == "--trap") {
2614           CmdArgs.push_back("-target-feature");
2615           CmdArgs.push_back("+use-tcc-in-div");
2616           continue;
2617         }
2618         if (Value == "--break") {
2619           CmdArgs.push_back("-target-feature");
2620           CmdArgs.push_back("-use-tcc-in-div");
2621           continue;
2622         }
2623         if (Value.startswith("-msoft-float")) {
2624           CmdArgs.push_back("-target-feature");
2625           CmdArgs.push_back("+soft-float");
2626           continue;
2627         }
2628         if (Value.startswith("-mhard-float")) {
2629           CmdArgs.push_back("-target-feature");
2630           CmdArgs.push_back("-soft-float");
2631           continue;
2632         }
2633
2634         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2635                                 .Case("-mips1", "+mips1")
2636                                 .Case("-mips2", "+mips2")
2637                                 .Case("-mips3", "+mips3")
2638                                 .Case("-mips4", "+mips4")
2639                                 .Case("-mips5", "+mips5")
2640                                 .Case("-mips32", "+mips32")
2641                                 .Case("-mips32r2", "+mips32r2")
2642                                 .Case("-mips32r3", "+mips32r3")
2643                                 .Case("-mips32r5", "+mips32r5")
2644                                 .Case("-mips32r6", "+mips32r6")
2645                                 .Case("-mips64", "+mips64")
2646                                 .Case("-mips64r2", "+mips64r2")
2647                                 .Case("-mips64r3", "+mips64r3")
2648                                 .Case("-mips64r5", "+mips64r5")
2649                                 .Case("-mips64r6", "+mips64r6")
2650                                 .Default(nullptr);
2651         if (MipsTargetFeature)
2652           continue;
2653       }
2654
2655       if (Value == "-force_cpusubtype_ALL") {
2656         // Do nothing, this is the default and we don't support anything else.
2657       } else if (Value == "-L") {
2658         CmdArgs.push_back("-msave-temp-labels");
2659       } else if (Value == "--fatal-warnings") {
2660         CmdArgs.push_back("-massembler-fatal-warnings");
2661       } else if (Value == "--noexecstack") {
2662         CmdArgs.push_back("-mnoexecstack");
2663       } else if (Value == "-compress-debug-sections" ||
2664                  Value == "--compress-debug-sections") {
2665         CompressDebugSections = true;
2666       } else if (Value == "-nocompress-debug-sections" ||
2667                  Value == "--nocompress-debug-sections") {
2668         CompressDebugSections = false;
2669       } else if (Value.startswith("-I")) {
2670         CmdArgs.push_back(Value.data());
2671         // We need to consume the next argument if the current arg is a plain
2672         // -I. The next arg will be the include directory.
2673         if (Value == "-I")
2674           TakeNextArg = true;
2675       } else if (Value.startswith("-gdwarf-")) {
2676         // "-gdwarf-N" options are not cc1as options.
2677         unsigned DwarfVersion = DwarfVersionNum(Value);
2678         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2679           CmdArgs.push_back(Value.data());
2680         } else {
2681           RenderDebugEnablingArgs(
2682               Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2683               llvm::DebuggerKind::Default);
2684         }
2685       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2686                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2687         // Do nothing, we'll validate it later.
2688       } else {
2689         D.Diag(diag::err_drv_unsupported_option_argument)
2690             << A->getOption().getName() << Value;
2691       }
2692     }
2693   }
2694   if (CompressDebugSections) {
2695     if (llvm::zlib::isAvailable())
2696       CmdArgs.push_back("-compress-debug-sections");
2697     else
2698       D.Diag(diag::warn_debug_compression_unavailable);
2699   }
2700   if (MipsTargetFeature != nullptr) {
2701     CmdArgs.push_back("-target-feature");
2702     CmdArgs.push_back(MipsTargetFeature);
2703   }
2704 }
2705
2706 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2707 // FIXME: Make sure we can also emit shared objects if they're requested
2708 // and available, check for possible errors, etc.
2709 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2710                        ArgStringList &CmdArgs) {
2711   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2712 }
2713
2714 namespace {
2715 enum OpenMPRuntimeKind {
2716   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2717   /// without knowing what runtime to target.
2718   OMPRT_Unknown,
2719
2720   /// The LLVM OpenMP runtime. When completed and integrated, this will become
2721   /// the default for Clang.
2722   OMPRT_OMP,
2723
2724   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2725   /// this runtime but can swallow the pragmas, and find and link against the
2726   /// runtime library itself.
2727   OMPRT_GOMP,
2728
2729   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2730   /// OpenMP runtime. We support this mode for users with existing dependencies
2731   /// on this runtime library name.
2732   OMPRT_IOMP5
2733 };
2734 }
2735
2736 /// Compute the desired OpenMP runtime from the flag provided.
2737 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2738                                           const ArgList &Args) {
2739   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2740
2741   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2742   if (A)
2743     RuntimeName = A->getValue();
2744
2745   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2746                 .Case("libomp", OMPRT_OMP)
2747                 .Case("libgomp", OMPRT_GOMP)
2748                 .Case("libiomp5", OMPRT_IOMP5)
2749                 .Default(OMPRT_Unknown);
2750
2751   if (RT == OMPRT_Unknown) {
2752     if (A)
2753       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2754           << A->getOption().getName() << A->getValue();
2755     else
2756       // FIXME: We could use a nicer diagnostic here.
2757       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2758   }
2759
2760   return RT;
2761 }
2762
2763 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2764                               const ArgList &Args) {
2765   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2766                     options::OPT_fno_openmp, false))
2767     return;
2768
2769   switch (getOpenMPRuntime(TC, Args)) {
2770   case OMPRT_OMP:
2771     CmdArgs.push_back("-lomp");
2772     break;
2773   case OMPRT_GOMP:
2774     CmdArgs.push_back("-lgomp");
2775     break;
2776   case OMPRT_IOMP5:
2777     CmdArgs.push_back("-liomp5");
2778     break;
2779   case OMPRT_Unknown:
2780     // Already diagnosed.
2781     break;
2782   }
2783 }
2784
2785 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2786                                 ArgStringList &CmdArgs, StringRef Sanitizer,
2787                                 bool IsShared, bool IsWhole) {
2788   // Wrap any static runtimes that must be forced into executable in
2789   // whole-archive.
2790   if (IsWhole) CmdArgs.push_back("-whole-archive");
2791   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2792   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
2793 }
2794
2795 // Tries to use a file with the list of dynamic symbols that need to be exported
2796 // from the runtime library. Returns true if the file was found.
2797 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2798                                     ArgStringList &CmdArgs,
2799                                     StringRef Sanitizer) {
2800   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2801   if (llvm::sys::fs::exists(SanRT + ".syms")) {
2802     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2803     return true;
2804   }
2805   return false;
2806 }
2807
2808 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2809                                      ArgStringList &CmdArgs) {
2810   // Force linking against the system libraries sanitizers depends on
2811   // (see PR15823 why this is necessary).
2812   CmdArgs.push_back("--no-as-needed");
2813   CmdArgs.push_back("-lpthread");
2814   CmdArgs.push_back("-lrt");
2815   CmdArgs.push_back("-lm");
2816   // There's no libdl on FreeBSD.
2817   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2818     CmdArgs.push_back("-ldl");
2819 }
2820
2821 static void
2822 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2823                          SmallVectorImpl<StringRef> &SharedRuntimes,
2824                          SmallVectorImpl<StringRef> &StaticRuntimes,
2825                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
2826                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
2827                          SmallVectorImpl<StringRef> &RequiredSymbols) {
2828   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2829   // Collect shared runtimes.
2830   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2831     SharedRuntimes.push_back("asan");
2832   }
2833   // The stats_client library is also statically linked into DSOs.
2834   if (SanArgs.needsStatsRt())
2835     StaticRuntimes.push_back("stats_client");
2836
2837   // Collect static runtimes.
2838   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2839     // Don't link static runtimes into DSOs or if compiling for Android.
2840     return;
2841   }
2842   if (SanArgs.needsAsanRt()) {
2843     if (SanArgs.needsSharedAsanRt()) {
2844       HelperStaticRuntimes.push_back("asan-preinit");
2845     } else {
2846       StaticRuntimes.push_back("asan");
2847       if (SanArgs.linkCXXRuntimes())
2848         StaticRuntimes.push_back("asan_cxx");
2849     }
2850   }
2851   if (SanArgs.needsDfsanRt())
2852     StaticRuntimes.push_back("dfsan");
2853   if (SanArgs.needsLsanRt())
2854     StaticRuntimes.push_back("lsan");
2855   if (SanArgs.needsMsanRt()) {
2856     StaticRuntimes.push_back("msan");
2857     if (SanArgs.linkCXXRuntimes())
2858       StaticRuntimes.push_back("msan_cxx");
2859   }
2860   if (SanArgs.needsTsanRt()) {
2861     StaticRuntimes.push_back("tsan");
2862     if (SanArgs.linkCXXRuntimes())
2863       StaticRuntimes.push_back("tsan_cxx");
2864   }
2865   if (SanArgs.needsUbsanRt()) {
2866     StaticRuntimes.push_back("ubsan_standalone");
2867     if (SanArgs.linkCXXRuntimes())
2868       StaticRuntimes.push_back("ubsan_standalone_cxx");
2869   }
2870   if (SanArgs.needsSafeStackRt())
2871     StaticRuntimes.push_back("safestack");
2872   if (SanArgs.needsCfiRt())
2873     StaticRuntimes.push_back("cfi");
2874   if (SanArgs.needsCfiDiagRt())
2875     StaticRuntimes.push_back("cfi_diag");
2876   if (SanArgs.needsStatsRt()) {
2877     NonWholeStaticRuntimes.push_back("stats");
2878     RequiredSymbols.push_back("__sanitizer_stats_register");
2879   }
2880 }
2881
2882 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2883 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2884 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2885                                  ArgStringList &CmdArgs) {
2886   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2887       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
2888   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2889                            NonWholeStaticRuntimes, HelperStaticRuntimes,
2890                            RequiredSymbols);
2891   for (auto RT : SharedRuntimes)
2892     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
2893   for (auto RT : HelperStaticRuntimes)
2894     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
2895   bool AddExportDynamic = false;
2896   for (auto RT : StaticRuntimes) {
2897     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
2898     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2899   }
2900   for (auto RT : NonWholeStaticRuntimes) {
2901     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
2902     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2903   }
2904   for (auto S : RequiredSymbols) {
2905     CmdArgs.push_back("-u");
2906     CmdArgs.push_back(Args.MakeArgString(S));
2907   }
2908   // If there is a static runtime with no dynamic list, force all the symbols
2909   // to be dynamic to be sure we export sanitizer interface functions.
2910   if (AddExportDynamic)
2911     CmdArgs.push_back("-export-dynamic");
2912   return !StaticRuntimes.empty();
2913 }
2914
2915 static bool areOptimizationsEnabled(const ArgList &Args) {
2916   // Find the last -O arg and see if it is non-zero.
2917   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2918     return !A->getOption().matches(options::OPT_O0);
2919   // Defaults to -O0.
2920   return false;
2921 }
2922
2923 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2924                                            const llvm::Triple &Triple) {
2925   switch (Triple.getArch()) {
2926   case llvm::Triple::xcore:
2927   case llvm::Triple::wasm32:
2928   case llvm::Triple::wasm64:
2929     // XCore never wants frame pointers, regardless of OS.
2930     // WebAssembly never wants frame pointers.
2931     return false;
2932   default:
2933     break;
2934   }
2935
2936   if (Triple.isOSLinux()) {
2937     switch (Triple.getArch()) {
2938     // Don't use a frame pointer on linux if optimizing for certain targets.
2939     case llvm::Triple::mips64:
2940     case llvm::Triple::mips64el:
2941     case llvm::Triple::mips:
2942     case llvm::Triple::mipsel:
2943     case llvm::Triple::systemz:
2944     case llvm::Triple::x86:
2945     case llvm::Triple::x86_64:
2946       return !areOptimizationsEnabled(Args);
2947     default:
2948       return true;
2949     }
2950   }
2951
2952   if (Triple.isOSWindows()) {
2953     switch (Triple.getArch()) {
2954     case llvm::Triple::x86:
2955       return !areOptimizationsEnabled(Args);
2956     case llvm::Triple::arm:
2957     case llvm::Triple::thumb:
2958       // Windows on ARM builds with FPO disabled to aid fast stack walking
2959       return true;
2960     default:
2961       // All other supported Windows ISAs use xdata unwind information, so frame
2962       // pointers are not generally useful.
2963       return false;
2964     }
2965   }
2966
2967   return true;
2968 }
2969
2970 static bool shouldUseFramePointer(const ArgList &Args,
2971                                   const llvm::Triple &Triple) {
2972   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2973                                options::OPT_fomit_frame_pointer))
2974     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2975   if (Args.hasArg(options::OPT_pg))
2976     return true;
2977
2978   return shouldUseFramePointerForTarget(Args, Triple);
2979 }
2980
2981 static bool shouldUseLeafFramePointer(const ArgList &Args,
2982                                       const llvm::Triple &Triple) {
2983   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2984                                options::OPT_momit_leaf_frame_pointer))
2985     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2986   if (Args.hasArg(options::OPT_pg))
2987     return true;
2988
2989   if (Triple.isPS4CPU())
2990     return false;
2991
2992   return shouldUseFramePointerForTarget(Args, Triple);
2993 }
2994
2995 /// Add a CC1 option to specify the debug compilation directory.
2996 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2997   SmallString<128> cwd;
2998   if (!llvm::sys::fs::current_path(cwd)) {
2999     CmdArgs.push_back("-fdebug-compilation-dir");
3000     CmdArgs.push_back(Args.MakeArgString(cwd));
3001   }
3002 }
3003
3004 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3005   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3006   if (FinalOutput && Args.hasArg(options::OPT_c)) {
3007     SmallString<128> T(FinalOutput->getValue());
3008     llvm::sys::path::replace_extension(T, "dwo");
3009     return Args.MakeArgString(T);
3010   } else {
3011     // Use the compilation dir.
3012     SmallString<128> T(
3013         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3014     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3015     llvm::sys::path::replace_extension(F, "dwo");
3016     T += F;
3017     return Args.MakeArgString(F);
3018   }
3019 }
3020
3021 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3022                            const JobAction &JA, const ArgList &Args,
3023                            const InputInfo &Output, const char *OutFile) {
3024   ArgStringList ExtractArgs;
3025   ExtractArgs.push_back("--extract-dwo");
3026
3027   ArgStringList StripArgs;
3028   StripArgs.push_back("--strip-dwo");
3029
3030   // Grabbing the output of the earlier compile step.
3031   StripArgs.push_back(Output.getFilename());
3032   ExtractArgs.push_back(Output.getFilename());
3033   ExtractArgs.push_back(OutFile);
3034
3035   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3036   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3037
3038   // First extract the dwo sections.
3039   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3040
3041   // Then remove them from the original .o file.
3042   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3043 }
3044
3045 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3046 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3047 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3048   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3049     if (A->getOption().matches(options::OPT_O4) ||
3050         A->getOption().matches(options::OPT_Ofast))
3051       return true;
3052
3053     if (A->getOption().matches(options::OPT_O0))
3054       return false;
3055
3056     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3057
3058     // Vectorize -Os.
3059     StringRef S(A->getValue());
3060     if (S == "s")
3061       return true;
3062
3063     // Don't vectorize -Oz, unless it's the slp vectorizer.
3064     if (S == "z")
3065       return isSlpVec;
3066
3067     unsigned OptLevel = 0;
3068     if (S.getAsInteger(10, OptLevel))
3069       return false;
3070
3071     return OptLevel > 1;
3072   }
3073
3074   return false;
3075 }
3076
3077 /// Add -x lang to \p CmdArgs for \p Input.
3078 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3079                              ArgStringList &CmdArgs) {
3080   // When using -verify-pch, we don't want to provide the type
3081   // 'precompiled-header' if it was inferred from the file extension
3082   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3083     return;
3084
3085   CmdArgs.push_back("-x");
3086   if (Args.hasArg(options::OPT_rewrite_objc))
3087     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3088   else
3089     CmdArgs.push_back(types::getTypeName(Input.getType()));
3090 }
3091
3092 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3093   if (Version < 100)
3094     return VersionTuple(Version);
3095
3096   if (Version < 10000)
3097     return VersionTuple(Version / 100, Version % 100);
3098
3099   unsigned Build = 0, Factor = 1;
3100   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3101     Build = Build + (Version % 10) * Factor;
3102   return VersionTuple(Version / 100, Version % 100, Build);
3103 }
3104
3105 // Claim options we don't want to warn if they are unused. We do this for
3106 // options that build systems might add but are unused when assembling or only
3107 // running the preprocessor for example.
3108 static void claimNoWarnArgs(const ArgList &Args) {
3109   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3110   // preprocessing, precompiling or assembling.
3111   Args.ClaimAllArgs(options::OPT_flto_EQ);
3112   Args.ClaimAllArgs(options::OPT_flto);
3113   Args.ClaimAllArgs(options::OPT_fno_lto);
3114 }
3115
3116 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3117 #ifdef LLVM_ON_UNIX
3118   const char *Username = getenv("LOGNAME");
3119 #else
3120   const char *Username = getenv("USERNAME");
3121 #endif
3122   if (Username) {
3123     // Validate that LoginName can be used in a path, and get its length.
3124     size_t Len = 0;
3125     for (const char *P = Username; *P; ++P, ++Len) {
3126       if (!isAlphanumeric(*P) && *P != '_') {
3127         Username = nullptr;
3128         break;
3129       }
3130     }
3131
3132     if (Username && Len > 0) {
3133       Result.append(Username, Username + Len);
3134       return;
3135     }
3136   }
3137
3138 // Fallback to user id.
3139 #ifdef LLVM_ON_UNIX
3140   std::string UID = llvm::utostr(getuid());
3141 #else
3142   // FIXME: Windows seems to have an 'SID' that might work.
3143   std::string UID = "9999";
3144 #endif
3145   Result.append(UID.begin(), UID.end());
3146 }
3147
3148 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3149                                           const llvm::Triple &Triple,
3150                                           const llvm::opt::ArgList &Args,
3151                                           bool IsWindowsMSVC) {
3152   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3153                    IsWindowsMSVC) ||
3154       Args.hasArg(options::OPT_fmsc_version) ||
3155       Args.hasArg(options::OPT_fms_compatibility_version)) {
3156     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3157     const Arg *MSCompatibilityVersion =
3158         Args.getLastArg(options::OPT_fms_compatibility_version);
3159
3160     if (MSCVersion && MSCompatibilityVersion) {
3161       if (D)
3162         D->Diag(diag::err_drv_argument_not_allowed_with)
3163             << MSCVersion->getAsString(Args)
3164             << MSCompatibilityVersion->getAsString(Args);
3165       return VersionTuple();
3166     }
3167
3168     if (MSCompatibilityVersion) {
3169       VersionTuple MSVT;
3170       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3171         D->Diag(diag::err_drv_invalid_value)
3172             << MSCompatibilityVersion->getAsString(Args)
3173             << MSCompatibilityVersion->getValue();
3174       return MSVT;
3175     }
3176
3177     if (MSCVersion) {
3178       unsigned Version = 0;
3179       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3180         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3181                                              << MSCVersion->getValue();
3182       return getMSCompatibilityVersion(Version);
3183     }
3184
3185     unsigned Major, Minor, Micro;
3186     Triple.getEnvironmentVersion(Major, Minor, Micro);
3187     if (Major || Minor || Micro)
3188       return VersionTuple(Major, Minor, Micro);
3189
3190     return VersionTuple(18);
3191   }
3192   return VersionTuple();
3193 }
3194
3195 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3196                                    const InputInfo &Output, const ArgList &Args,
3197                                    ArgStringList &CmdArgs) {
3198   auto *ProfileGenerateArg = Args.getLastArg(
3199       options::OPT_fprofile_instr_generate,
3200       options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3201       options::OPT_fprofile_generate_EQ,
3202       options::OPT_fno_profile_instr_generate);
3203   if (ProfileGenerateArg &&
3204       ProfileGenerateArg->getOption().matches(
3205           options::OPT_fno_profile_instr_generate))
3206     ProfileGenerateArg = nullptr;
3207
3208   auto *ProfileUseArg = Args.getLastArg(
3209       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3210       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3211       options::OPT_fno_profile_instr_use);
3212   if (ProfileUseArg &&
3213       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3214     ProfileUseArg = nullptr;
3215
3216   if (ProfileGenerateArg && ProfileUseArg)
3217     D.Diag(diag::err_drv_argument_not_allowed_with)
3218         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3219
3220   if (ProfileGenerateArg) {
3221     if (ProfileGenerateArg->getOption().matches(
3222             options::OPT_fprofile_instr_generate_EQ))
3223       ProfileGenerateArg->render(Args, CmdArgs);
3224     else if (ProfileGenerateArg->getOption().matches(
3225                  options::OPT_fprofile_generate_EQ)) {
3226       SmallString<128> Path(ProfileGenerateArg->getValue());
3227       llvm::sys::path::append(Path, "default.profraw");
3228       CmdArgs.push_back(
3229           Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3230     } else
3231       Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3232   }
3233
3234   if (ProfileUseArg) {
3235     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3236       ProfileUseArg->render(Args, CmdArgs);
3237     else if ((ProfileUseArg->getOption().matches(
3238                   options::OPT_fprofile_use_EQ) ||
3239               ProfileUseArg->getOption().matches(
3240                   options::OPT_fprofile_instr_use))) {
3241       SmallString<128> Path(
3242           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3243       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3244         llvm::sys::path::append(Path, "default.profdata");
3245       CmdArgs.push_back(
3246           Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3247     }
3248   }
3249
3250   if (Args.hasArg(options::OPT_ftest_coverage) ||
3251       Args.hasArg(options::OPT_coverage))
3252     CmdArgs.push_back("-femit-coverage-notes");
3253   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3254                    false) ||
3255       Args.hasArg(options::OPT_coverage))
3256     CmdArgs.push_back("-femit-coverage-data");
3257
3258   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3259                    options::OPT_fno_coverage_mapping, false) &&
3260       !ProfileGenerateArg)
3261     D.Diag(diag::err_drv_argument_only_allowed_with)
3262         << "-fcoverage-mapping"
3263         << "-fprofile-instr-generate";
3264
3265   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3266                    options::OPT_fno_coverage_mapping, false))
3267     CmdArgs.push_back("-fcoverage-mapping");
3268
3269   if (C.getArgs().hasArg(options::OPT_c) ||
3270       C.getArgs().hasArg(options::OPT_S)) {
3271     if (Output.isFilename()) {
3272       CmdArgs.push_back("-coverage-file");
3273       SmallString<128> CoverageFilename;
3274       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3275         CoverageFilename = FinalOutput->getValue();
3276       } else {
3277         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3278       }
3279       if (llvm::sys::path::is_relative(CoverageFilename)) {
3280         SmallString<128> Pwd;
3281         if (!llvm::sys::fs::current_path(Pwd)) {
3282           llvm::sys::path::append(Pwd, CoverageFilename);
3283           CoverageFilename.swap(Pwd);
3284         }
3285       }
3286       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3287     }
3288   }
3289 }
3290
3291 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3292                                 ArgStringList &CmdArgs) {
3293   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3294                     false) ||
3295        Args.hasFlag(options::OPT_fprofile_generate,
3296                     options::OPT_fno_profile_instr_generate, false) ||
3297        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3298                     options::OPT_fno_profile_instr_generate, false) ||
3299        Args.hasFlag(options::OPT_fprofile_instr_generate,
3300                     options::OPT_fno_profile_instr_generate, false) ||
3301        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3302                     options::OPT_fno_profile_instr_generate, false) ||
3303        Args.hasArg(options::OPT_fcreate_profile) ||
3304        Args.hasArg(options::OPT_coverage)))
3305     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3306 }
3307
3308 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3309 /// smooshes them together with platform defaults, to decide whether
3310 /// this compile should be using PIC mode or not. Returns a tuple of
3311 /// (RelocationModel, PICLevel, IsPIE).
3312 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3313 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3314              const ArgList &Args) {
3315   // FIXME: why does this code...and so much everywhere else, use both
3316   // ToolChain.getTriple() and Triple?
3317   bool PIE = ToolChain.isPIEDefault();
3318   bool PIC = PIE || ToolChain.isPICDefault();
3319   // The Darwin/MachO default to use PIC does not apply when using -static.
3320   if (ToolChain.getTriple().isOSBinFormatMachO() &&
3321       Args.hasArg(options::OPT_static))
3322     PIE = PIC = false;
3323   bool IsPICLevelTwo = PIC;
3324
3325   bool KernelOrKext =
3326       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3327
3328   // Android-specific defaults for PIC/PIE
3329   if (ToolChain.getTriple().isAndroid()) {
3330     switch (ToolChain.getArch()) {
3331     case llvm::Triple::arm:
3332     case llvm::Triple::armeb:
3333     case llvm::Triple::thumb:
3334     case llvm::Triple::thumbeb:
3335     case llvm::Triple::aarch64:
3336     case llvm::Triple::mips:
3337     case llvm::Triple::mipsel:
3338     case llvm::Triple::mips64:
3339     case llvm::Triple::mips64el:
3340       PIC = true; // "-fpic"
3341       break;
3342
3343     case llvm::Triple::x86:
3344     case llvm::Triple::x86_64:
3345       PIC = true; // "-fPIC"
3346       IsPICLevelTwo = true;
3347       break;
3348
3349     default:
3350       break;
3351     }
3352   }
3353
3354   // OpenBSD-specific defaults for PIE
3355   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3356     switch (ToolChain.getArch()) {
3357     case llvm::Triple::mips64:
3358     case llvm::Triple::mips64el:
3359     case llvm::Triple::sparcel:
3360     case llvm::Triple::x86:
3361     case llvm::Triple::x86_64:
3362       IsPICLevelTwo = false; // "-fpie"
3363       break;
3364
3365     case llvm::Triple::ppc:
3366     case llvm::Triple::sparc:
3367     case llvm::Triple::sparcv9:
3368       IsPICLevelTwo = true; // "-fPIE"
3369       break;
3370
3371     default:
3372       break;
3373     }
3374   }
3375
3376   // The last argument relating to either PIC or PIE wins, and no
3377   // other argument is used. If the last argument is any flavor of the
3378   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3379   // option implicitly enables PIC at the same level.
3380   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3381                                     options::OPT_fpic, options::OPT_fno_pic,
3382                                     options::OPT_fPIE, options::OPT_fno_PIE,
3383                                     options::OPT_fpie, options::OPT_fno_pie);
3384   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3385   // is forced, then neither PIC nor PIE flags will have no effect.
3386   if (!ToolChain.isPICDefaultForced()) {
3387     if (LastPICArg) {
3388       Option O = LastPICArg->getOption();
3389       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3390           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3391         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3392         PIC =
3393             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3394         IsPICLevelTwo =
3395             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3396       } else {
3397         PIE = PIC = false;
3398         if (Triple.isPS4CPU()) {
3399           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3400           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3401           if (Model != "kernel") {
3402             PIC = true;
3403             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3404                 << LastPICArg->getSpelling();
3405           }
3406         }
3407       }
3408     }
3409   }
3410
3411   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3412   // PIC level would've been set to level 1, force it back to level 2 PIC
3413   // instead.
3414   if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3415     IsPICLevelTwo |= ToolChain.isPICDefault();
3416
3417   // This kernel flags are a trump-card: they will disable PIC/PIE
3418   // generation, independent of the argument order.
3419   if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3420                        !Triple.isWatchOS()))
3421     PIC = PIE = false;
3422
3423   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3424     // This is a very special mode. It trumps the other modes, almost no one
3425     // uses it, and it isn't even valid on any OS but Darwin.
3426     if (!ToolChain.getTriple().isOSDarwin())
3427       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3428           << A->getSpelling() << ToolChain.getTriple().str();
3429
3430     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3431
3432     // Only a forced PIC mode can cause the actual compile to have PIC defines
3433     // etc., no flags are sufficient. This behavior was selected to closely
3434     // match that of llvm-gcc and Apple GCC before that.
3435     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3436
3437     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3438   }
3439
3440   if (PIC)
3441     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3442
3443   return std::make_tuple(llvm::Reloc::Static, 0, false);
3444 }
3445
3446 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3447   switch (Model) {
3448   case llvm::Reloc::Default:
3449     return nullptr;
3450   case llvm::Reloc::Static:
3451     return "static";
3452   case llvm::Reloc::PIC_:
3453     return "pic";
3454   case llvm::Reloc::DynamicNoPIC:
3455     return "dynamic-no-pic";
3456   }
3457   llvm_unreachable("Unknown Reloc::Model kind");
3458 }
3459
3460 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3461                              ArgStringList &CmdArgs) {
3462   llvm::Reloc::Model RelocationModel;
3463   unsigned PICLevel;
3464   bool IsPIE;
3465   std::tie(RelocationModel, PICLevel, IsPIE) =
3466       ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3467
3468   if (RelocationModel != llvm::Reloc::Static)
3469     CmdArgs.push_back("-KPIC");
3470 }
3471
3472 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3473                          const InputInfo &Output, const InputInfoList &Inputs,
3474                          const ArgList &Args, const char *LinkingOutput) const {
3475   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3476   const llvm::Triple Triple(TripleStr);
3477
3478   bool KernelOrKext =
3479       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3480   const Driver &D = getToolChain().getDriver();
3481   ArgStringList CmdArgs;
3482
3483   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3484   bool IsWindowsCygnus =
3485       getToolChain().getTriple().isWindowsCygwinEnvironment();
3486   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3487   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3488
3489   // Check number of inputs for sanity. We need at least one input.
3490   assert(Inputs.size() >= 1 && "Must have at least one input.");
3491   const InputInfo &Input = Inputs[0];
3492   // CUDA compilation may have multiple inputs (source file + results of
3493   // device-side compilations). All other jobs are expected to have exactly one
3494   // input.
3495   bool IsCuda = types::isCuda(Input.getType());
3496   assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3497
3498   // Invoke ourselves in -cc1 mode.
3499   //
3500   // FIXME: Implement custom jobs for internal actions.
3501   CmdArgs.push_back("-cc1");
3502
3503   // Add the "effective" target triple.
3504   CmdArgs.push_back("-triple");
3505   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3506
3507   const ToolChain *AuxToolChain = nullptr;
3508   if (IsCuda) {
3509     // FIXME: We need a (better) way to pass information about
3510     // particular compilation pass we're constructing here. For now we
3511     // can check which toolchain we're using and pick the other one to
3512     // extract the triple.
3513     if (&getToolChain() == C.getCudaDeviceToolChain())
3514       AuxToolChain = C.getCudaHostToolChain();
3515     else if (&getToolChain() == C.getCudaHostToolChain())
3516       AuxToolChain = C.getCudaDeviceToolChain();
3517     else
3518       llvm_unreachable("Can't figure out CUDA compilation mode.");
3519     assert(AuxToolChain != nullptr && "No aux toolchain.");
3520     CmdArgs.push_back("-aux-triple");
3521     CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3522     CmdArgs.push_back("-fcuda-target-overloads");
3523     CmdArgs.push_back("-fcuda-disable-target-call-checks");
3524   }
3525
3526   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3527                                Triple.getArch() == llvm::Triple::thumb)) {
3528     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3529     unsigned Version;
3530     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3531     if (Version < 7)
3532       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3533                                                 << TripleStr;
3534   }
3535
3536   // Push all default warning arguments that are specific to
3537   // the given target.  These come before user provided warning options
3538   // are provided.
3539   getToolChain().addClangWarningOptions(CmdArgs);
3540
3541   // Select the appropriate action.
3542   RewriteKind rewriteKind = RK_None;
3543
3544   if (isa<AnalyzeJobAction>(JA)) {
3545     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3546     CmdArgs.push_back("-analyze");
3547   } else if (isa<MigrateJobAction>(JA)) {
3548     CmdArgs.push_back("-migrate");
3549   } else if (isa<PreprocessJobAction>(JA)) {
3550     if (Output.getType() == types::TY_Dependencies)
3551       CmdArgs.push_back("-Eonly");
3552     else {
3553       CmdArgs.push_back("-E");
3554       if (Args.hasArg(options::OPT_rewrite_objc) &&
3555           !Args.hasArg(options::OPT_g_Group))
3556         CmdArgs.push_back("-P");
3557     }
3558   } else if (isa<AssembleJobAction>(JA)) {
3559     CmdArgs.push_back("-emit-obj");
3560
3561     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3562
3563     // Also ignore explicit -force_cpusubtype_ALL option.
3564     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3565   } else if (isa<PrecompileJobAction>(JA)) {
3566     // Use PCH if the user requested it.
3567     bool UsePCH = D.CCCUsePCH;
3568
3569     if (JA.getType() == types::TY_Nothing)
3570       CmdArgs.push_back("-fsyntax-only");
3571     else if (UsePCH)
3572       CmdArgs.push_back("-emit-pch");
3573     else
3574       CmdArgs.push_back("-emit-pth");
3575   } else if (isa<VerifyPCHJobAction>(JA)) {
3576     CmdArgs.push_back("-verify-pch");
3577   } else {
3578     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3579            "Invalid action for clang tool.");
3580     if (JA.getType() == types::TY_Nothing) {
3581       CmdArgs.push_back("-fsyntax-only");
3582     } else if (JA.getType() == types::TY_LLVM_IR ||
3583                JA.getType() == types::TY_LTO_IR) {
3584       CmdArgs.push_back("-emit-llvm");
3585     } else if (JA.getType() == types::TY_LLVM_BC ||
3586                JA.getType() == types::TY_LTO_BC) {
3587       CmdArgs.push_back("-emit-llvm-bc");
3588     } else if (JA.getType() == types::TY_PP_Asm) {
3589       CmdArgs.push_back("-S");
3590     } else if (JA.getType() == types::TY_AST) {
3591       CmdArgs.push_back("-emit-pch");
3592     } else if (JA.getType() == types::TY_ModuleFile) {
3593       CmdArgs.push_back("-module-file-info");
3594     } else if (JA.getType() == types::TY_RewrittenObjC) {
3595       CmdArgs.push_back("-rewrite-objc");
3596       rewriteKind = RK_NonFragile;
3597     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3598       CmdArgs.push_back("-rewrite-objc");
3599       rewriteKind = RK_Fragile;
3600     } else {
3601       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3602     }
3603
3604     // Preserve use-list order by default when emitting bitcode, so that
3605     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3606     // same result as running passes here.  For LTO, we don't need to preserve
3607     // the use-list order, since serialization to bitcode is part of the flow.
3608     if (JA.getType() == types::TY_LLVM_BC)
3609       CmdArgs.push_back("-emit-llvm-uselists");
3610
3611     if (D.isUsingLTO())
3612       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3613   }
3614
3615   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3616     if (!types::isLLVMIR(Input.getType()))
3617       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3618                                                        << "-x ir";
3619     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3620   }
3621
3622   // We normally speed up the clang process a bit by skipping destructors at
3623   // exit, but when we're generating diagnostics we can rely on some of the
3624   // cleanup.
3625   if (!C.isForDiagnostics())
3626     CmdArgs.push_back("-disable-free");
3627
3628 // Disable the verification pass in -asserts builds.
3629 #ifdef NDEBUG
3630   CmdArgs.push_back("-disable-llvm-verifier");
3631 #endif
3632
3633   // Set the main file name, so that debug info works even with
3634   // -save-temps.
3635   CmdArgs.push_back("-main-file-name");
3636   CmdArgs.push_back(getBaseInputName(Args, Input));
3637
3638   // Some flags which affect the language (via preprocessor
3639   // defines).
3640   if (Args.hasArg(options::OPT_static))
3641     CmdArgs.push_back("-static-define");
3642
3643   if (isa<AnalyzeJobAction>(JA)) {
3644     // Enable region store model by default.
3645     CmdArgs.push_back("-analyzer-store=region");
3646
3647     // Treat blocks as analysis entry points.
3648     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3649
3650     CmdArgs.push_back("-analyzer-eagerly-assume");
3651
3652     // Add default argument set.
3653     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3654       CmdArgs.push_back("-analyzer-checker=core");
3655
3656     if (!IsWindowsMSVC) {
3657       CmdArgs.push_back("-analyzer-checker=unix");
3658     } else {
3659       // Enable "unix" checkers that also work on Windows.
3660       CmdArgs.push_back("-analyzer-checker=unix.API");
3661       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3662       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3663       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3664       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3665       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3666     }
3667
3668       // Disable some unix checkers for PS4.
3669       if (IsPS4CPU) {
3670         CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3671         CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3672       }
3673
3674       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3675         CmdArgs.push_back("-analyzer-checker=osx");
3676
3677       CmdArgs.push_back("-analyzer-checker=deadcode");
3678
3679       if (types::isCXX(Input.getType()))
3680         CmdArgs.push_back("-analyzer-checker=cplusplus");
3681
3682       if (!IsPS4CPU) {
3683         CmdArgs.push_back(
3684             "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3685         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3686         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3687         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3688         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3689         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3690       }
3691
3692       // Default nullability checks.
3693       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3694       CmdArgs.push_back(
3695           "-analyzer-checker=nullability.NullReturnedFromNonnull");
3696     }
3697
3698     // Set the output format. The default is plist, for (lame) historical
3699     // reasons.
3700     CmdArgs.push_back("-analyzer-output");
3701     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3702       CmdArgs.push_back(A->getValue());
3703     else
3704       CmdArgs.push_back("plist");
3705
3706     // Disable the presentation of standard compiler warnings when
3707     // using --analyze.  We only want to show static analyzer diagnostics
3708     // or frontend errors.
3709     CmdArgs.push_back("-w");
3710
3711     // Add -Xanalyzer arguments when running as analyzer.
3712     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3713   }
3714
3715   CheckCodeGenerationOptions(D, Args);
3716
3717   llvm::Reloc::Model RelocationModel;
3718   unsigned PICLevel;
3719   bool IsPIE;
3720   std::tie(RelocationModel, PICLevel, IsPIE) =
3721       ParsePICArgs(getToolChain(), Triple, Args);
3722
3723   const char *RMName = RelocationModelName(RelocationModel);
3724   if (RMName) {
3725     CmdArgs.push_back("-mrelocation-model");
3726     CmdArgs.push_back(RMName);
3727   }
3728   if (PICLevel > 0) {
3729     CmdArgs.push_back("-pic-level");
3730     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3731     if (IsPIE) {
3732       CmdArgs.push_back("-pie-level");
3733       CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3734     }
3735   }
3736
3737   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3738     CmdArgs.push_back("-meabi");
3739     CmdArgs.push_back(A->getValue());
3740   }
3741
3742   CmdArgs.push_back("-mthread-model");
3743   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3744     CmdArgs.push_back(A->getValue());
3745   else
3746     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3747
3748   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3749
3750   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3751                     options::OPT_fno_merge_all_constants))
3752     CmdArgs.push_back("-fno-merge-all-constants");
3753
3754   // LLVM Code Generator Options.
3755
3756   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3757       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3758     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3759                                       options::OPT_frewrite_map_file_EQ)) {
3760       CmdArgs.push_back("-frewrite-map-file");
3761       CmdArgs.push_back(A->getValue());
3762       A->claim();
3763     }
3764   }
3765
3766   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3767     StringRef v = A->getValue();
3768     CmdArgs.push_back("-mllvm");
3769     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3770     A->claim();
3771   }
3772
3773   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3774     CmdArgs.push_back("-mregparm");
3775     CmdArgs.push_back(A->getValue());
3776   }
3777
3778   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3779                                options::OPT_freg_struct_return)) {
3780     if (getToolChain().getArch() != llvm::Triple::x86) {
3781       D.Diag(diag::err_drv_unsupported_opt_for_target)
3782           << A->getSpelling() << getToolChain().getTriple().str();
3783     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3784       CmdArgs.push_back("-fpcc-struct-return");
3785     } else {
3786       assert(A->getOption().matches(options::OPT_freg_struct_return));
3787       CmdArgs.push_back("-freg-struct-return");
3788     }
3789   }
3790
3791   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3792     CmdArgs.push_back("-mrtd");
3793
3794   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3795     CmdArgs.push_back("-mdisable-fp-elim");
3796   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3797                     options::OPT_fno_zero_initialized_in_bss))
3798     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3799
3800   bool OFastEnabled = isOptimizationLevelFast(Args);
3801   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3802   // enabled.  This alias option is being used to simplify the hasFlag logic.
3803   OptSpecifier StrictAliasingAliasOption =
3804       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3805   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3806   // doesn't do any TBAA.
3807   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3808   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3809                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3810     CmdArgs.push_back("-relaxed-aliasing");
3811   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3812                     options::OPT_fno_struct_path_tbaa))
3813     CmdArgs.push_back("-no-struct-path-tbaa");
3814   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3815                    false))
3816     CmdArgs.push_back("-fstrict-enums");
3817   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3818                    options::OPT_fno_strict_vtable_pointers,
3819                    false))
3820     CmdArgs.push_back("-fstrict-vtable-pointers");
3821   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3822                     options::OPT_fno_optimize_sibling_calls))
3823     CmdArgs.push_back("-mdisable-tail-calls");
3824
3825   // Handle segmented stacks.
3826   if (Args.hasArg(options::OPT_fsplit_stack))
3827     CmdArgs.push_back("-split-stacks");
3828
3829   // If -Ofast is the optimization level, then -ffast-math should be enabled.
3830   // This alias option is being used to simplify the getLastArg logic.
3831   OptSpecifier FastMathAliasOption =
3832       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3833
3834   // Handle various floating point optimization flags, mapping them to the
3835   // appropriate LLVM code generation flags. The pattern for all of these is to
3836   // default off the codegen optimizations, and if any flag enables them and no
3837   // flag disables them after the flag enabling them, enable the codegen
3838   // optimization. This is complicated by several "umbrella" flags.
3839   if (Arg *A = Args.getLastArg(
3840           options::OPT_ffast_math, FastMathAliasOption,
3841           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3842           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3843           options::OPT_fno_honor_infinities))
3844     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3845         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3846         A->getOption().getID() != options::OPT_fhonor_infinities)
3847       CmdArgs.push_back("-menable-no-infs");
3848   if (Arg *A = Args.getLastArg(
3849           options::OPT_ffast_math, FastMathAliasOption,
3850           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3851           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3852           options::OPT_fno_honor_nans))
3853     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3854         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3855         A->getOption().getID() != options::OPT_fhonor_nans)
3856       CmdArgs.push_back("-menable-no-nans");
3857
3858   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3859   bool MathErrno = getToolChain().IsMathErrnoDefault();
3860   if (Arg *A =
3861           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3862                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
3863                           options::OPT_fno_math_errno)) {
3864     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3865     // However, turning *off* -ffast_math merely restores the toolchain default
3866     // (which may be false).
3867     if (A->getOption().getID() == options::OPT_fno_math_errno ||
3868         A->getOption().getID() == options::OPT_ffast_math ||
3869         A->getOption().getID() == options::OPT_Ofast)
3870       MathErrno = false;
3871     else if (A->getOption().getID() == options::OPT_fmath_errno)
3872       MathErrno = true;
3873   }
3874   if (MathErrno)
3875     CmdArgs.push_back("-fmath-errno");
3876
3877   // There are several flags which require disabling very specific
3878   // optimizations. Any of these being disabled forces us to turn off the
3879   // entire set of LLVM optimizations, so collect them through all the flag
3880   // madness.
3881   bool AssociativeMath = false;
3882   if (Arg *A = Args.getLastArg(
3883           options::OPT_ffast_math, FastMathAliasOption,
3884           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3885           options::OPT_fno_unsafe_math_optimizations,
3886           options::OPT_fassociative_math, options::OPT_fno_associative_math))
3887     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3888         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3889         A->getOption().getID() != options::OPT_fno_associative_math)
3890       AssociativeMath = true;
3891   bool ReciprocalMath = false;
3892   if (Arg *A = Args.getLastArg(
3893           options::OPT_ffast_math, FastMathAliasOption,
3894           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3895           options::OPT_fno_unsafe_math_optimizations,
3896           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3897     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3898         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3899         A->getOption().getID() != options::OPT_fno_reciprocal_math)
3900       ReciprocalMath = true;
3901   bool SignedZeros = true;
3902   if (Arg *A = Args.getLastArg(
3903           options::OPT_ffast_math, FastMathAliasOption,
3904           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3905           options::OPT_fno_unsafe_math_optimizations,
3906           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3907     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3908         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3909         A->getOption().getID() != options::OPT_fsigned_zeros)
3910       SignedZeros = false;
3911   bool TrappingMath = true;
3912   if (Arg *A = Args.getLastArg(
3913           options::OPT_ffast_math, FastMathAliasOption,
3914           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3915           options::OPT_fno_unsafe_math_optimizations,
3916           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3917     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3918         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3919         A->getOption().getID() != options::OPT_ftrapping_math)
3920       TrappingMath = false;
3921   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3922       !TrappingMath)
3923     CmdArgs.push_back("-menable-unsafe-fp-math");
3924
3925   if (!SignedZeros)
3926     CmdArgs.push_back("-fno-signed-zeros");
3927
3928   if (ReciprocalMath)
3929     CmdArgs.push_back("-freciprocal-math");
3930
3931   // Validate and pass through -fp-contract option.
3932   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3933                                options::OPT_fno_fast_math,
3934                                options::OPT_ffp_contract)) {
3935     if (A->getOption().getID() == options::OPT_ffp_contract) {
3936       StringRef Val = A->getValue();
3937       if (Val == "fast" || Val == "on" || Val == "off") {
3938         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3939       } else {
3940         D.Diag(diag::err_drv_unsupported_option_argument)
3941             << A->getOption().getName() << Val;
3942       }
3943     } else if (A->getOption().matches(options::OPT_ffast_math) ||
3944                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3945       // If fast-math is set then set the fp-contract mode to fast.
3946       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3947     }
3948   }
3949
3950   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3951
3952   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3953   // and if we find them, tell the frontend to provide the appropriate
3954   // preprocessor macros. This is distinct from enabling any optimizations as
3955   // these options induce language changes which must survive serialization
3956   // and deserialization, etc.
3957   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3958                                options::OPT_fno_fast_math))
3959     if (!A->getOption().matches(options::OPT_fno_fast_math))
3960       CmdArgs.push_back("-ffast-math");
3961   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3962                                options::OPT_fno_fast_math))
3963     if (A->getOption().matches(options::OPT_ffinite_math_only))
3964       CmdArgs.push_back("-ffinite-math-only");
3965
3966   // Decide whether to use verbose asm. Verbose assembly is the default on
3967   // toolchains which have the integrated assembler on by default.
3968   bool IsIntegratedAssemblerDefault =
3969       getToolChain().IsIntegratedAssemblerDefault();
3970   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3971                    IsIntegratedAssemblerDefault) ||
3972       Args.hasArg(options::OPT_dA))
3973     CmdArgs.push_back("-masm-verbose");
3974
3975   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3976                     IsIntegratedAssemblerDefault))
3977     CmdArgs.push_back("-no-integrated-as");
3978
3979   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3980     CmdArgs.push_back("-mdebug-pass");
3981     CmdArgs.push_back("Structure");
3982   }
3983   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3984     CmdArgs.push_back("-mdebug-pass");
3985     CmdArgs.push_back("Arguments");
3986   }
3987
3988   // Enable -mconstructor-aliases except on darwin, where we have to
3989   // work around a linker bug;  see <rdar://problem/7651567>.
3990   if (!getToolChain().getTriple().isOSDarwin())
3991     CmdArgs.push_back("-mconstructor-aliases");
3992
3993   // Darwin's kernel doesn't support guard variables; just die if we
3994   // try to use them.
3995   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3996     CmdArgs.push_back("-fforbid-guard-variables");
3997
3998   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3999                    false)) {
4000     CmdArgs.push_back("-mms-bitfields");
4001   }
4002
4003   // This is a coarse approximation of what llvm-gcc actually does, both
4004   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4005   // complicated ways.
4006   bool AsynchronousUnwindTables =
4007       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4008                    options::OPT_fno_asynchronous_unwind_tables,
4009                    (getToolChain().IsUnwindTablesDefault() ||
4010                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4011                        !KernelOrKext);
4012   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4013                    AsynchronousUnwindTables))
4014     CmdArgs.push_back("-munwind-tables");
4015
4016   getToolChain().addClangTargetOptions(Args, CmdArgs);
4017
4018   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4019     CmdArgs.push_back("-mlimit-float-precision");
4020     CmdArgs.push_back(A->getValue());
4021   }
4022
4023   // FIXME: Handle -mtune=.
4024   (void)Args.hasArg(options::OPT_mtune_EQ);
4025
4026   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4027     CmdArgs.push_back("-mcode-model");
4028     CmdArgs.push_back(A->getValue());
4029   }
4030
4031   // Add the target cpu
4032   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4033   if (!CPU.empty()) {
4034     CmdArgs.push_back("-target-cpu");
4035     CmdArgs.push_back(Args.MakeArgString(CPU));
4036   }
4037
4038   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4039     CmdArgs.push_back("-mfpmath");
4040     CmdArgs.push_back(A->getValue());
4041   }
4042
4043   // Add the target features
4044   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4045
4046   // Add target specific flags.
4047   switch (getToolChain().getArch()) {
4048   default:
4049     break;
4050
4051   case llvm::Triple::arm:
4052   case llvm::Triple::armeb:
4053   case llvm::Triple::thumb:
4054   case llvm::Triple::thumbeb:
4055     // Use the effective triple, which takes into account the deployment target.
4056     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4057     break;
4058
4059   case llvm::Triple::aarch64:
4060   case llvm::Triple::aarch64_be:
4061     AddAArch64TargetArgs(Args, CmdArgs);
4062     break;
4063
4064   case llvm::Triple::mips:
4065   case llvm::Triple::mipsel:
4066   case llvm::Triple::mips64:
4067   case llvm::Triple::mips64el:
4068     AddMIPSTargetArgs(Args, CmdArgs);
4069     break;
4070
4071   case llvm::Triple::ppc:
4072   case llvm::Triple::ppc64:
4073   case llvm::Triple::ppc64le:
4074     AddPPCTargetArgs(Args, CmdArgs);
4075     break;
4076
4077   case llvm::Triple::sparc:
4078   case llvm::Triple::sparcel:
4079   case llvm::Triple::sparcv9:
4080     AddSparcTargetArgs(Args, CmdArgs);
4081     break;
4082
4083   case llvm::Triple::x86:
4084   case llvm::Triple::x86_64:
4085     AddX86TargetArgs(Args, CmdArgs);
4086     break;
4087
4088   case llvm::Triple::hexagon:
4089     AddHexagonTargetArgs(Args, CmdArgs);
4090     break;
4091
4092   case llvm::Triple::wasm32:
4093   case llvm::Triple::wasm64:
4094     AddWebAssemblyTargetArgs(Args, CmdArgs);
4095     break;
4096   }
4097
4098   // The 'g' groups options involve a somewhat intricate sequence of decisions
4099   // about what to pass from the driver to the frontend, but by the time they
4100   // reach cc1 they've been factored into three well-defined orthogonal choices:
4101   //  * what level of debug info to generate
4102   //  * what dwarf version to write
4103   //  * what debugger tuning to use
4104   // This avoids having to monkey around further in cc1 other than to disable
4105   // codeview if not running in a Windows environment. Perhaps even that
4106   // decision should be made in the driver as well though.
4107   unsigned DwarfVersion = 0;
4108   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4109   // These two are potentially updated by AddClangCLArgs.
4110   enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4111       CodeGenOptions::NoDebugInfo;
4112   bool EmitCodeView = false;
4113
4114   // Add clang-cl arguments.
4115   if (getToolChain().getDriver().IsCLMode())
4116     AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4117
4118   // Pass the linker version in use.
4119   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4120     CmdArgs.push_back("-target-linker-version");
4121     CmdArgs.push_back(A->getValue());
4122   }
4123
4124   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4125     CmdArgs.push_back("-momit-leaf-frame-pointer");
4126
4127   // Explicitly error on some things we know we don't support and can't just
4128   // ignore.
4129   types::ID InputType = Input.getType();
4130   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4131     Arg *Unsupported;
4132     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4133         getToolChain().getArch() == llvm::Triple::x86) {
4134       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4135           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4136         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4137             << Unsupported->getOption().getName();
4138     }
4139   }
4140
4141   Args.AddAllArgs(CmdArgs, options::OPT_v);
4142   Args.AddLastArg(CmdArgs, options::OPT_H);
4143   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4144     CmdArgs.push_back("-header-include-file");
4145     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4146                                                : "-");
4147   }
4148   Args.AddLastArg(CmdArgs, options::OPT_P);
4149   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4150
4151   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4152     CmdArgs.push_back("-diagnostic-log-file");
4153     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4154                                                  : "-");
4155   }
4156
4157   Args.ClaimAllArgs(options::OPT_g_Group);
4158   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4159   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4160     // If the last option explicitly specified a debug-info level, use it.
4161     if (A->getOption().matches(options::OPT_gN_Group)) {
4162       DebugInfoKind = DebugLevelToInfoKind(*A);
4163       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4164       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4165       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4166       if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4167           A->getIndex() > SplitDwarfArg->getIndex())
4168         SplitDwarfArg = nullptr;
4169     } else
4170       // For any other 'g' option, use Limited.
4171       DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4172   }
4173
4174   // If a debugger tuning argument appeared, remember it.
4175   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4176                                options::OPT_ggdbN_Group)) {
4177     if (A->getOption().matches(options::OPT_glldb))
4178       DebuggerTuning = llvm::DebuggerKind::LLDB;
4179     else if (A->getOption().matches(options::OPT_gsce))
4180       DebuggerTuning = llvm::DebuggerKind::SCE;
4181     else
4182       DebuggerTuning = llvm::DebuggerKind::GDB;
4183   }
4184
4185   // If a -gdwarf argument appeared, remember it.
4186   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4187                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4188     DwarfVersion = DwarfVersionNum(A->getSpelling());
4189
4190   // Forward -gcodeview.
4191   // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4192   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4193     // DwarfVersion remains at 0 if no explicit choice was made.
4194     CmdArgs.push_back("-gcodeview");
4195   } else if (DwarfVersion == 0 &&
4196              DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4197     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4198   }
4199
4200   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4201   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4202
4203   // PS4 defaults to no column info
4204   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4205                    /*Default=*/ !IsPS4CPU))
4206     CmdArgs.push_back("-dwarf-column-info");
4207
4208   // FIXME: Move backend command line options to the module.
4209   if (Args.hasArg(options::OPT_gmodules)) {
4210     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4211     CmdArgs.push_back("-dwarf-ext-refs");
4212     CmdArgs.push_back("-fmodule-format=obj");
4213   }
4214
4215   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4216   // splitting and extraction.
4217   // FIXME: Currently only works on Linux.
4218   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4219     DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4220     CmdArgs.push_back("-backend-option");
4221     CmdArgs.push_back("-split-dwarf=Enable");
4222   }
4223
4224   // After we've dealt with all combinations of things that could
4225   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4226   // figure out if we need to "upgrade" it to standalone debug info.
4227   // We parse these two '-f' options whether or not they will be used,
4228   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4229   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4230                                     options::OPT_fno_standalone_debug,
4231                                     getToolChain().GetDefaultStandaloneDebug());
4232   if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4233     DebugInfoKind = CodeGenOptions::FullDebugInfo;
4234   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4235                           DebuggerTuning);
4236
4237   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4238   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4239     CmdArgs.push_back("-backend-option");
4240     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4241   }
4242
4243   // -gdwarf-aranges turns on the emission of the aranges section in the
4244   // backend.
4245   // Always enabled on the PS4.
4246   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4247     CmdArgs.push_back("-backend-option");
4248     CmdArgs.push_back("-generate-arange-section");
4249   }
4250
4251   if (Args.hasFlag(options::OPT_fdebug_types_section,
4252                    options::OPT_fno_debug_types_section, false)) {
4253     CmdArgs.push_back("-backend-option");
4254     CmdArgs.push_back("-generate-type-units");
4255   }
4256
4257   // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4258   // default.
4259   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4260                              Triple.getArch() == llvm::Triple::wasm32 ||
4261                              Triple.getArch() == llvm::Triple::wasm64;
4262
4263   if (Args.hasFlag(options::OPT_ffunction_sections,
4264                    options::OPT_fno_function_sections, UseSeparateSections)) {
4265     CmdArgs.push_back("-ffunction-sections");
4266   }
4267
4268   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4269                    UseSeparateSections)) {
4270     CmdArgs.push_back("-fdata-sections");
4271   }
4272
4273   if (!Args.hasFlag(options::OPT_funique_section_names,
4274                     options::OPT_fno_unique_section_names, true))
4275     CmdArgs.push_back("-fno-unique-section-names");
4276
4277   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4278
4279   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4280
4281   // Add runtime flag for PS4 when PGO or Coverage are enabled.
4282   if (getToolChain().getTriple().isPS4CPU())
4283     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4284
4285   // Pass options for controlling the default header search paths.
4286   if (Args.hasArg(options::OPT_nostdinc)) {
4287     CmdArgs.push_back("-nostdsysteminc");
4288     CmdArgs.push_back("-nobuiltininc");
4289   } else {
4290     if (Args.hasArg(options::OPT_nostdlibinc))
4291       CmdArgs.push_back("-nostdsysteminc");
4292     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4293     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4294   }
4295
4296   // Pass the path to compiler resource files.
4297   CmdArgs.push_back("-resource-dir");
4298   CmdArgs.push_back(D.ResourceDir.c_str());
4299
4300   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4301
4302   bool ARCMTEnabled = false;
4303   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4304     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4305                                        options::OPT_ccc_arcmt_modify,
4306                                        options::OPT_ccc_arcmt_migrate)) {
4307       ARCMTEnabled = true;
4308       switch (A->getOption().getID()) {
4309       default:
4310         llvm_unreachable("missed a case");
4311       case options::OPT_ccc_arcmt_check:
4312         CmdArgs.push_back("-arcmt-check");
4313         break;
4314       case options::OPT_ccc_arcmt_modify:
4315         CmdArgs.push_back("-arcmt-modify");
4316         break;
4317       case options::OPT_ccc_arcmt_migrate:
4318         CmdArgs.push_back("-arcmt-migrate");
4319         CmdArgs.push_back("-mt-migrate-directory");
4320         CmdArgs.push_back(A->getValue());
4321
4322         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4323         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4324         break;
4325       }
4326     }
4327   } else {
4328     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4329     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4330     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4331   }
4332
4333   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4334     if (ARCMTEnabled) {
4335       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4336                                                       << "-ccc-arcmt-migrate";
4337     }
4338     CmdArgs.push_back("-mt-migrate-directory");
4339     CmdArgs.push_back(A->getValue());
4340
4341     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4342                      options::OPT_objcmt_migrate_subscripting,
4343                      options::OPT_objcmt_migrate_property)) {
4344       // None specified, means enable them all.
4345       CmdArgs.push_back("-objcmt-migrate-literals");
4346       CmdArgs.push_back("-objcmt-migrate-subscripting");
4347       CmdArgs.push_back("-objcmt-migrate-property");
4348     } else {
4349       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4350       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4351       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4352     }
4353   } else {
4354     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4355     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4356     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4357     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4358     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4359     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4360     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4361     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4362     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4363     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4364     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4365     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4366     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4367     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4368     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4369     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4370   }
4371
4372   // Add preprocessing options like -I, -D, etc. if we are using the
4373   // preprocessor.
4374   //
4375   // FIXME: Support -fpreprocessed
4376   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4377     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4378                             AuxToolChain);
4379
4380   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4381   // that "The compiler can only warn and ignore the option if not recognized".
4382   // When building with ccache, it will pass -D options to clang even on
4383   // preprocessed inputs and configure concludes that -fPIC is not supported.
4384   Args.ClaimAllArgs(options::OPT_D);
4385
4386   // Manually translate -O4 to -O3; let clang reject others.
4387   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4388     if (A->getOption().matches(options::OPT_O4)) {
4389       CmdArgs.push_back("-O3");
4390       D.Diag(diag::warn_O4_is_O3);
4391     } else {
4392       A->render(Args, CmdArgs);
4393     }
4394   }
4395
4396   // Warn about ignored options to clang.
4397   for (const Arg *A :
4398        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4399     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4400     A->claim();
4401   }
4402
4403   claimNoWarnArgs(Args);
4404
4405   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4406   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4407   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4408     CmdArgs.push_back("-pedantic");
4409   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4410   Args.AddLastArg(CmdArgs, options::OPT_w);
4411
4412   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4413   // (-ansi is equivalent to -std=c89 or -std=c++98).
4414   //
4415   // If a std is supplied, only add -trigraphs if it follows the
4416   // option.
4417   bool ImplyVCPPCXXVer = false;
4418   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4419     if (Std->getOption().matches(options::OPT_ansi))
4420       if (types::isCXX(InputType))
4421         CmdArgs.push_back("-std=c++98");
4422       else
4423         CmdArgs.push_back("-std=c89");
4424     else
4425       Std->render(Args, CmdArgs);
4426
4427     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4428     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4429                                  options::OPT_ftrigraphs,
4430                                  options::OPT_fno_trigraphs))
4431       if (A != Std)
4432         A->render(Args, CmdArgs);
4433   } else {
4434     // Honor -std-default.
4435     //
4436     // FIXME: Clang doesn't correctly handle -std= when the input language
4437     // doesn't match. For the time being just ignore this for C++ inputs;
4438     // eventually we want to do all the standard defaulting here instead of
4439     // splitting it between the driver and clang -cc1.
4440     if (!types::isCXX(InputType))
4441       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4442                                 /*Joined=*/true);
4443     else if (IsWindowsMSVC)
4444       ImplyVCPPCXXVer = true;
4445
4446     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4447                     options::OPT_fno_trigraphs);
4448   }
4449
4450   // GCC's behavior for -Wwrite-strings is a bit strange:
4451   //  * In C, this "warning flag" changes the types of string literals from
4452   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4453   //    for the discarded qualifier.
4454   //  * In C++, this is just a normal warning flag.
4455   //
4456   // Implementing this warning correctly in C is hard, so we follow GCC's
4457   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4458   // a non-const char* in C, rather than using this crude hack.
4459   if (!types::isCXX(InputType)) {
4460     // FIXME: This should behave just like a warning flag, and thus should also
4461     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4462     Arg *WriteStrings =
4463         Args.getLastArg(options::OPT_Wwrite_strings,
4464                         options::OPT_Wno_write_strings, options::OPT_w);
4465     if (WriteStrings &&
4466         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4467       CmdArgs.push_back("-fconst-strings");
4468   }
4469
4470   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4471   // during C++ compilation, which it is by default. GCC keeps this define even
4472   // in the presence of '-w', match this behavior bug-for-bug.
4473   if (types::isCXX(InputType) &&
4474       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4475                    true)) {
4476     CmdArgs.push_back("-fdeprecated-macro");
4477   }
4478
4479   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4480   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4481     if (Asm->getOption().matches(options::OPT_fasm))
4482       CmdArgs.push_back("-fgnu-keywords");
4483     else
4484       CmdArgs.push_back("-fno-gnu-keywords");
4485   }
4486
4487   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4488     CmdArgs.push_back("-fno-dwarf-directory-asm");
4489
4490   if (ShouldDisableAutolink(Args, getToolChain()))
4491     CmdArgs.push_back("-fno-autolink");
4492
4493   // Add in -fdebug-compilation-dir if necessary.
4494   addDebugCompDirArg(Args, CmdArgs);
4495
4496   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4497     StringRef Map = A->getValue();
4498     if (Map.find('=') == StringRef::npos)
4499       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4500     else
4501       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4502     A->claim();
4503   }
4504
4505   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4506                                options::OPT_ftemplate_depth_EQ)) {
4507     CmdArgs.push_back("-ftemplate-depth");
4508     CmdArgs.push_back(A->getValue());
4509   }
4510
4511   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4512     CmdArgs.push_back("-foperator-arrow-depth");
4513     CmdArgs.push_back(A->getValue());
4514   }
4515
4516   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4517     CmdArgs.push_back("-fconstexpr-depth");
4518     CmdArgs.push_back(A->getValue());
4519   }
4520
4521   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4522     CmdArgs.push_back("-fconstexpr-steps");
4523     CmdArgs.push_back(A->getValue());
4524   }
4525
4526   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4527     CmdArgs.push_back("-fbracket-depth");
4528     CmdArgs.push_back(A->getValue());
4529   }
4530
4531   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4532                                options::OPT_Wlarge_by_value_copy_def)) {
4533     if (A->getNumValues()) {
4534       StringRef bytes = A->getValue();
4535       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4536     } else
4537       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4538   }
4539
4540   if (Args.hasArg(options::OPT_relocatable_pch))
4541     CmdArgs.push_back("-relocatable-pch");
4542
4543   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4544     CmdArgs.push_back("-fconstant-string-class");
4545     CmdArgs.push_back(A->getValue());
4546   }
4547
4548   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4549     CmdArgs.push_back("-ftabstop");
4550     CmdArgs.push_back(A->getValue());
4551   }
4552
4553   CmdArgs.push_back("-ferror-limit");
4554   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4555     CmdArgs.push_back(A->getValue());
4556   else
4557     CmdArgs.push_back("19");
4558
4559   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4560     CmdArgs.push_back("-fmacro-backtrace-limit");
4561     CmdArgs.push_back(A->getValue());
4562   }
4563
4564   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4565     CmdArgs.push_back("-ftemplate-backtrace-limit");
4566     CmdArgs.push_back(A->getValue());
4567   }
4568
4569   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4570     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4571     CmdArgs.push_back(A->getValue());
4572   }
4573
4574   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4575     CmdArgs.push_back("-fspell-checking-limit");
4576     CmdArgs.push_back(A->getValue());
4577   }
4578
4579   // Pass -fmessage-length=.
4580   CmdArgs.push_back("-fmessage-length");
4581   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4582     CmdArgs.push_back(A->getValue());
4583   } else {
4584     // If -fmessage-length=N was not specified, determine whether this is a
4585     // terminal and, if so, implicitly define -fmessage-length appropriately.
4586     unsigned N = llvm::sys::Process::StandardErrColumns();
4587     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4588   }
4589
4590   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4591   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4592                                      options::OPT_fvisibility_ms_compat)) {
4593     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4594       CmdArgs.push_back("-fvisibility");
4595       CmdArgs.push_back(A->getValue());
4596     } else {
4597       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4598       CmdArgs.push_back("-fvisibility");
4599       CmdArgs.push_back("hidden");
4600       CmdArgs.push_back("-ftype-visibility");
4601       CmdArgs.push_back("default");
4602     }
4603   }
4604
4605   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4606
4607   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4608
4609   // -fhosted is default.
4610   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4611       KernelOrKext)
4612     CmdArgs.push_back("-ffreestanding");
4613
4614   // Forward -f (flag) options which we can pass directly.
4615   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4616   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4617   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4618   // Emulated TLS is enabled by default on Android, and can be enabled manually
4619   // with -femulated-tls.
4620   bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
4621   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4622                    EmulatedTLSDefault))
4623     CmdArgs.push_back("-femulated-tls");
4624   // AltiVec-like language extensions aren't relevant for assembling.
4625   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4626     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4627     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4628   }
4629   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4630   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4631
4632   // Forward flags for OpenMP
4633   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4634                    options::OPT_fno_openmp, false))
4635     switch (getOpenMPRuntime(getToolChain(), Args)) {
4636     case OMPRT_OMP:
4637     case OMPRT_IOMP5:
4638       // Clang can generate useful OpenMP code for these two runtime libraries.
4639       CmdArgs.push_back("-fopenmp");
4640
4641       // If no option regarding the use of TLS in OpenMP codegeneration is
4642       // given, decide a default based on the target. Otherwise rely on the
4643       // options and pass the right information to the frontend.
4644       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4645                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4646         CmdArgs.push_back("-fnoopenmp-use-tls");
4647       break;
4648     default:
4649       // By default, if Clang doesn't know how to generate useful OpenMP code
4650       // for a specific runtime library, we just don't pass the '-fopenmp' flag
4651       // down to the actual compilation.
4652       // FIXME: It would be better to have a mode which *only* omits IR
4653       // generation based on the OpenMP support so that we get consistent
4654       // semantic analysis, etc.
4655       break;
4656     }
4657
4658   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4659   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4660
4661   // Report an error for -faltivec on anything other than PowerPC.
4662   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4663     const llvm::Triple::ArchType Arch = getToolChain().getArch();
4664     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4665           Arch == llvm::Triple::ppc64le))
4666       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4667                                                        << "ppc/ppc64/ppc64le";
4668   }
4669
4670   // -fzvector is incompatible with -faltivec.
4671   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4672     if (Args.hasArg(options::OPT_faltivec))
4673       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4674                                                       << "-faltivec";
4675
4676   if (getToolChain().SupportsProfiling())
4677     Args.AddLastArg(CmdArgs, options::OPT_pg);
4678
4679   // -flax-vector-conversions is default.
4680   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4681                     options::OPT_fno_lax_vector_conversions))
4682     CmdArgs.push_back("-fno-lax-vector-conversions");
4683
4684   if (Args.getLastArg(options::OPT_fapple_kext) ||
4685       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4686     CmdArgs.push_back("-fapple-kext");
4687
4688   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4689   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4690   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4691   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4692   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4693
4694   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4695     CmdArgs.push_back("-ftrapv-handler");
4696     CmdArgs.push_back(A->getValue());
4697   }
4698
4699   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4700
4701   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4702   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4703   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4704     if (A->getOption().matches(options::OPT_fwrapv))
4705       CmdArgs.push_back("-fwrapv");
4706   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4707                                       options::OPT_fno_strict_overflow)) {
4708     if (A->getOption().matches(options::OPT_fno_strict_overflow))
4709       CmdArgs.push_back("-fwrapv");
4710   }
4711
4712   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4713                                options::OPT_fno_reroll_loops))
4714     if (A->getOption().matches(options::OPT_freroll_loops))
4715       CmdArgs.push_back("-freroll-loops");
4716
4717   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4718   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4719                   options::OPT_fno_unroll_loops);
4720
4721   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4722
4723   // -stack-protector=0 is default.
4724   unsigned StackProtectorLevel = 0;
4725   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4726     Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4727     Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4728     Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4729     Args.ClaimAllArgs(options::OPT_fstack_protector);
4730   } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4731                                       options::OPT_fstack_protector_all,
4732                                       options::OPT_fstack_protector_strong,
4733                                       options::OPT_fstack_protector)) {
4734     if (A->getOption().matches(options::OPT_fstack_protector)) {
4735       StackProtectorLevel = std::max<unsigned>(
4736           LangOptions::SSPOn,
4737           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4738     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4739       StackProtectorLevel = LangOptions::SSPStrong;
4740     else if (A->getOption().matches(options::OPT_fstack_protector_all))
4741       StackProtectorLevel = LangOptions::SSPReq;
4742   } else {
4743     StackProtectorLevel =
4744         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4745   }
4746   if (StackProtectorLevel) {
4747     CmdArgs.push_back("-stack-protector");
4748     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4749   }
4750
4751   // --param ssp-buffer-size=
4752   for (const Arg *A : Args.filtered(options::OPT__param)) {
4753     StringRef Str(A->getValue());
4754     if (Str.startswith("ssp-buffer-size=")) {
4755       if (StackProtectorLevel) {
4756         CmdArgs.push_back("-stack-protector-buffer-size");
4757         // FIXME: Verify the argument is a valid integer.
4758         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4759       }
4760       A->claim();
4761     }
4762   }
4763
4764   // Translate -mstackrealign
4765   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4766                    false))
4767     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4768
4769   if (Args.hasArg(options::OPT_mstack_alignment)) {
4770     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4771     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4772   }
4773
4774   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4775     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4776
4777     if (!Size.empty())
4778       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4779     else
4780       CmdArgs.push_back("-mstack-probe-size=0");
4781   }
4782
4783   switch (getToolChain().getArch()) {
4784   case llvm::Triple::aarch64:
4785   case llvm::Triple::aarch64_be:
4786   case llvm::Triple::arm:
4787   case llvm::Triple::armeb:
4788   case llvm::Triple::thumb:
4789   case llvm::Triple::thumbeb:
4790     CmdArgs.push_back("-fallow-half-arguments-and-returns");
4791     break;
4792
4793   default:
4794     break;
4795   }
4796
4797   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4798                                options::OPT_mno_restrict_it)) {
4799     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4800       CmdArgs.push_back("-backend-option");
4801       CmdArgs.push_back("-arm-restrict-it");
4802     } else {
4803       CmdArgs.push_back("-backend-option");
4804       CmdArgs.push_back("-arm-no-restrict-it");
4805     }
4806   } else if (Triple.isOSWindows() &&
4807              (Triple.getArch() == llvm::Triple::arm ||
4808               Triple.getArch() == llvm::Triple::thumb)) {
4809     // Windows on ARM expects restricted IT blocks
4810     CmdArgs.push_back("-backend-option");
4811     CmdArgs.push_back("-arm-restrict-it");
4812   }
4813
4814   // Forward -f options with positive and negative forms; we translate
4815   // these by hand.
4816   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4817     StringRef fname = A->getValue();
4818     if (!llvm::sys::fs::exists(fname))
4819       D.Diag(diag::err_drv_no_such_file) << fname;
4820     else
4821       A->render(Args, CmdArgs);
4822   }
4823
4824   // -fbuiltin is default unless -mkernel is used.
4825   bool UseBuiltins =
4826       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4827                    !Args.hasArg(options::OPT_mkernel));
4828   if (!UseBuiltins)
4829     CmdArgs.push_back("-fno-builtin");
4830
4831   // -ffreestanding implies -fno-builtin.
4832   if (Args.hasArg(options::OPT_ffreestanding))
4833     UseBuiltins = false;
4834
4835   // Process the -fno-builtin-* options.
4836   for (const auto &Arg : Args) {
4837     const Option &O = Arg->getOption();
4838     if (!O.matches(options::OPT_fno_builtin_))
4839       continue;
4840
4841     Arg->claim();
4842     // If -fno-builtin is specified, then there's no need to pass the option to
4843     // the frontend.
4844     if (!UseBuiltins)
4845       continue;
4846
4847     StringRef FuncName = Arg->getValue();
4848     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
4849   }
4850
4851   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4852                     options::OPT_fno_assume_sane_operator_new))
4853     CmdArgs.push_back("-fno-assume-sane-operator-new");
4854
4855   // -fblocks=0 is default.
4856   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4857                    getToolChain().IsBlocksDefault()) ||
4858       (Args.hasArg(options::OPT_fgnu_runtime) &&
4859        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4860        !Args.hasArg(options::OPT_fno_blocks))) {
4861     CmdArgs.push_back("-fblocks");
4862
4863     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4864         !getToolChain().hasBlocksRuntime())
4865       CmdArgs.push_back("-fblocks-runtime-optional");
4866   }
4867
4868   // -fmodules enables the use of precompiled modules (off by default).
4869   // Users can pass -fno-cxx-modules to turn off modules support for
4870   // C++/Objective-C++ programs.
4871   bool HaveModules = false;
4872   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4873     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4874                                      options::OPT_fno_cxx_modules, true);
4875     if (AllowedInCXX || !types::isCXX(InputType)) {
4876       CmdArgs.push_back("-fmodules");
4877       HaveModules = true;
4878     }
4879   }
4880
4881   // -fmodule-maps enables implicit reading of module map files. By default,
4882   // this is enabled if we are using precompiled modules.
4883   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4884                    options::OPT_fno_implicit_module_maps, HaveModules)) {
4885     CmdArgs.push_back("-fimplicit-module-maps");
4886   }
4887
4888   // -fmodules-decluse checks that modules used are declared so (off by
4889   // default).
4890   if (Args.hasFlag(options::OPT_fmodules_decluse,
4891                    options::OPT_fno_modules_decluse, false)) {
4892     CmdArgs.push_back("-fmodules-decluse");
4893   }
4894
4895   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4896   // all #included headers are part of modules.
4897   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4898                    options::OPT_fno_modules_strict_decluse, false)) {
4899     CmdArgs.push_back("-fmodules-strict-decluse");
4900   }
4901
4902   // -fno-implicit-modules turns off implicitly compiling modules on demand.
4903   if (!Args.hasFlag(options::OPT_fimplicit_modules,
4904                     options::OPT_fno_implicit_modules)) {
4905     CmdArgs.push_back("-fno-implicit-modules");
4906   }
4907
4908   // -fmodule-name specifies the module that is currently being built (or
4909   // used for header checking by -fmodule-maps).
4910   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4911
4912   // -fmodule-map-file can be used to specify files containing module
4913   // definitions.
4914   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4915
4916   // -fmodule-file can be used to specify files containing precompiled modules.
4917   if (HaveModules)
4918     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4919   else
4920     Args.ClaimAllArgs(options::OPT_fmodule_file);
4921
4922   // -fmodule-cache-path specifies where our implicitly-built module files
4923   // should be written.
4924   SmallString<128> Path;
4925   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4926     Path = A->getValue();
4927   if (HaveModules) {
4928     if (C.isForDiagnostics()) {
4929       // When generating crash reports, we want to emit the modules along with
4930       // the reproduction sources, so we ignore any provided module path.
4931       Path = Output.getFilename();
4932       llvm::sys::path::replace_extension(Path, ".cache");
4933       llvm::sys::path::append(Path, "modules");
4934     } else if (Path.empty()) {
4935       // No module path was provided: use the default.
4936       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4937       llvm::sys::path::append(Path, "org.llvm.clang.");
4938       appendUserToPath(Path);
4939       llvm::sys::path::append(Path, "ModuleCache");
4940     }
4941     const char Arg[] = "-fmodules-cache-path=";
4942     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4943     CmdArgs.push_back(Args.MakeArgString(Path));
4944   }
4945
4946   // When building modules and generating crashdumps, we need to dump a module
4947   // dependency VFS alongside the output.
4948   if (HaveModules && C.isForDiagnostics()) {
4949     SmallString<128> VFSDir(Output.getFilename());
4950     llvm::sys::path::replace_extension(VFSDir, ".cache");
4951     // Add the cache directory as a temp so the crash diagnostics pick it up.
4952     C.addTempFile(Args.MakeArgString(VFSDir));
4953
4954     llvm::sys::path::append(VFSDir, "vfs");
4955     CmdArgs.push_back("-module-dependency-dir");
4956     CmdArgs.push_back(Args.MakeArgString(VFSDir));
4957   }
4958
4959   if (HaveModules)
4960     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4961
4962   // Pass through all -fmodules-ignore-macro arguments.
4963   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4964   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4965   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4966
4967   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4968
4969   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4970     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4971       D.Diag(diag::err_drv_argument_not_allowed_with)
4972           << A->getAsString(Args) << "-fbuild-session-timestamp";
4973
4974     llvm::sys::fs::file_status Status;
4975     if (llvm::sys::fs::status(A->getValue(), Status))
4976       D.Diag(diag::err_drv_no_such_file) << A->getValue();
4977     CmdArgs.push_back(Args.MakeArgString(
4978         "-fbuild-session-timestamp=" +
4979         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4980   }
4981
4982   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4983     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4984                          options::OPT_fbuild_session_file))
4985       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4986
4987     Args.AddLastArg(CmdArgs,
4988                     options::OPT_fmodules_validate_once_per_build_session);
4989   }
4990
4991   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4992
4993   // -faccess-control is default.
4994   if (Args.hasFlag(options::OPT_fno_access_control,
4995                    options::OPT_faccess_control, false))
4996     CmdArgs.push_back("-fno-access-control");
4997
4998   // -felide-constructors is the default.
4999   if (Args.hasFlag(options::OPT_fno_elide_constructors,
5000                    options::OPT_felide_constructors, false))
5001     CmdArgs.push_back("-fno-elide-constructors");
5002
5003   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5004
5005   if (KernelOrKext || (types::isCXX(InputType) &&
5006                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5007                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
5008     CmdArgs.push_back("-fno-rtti");
5009
5010   // -fshort-enums=0 is default for all architectures except Hexagon.
5011   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5012                    getToolChain().getArch() == llvm::Triple::hexagon))
5013     CmdArgs.push_back("-fshort-enums");
5014
5015   // -fsigned-char is default.
5016   if (Arg *A = Args.getLastArg(
5017           options::OPT_fsigned_char, options::OPT_fno_signed_char,
5018           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5019     if (A->getOption().matches(options::OPT_funsigned_char) ||
5020         A->getOption().matches(options::OPT_fno_signed_char)) {
5021       CmdArgs.push_back("-fno-signed-char");
5022     }
5023   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5024     CmdArgs.push_back("-fno-signed-char");
5025   }
5026
5027   // -fuse-cxa-atexit is default.
5028   if (!Args.hasFlag(
5029           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5030           !IsWindowsCygnus && !IsWindowsGNU &&
5031               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5032               getToolChain().getArch() != llvm::Triple::hexagon &&
5033               getToolChain().getArch() != llvm::Triple::xcore &&
5034               ((getToolChain().getTriple().getVendor() !=
5035                 llvm::Triple::MipsTechnologies) ||
5036                getToolChain().getTriple().hasEnvironment())) ||
5037       KernelOrKext)
5038     CmdArgs.push_back("-fno-use-cxa-atexit");
5039
5040   // -fms-extensions=0 is default.
5041   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5042                    IsWindowsMSVC))
5043     CmdArgs.push_back("-fms-extensions");
5044
5045   // -fno-use-line-directives is default.
5046   if (Args.hasFlag(options::OPT_fuse_line_directives,
5047                    options::OPT_fno_use_line_directives, false))
5048     CmdArgs.push_back("-fuse-line-directives");
5049
5050   // -fms-compatibility=0 is default.
5051   if (Args.hasFlag(options::OPT_fms_compatibility,
5052                    options::OPT_fno_ms_compatibility,
5053                    (IsWindowsMSVC &&
5054                     Args.hasFlag(options::OPT_fms_extensions,
5055                                  options::OPT_fno_ms_extensions, true))))
5056     CmdArgs.push_back("-fms-compatibility");
5057
5058   // -fms-compatibility-version=18.00 is default.
5059   VersionTuple MSVT = visualstudio::getMSVCVersion(
5060       &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
5061   if (!MSVT.empty())
5062     CmdArgs.push_back(
5063         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5064
5065   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5066   if (ImplyVCPPCXXVer) {
5067     if (IsMSVC2015Compatible)
5068       CmdArgs.push_back("-std=c++14");
5069     else
5070       CmdArgs.push_back("-std=c++11");
5071   }
5072
5073   // -fno-borland-extensions is default.
5074   if (Args.hasFlag(options::OPT_fborland_extensions,
5075                    options::OPT_fno_borland_extensions, false))
5076     CmdArgs.push_back("-fborland-extensions");
5077
5078   // -fno-declspec is default, except for PS4.
5079   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5080                    getToolChain().getTriple().isPS4()))
5081     CmdArgs.push_back("-fdeclspec");
5082   else if (Args.hasArg(options::OPT_fno_declspec))
5083     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5084
5085   // -fthreadsafe-static is default, except for MSVC compatibility versions less
5086   // than 19.
5087   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5088                     options::OPT_fno_threadsafe_statics,
5089                     !IsWindowsMSVC || IsMSVC2015Compatible))
5090     CmdArgs.push_back("-fno-threadsafe-statics");
5091
5092   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5093   // needs it.
5094   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5095                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5096     CmdArgs.push_back("-fdelayed-template-parsing");
5097
5098   // -fgnu-keywords default varies depending on language; only pass if
5099   // specified.
5100   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5101                                options::OPT_fno_gnu_keywords))
5102     A->render(Args, CmdArgs);
5103
5104   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5105                    false))
5106     CmdArgs.push_back("-fgnu89-inline");
5107
5108   if (Args.hasArg(options::OPT_fno_inline))
5109     CmdArgs.push_back("-fno-inline");
5110
5111   if (Args.hasArg(options::OPT_fno_inline_functions))
5112     CmdArgs.push_back("-fno-inline-functions");
5113
5114   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5115
5116   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5117   // legacy is the default. Except for deployment taget of 10.5,
5118   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5119   // gets ignored silently.
5120   if (objcRuntime.isNonFragile()) {
5121     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5122                       options::OPT_fno_objc_legacy_dispatch,
5123                       objcRuntime.isLegacyDispatchDefaultForArch(
5124                           getToolChain().getArch()))) {
5125       if (getToolChain().UseObjCMixedDispatch())
5126         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5127       else
5128         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5129     }
5130   }
5131
5132   // When ObjectiveC legacy runtime is in effect on MacOSX,
5133   // turn on the option to do Array/Dictionary subscripting
5134   // by default.
5135   if (getToolChain().getArch() == llvm::Triple::x86 &&
5136       getToolChain().getTriple().isMacOSX() &&
5137       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5138       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5139       objcRuntime.isNeXTFamily())
5140     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5141
5142   // -fencode-extended-block-signature=1 is default.
5143   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5144     CmdArgs.push_back("-fencode-extended-block-signature");
5145   }
5146
5147   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5148   // NOTE: This logic is duplicated in ToolChains.cpp.
5149   bool ARC = isObjCAutoRefCount(Args);
5150   if (ARC) {
5151     getToolChain().CheckObjCARC();
5152
5153     CmdArgs.push_back("-fobjc-arc");
5154
5155     // FIXME: It seems like this entire block, and several around it should be
5156     // wrapped in isObjC, but for now we just use it here as this is where it
5157     // was being used previously.
5158     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5159       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5160         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5161       else
5162         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5163     }
5164
5165     // Allow the user to enable full exceptions code emission.
5166     // We define off for Objective-CC, on for Objective-C++.
5167     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5168                      options::OPT_fno_objc_arc_exceptions,
5169                      /*default*/ types::isCXX(InputType)))
5170       CmdArgs.push_back("-fobjc-arc-exceptions");
5171
5172   }
5173
5174   // -fobjc-infer-related-result-type is the default, except in the Objective-C
5175   // rewriter.
5176   if (rewriteKind != RK_None)
5177     CmdArgs.push_back("-fno-objc-infer-related-result-type");
5178
5179   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5180   // takes precedence.
5181   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5182   if (!GCArg)
5183     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5184   if (GCArg) {
5185     if (ARC) {
5186       D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5187     } else if (getToolChain().SupportsObjCGC()) {
5188       GCArg->render(Args, CmdArgs);
5189     } else {
5190       // FIXME: We should move this to a hard error.
5191       D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5192     }
5193   }
5194
5195   // Pass down -fobjc-weak or -fno-objc-weak if present.
5196   if (types::isObjC(InputType)) {
5197     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5198                                    options::OPT_fno_objc_weak);
5199     if (!WeakArg) {
5200       // nothing to do
5201     } else if (GCArg) {
5202       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5203         D.Diag(diag::err_objc_weak_with_gc);
5204     } else if (!objcRuntime.allowsWeak()) {
5205       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5206         D.Diag(diag::err_objc_weak_unsupported);
5207     } else {
5208       WeakArg->render(Args, CmdArgs);
5209     }
5210   }
5211
5212   if (Args.hasFlag(options::OPT_fapplication_extension,
5213                    options::OPT_fno_application_extension, false))
5214     CmdArgs.push_back("-fapplication-extension");
5215
5216   // Handle GCC-style exception args.
5217   if (!C.getDriver().IsCLMode())
5218     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5219                      CmdArgs);
5220
5221   if (getToolChain().UseSjLjExceptions(Args))
5222     CmdArgs.push_back("-fsjlj-exceptions");
5223
5224   // C++ "sane" operator new.
5225   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5226                     options::OPT_fno_assume_sane_operator_new))
5227     CmdArgs.push_back("-fno-assume-sane-operator-new");
5228
5229   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5230   // most platforms.
5231   if (Args.hasFlag(options::OPT_fsized_deallocation,
5232                    options::OPT_fno_sized_deallocation, false))
5233     CmdArgs.push_back("-fsized-deallocation");
5234
5235   // -fconstant-cfstrings is default, and may be subject to argument translation
5236   // on Darwin.
5237   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5238                     options::OPT_fno_constant_cfstrings) ||
5239       !Args.hasFlag(options::OPT_mconstant_cfstrings,
5240                     options::OPT_mno_constant_cfstrings))
5241     CmdArgs.push_back("-fno-constant-cfstrings");
5242
5243   // -fshort-wchar default varies depending on platform; only
5244   // pass if specified.
5245   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5246                                options::OPT_fno_short_wchar))
5247     A->render(Args, CmdArgs);
5248
5249   // -fno-pascal-strings is default, only pass non-default.
5250   if (Args.hasFlag(options::OPT_fpascal_strings,
5251                    options::OPT_fno_pascal_strings, false))
5252     CmdArgs.push_back("-fpascal-strings");
5253
5254   // Honor -fpack-struct= and -fpack-struct, if given. Note that
5255   // -fno-pack-struct doesn't apply to -fpack-struct=.
5256   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5257     std::string PackStructStr = "-fpack-struct=";
5258     PackStructStr += A->getValue();
5259     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5260   } else if (Args.hasFlag(options::OPT_fpack_struct,
5261                           options::OPT_fno_pack_struct, false)) {
5262     CmdArgs.push_back("-fpack-struct=1");
5263   }
5264
5265   // Handle -fmax-type-align=N and -fno-type-align
5266   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5267   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5268     if (!SkipMaxTypeAlign) {
5269       std::string MaxTypeAlignStr = "-fmax-type-align=";
5270       MaxTypeAlignStr += A->getValue();
5271       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5272     }
5273   } else if (getToolChain().getTriple().isOSDarwin()) {
5274     if (!SkipMaxTypeAlign) {
5275       std::string MaxTypeAlignStr = "-fmax-type-align=16";
5276       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5277     }
5278   }
5279
5280   // -fcommon is the default unless compiling kernel code or the target says so
5281   bool NoCommonDefault =
5282       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5283   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5284                     !NoCommonDefault))
5285     CmdArgs.push_back("-fno-common");
5286
5287   // -fsigned-bitfields is default, and clang doesn't yet support
5288   // -funsigned-bitfields.
5289   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5290                     options::OPT_funsigned_bitfields))
5291     D.Diag(diag::warn_drv_clang_unsupported)
5292         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5293
5294   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5295   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5296     D.Diag(diag::err_drv_clang_unsupported)
5297         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5298
5299   // -finput_charset=UTF-8 is default. Reject others
5300   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5301     StringRef value = inputCharset->getValue();
5302     if (value != "UTF-8")
5303       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5304                                           << value;
5305   }
5306
5307   // -fexec_charset=UTF-8 is default. Reject others
5308   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5309     StringRef value = execCharset->getValue();
5310     if (value != "UTF-8")
5311       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5312                                           << value;
5313   }
5314
5315   // -fcaret-diagnostics is default.
5316   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5317                     options::OPT_fno_caret_diagnostics, true))
5318     CmdArgs.push_back("-fno-caret-diagnostics");
5319
5320   // -fdiagnostics-fixit-info is default, only pass non-default.
5321   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5322                     options::OPT_fno_diagnostics_fixit_info))
5323     CmdArgs.push_back("-fno-diagnostics-fixit-info");
5324
5325   // Enable -fdiagnostics-show-option by default.
5326   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5327                    options::OPT_fno_diagnostics_show_option))
5328     CmdArgs.push_back("-fdiagnostics-show-option");
5329
5330   if (const Arg *A =
5331           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5332     CmdArgs.push_back("-fdiagnostics-show-category");
5333     CmdArgs.push_back(A->getValue());
5334   }
5335
5336   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5337     CmdArgs.push_back("-fdiagnostics-format");
5338     CmdArgs.push_back(A->getValue());
5339   }
5340
5341   if (Arg *A = Args.getLastArg(
5342           options::OPT_fdiagnostics_show_note_include_stack,
5343           options::OPT_fno_diagnostics_show_note_include_stack)) {
5344     if (A->getOption().matches(
5345             options::OPT_fdiagnostics_show_note_include_stack))
5346       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5347     else
5348       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5349   }
5350
5351   // Color diagnostics are the default, unless the terminal doesn't support
5352   // them.
5353   // Support both clang's -f[no-]color-diagnostics and gcc's
5354   // -f[no-]diagnostics-colors[=never|always|auto].
5355   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5356   for (const auto &Arg : Args) {
5357     const Option &O = Arg->getOption();
5358     if (!O.matches(options::OPT_fcolor_diagnostics) &&
5359         !O.matches(options::OPT_fdiagnostics_color) &&
5360         !O.matches(options::OPT_fno_color_diagnostics) &&
5361         !O.matches(options::OPT_fno_diagnostics_color) &&
5362         !O.matches(options::OPT_fdiagnostics_color_EQ))
5363       continue;
5364
5365     Arg->claim();
5366     if (O.matches(options::OPT_fcolor_diagnostics) ||
5367         O.matches(options::OPT_fdiagnostics_color)) {
5368       ShowColors = Colors_On;
5369     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5370                O.matches(options::OPT_fno_diagnostics_color)) {
5371       ShowColors = Colors_Off;
5372     } else {
5373       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5374       StringRef value(Arg->getValue());
5375       if (value == "always")
5376         ShowColors = Colors_On;
5377       else if (value == "never")
5378         ShowColors = Colors_Off;
5379       else if (value == "auto")
5380         ShowColors = Colors_Auto;
5381       else
5382         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5383             << ("-fdiagnostics-color=" + value).str();
5384     }
5385   }
5386   if (ShowColors == Colors_On ||
5387       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5388     CmdArgs.push_back("-fcolor-diagnostics");
5389
5390   if (Args.hasArg(options::OPT_fansi_escape_codes))
5391     CmdArgs.push_back("-fansi-escape-codes");
5392
5393   if (!Args.hasFlag(options::OPT_fshow_source_location,
5394                     options::OPT_fno_show_source_location))
5395     CmdArgs.push_back("-fno-show-source-location");
5396
5397   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5398                     true))
5399     CmdArgs.push_back("-fno-show-column");
5400
5401   if (!Args.hasFlag(options::OPT_fspell_checking,
5402                     options::OPT_fno_spell_checking))
5403     CmdArgs.push_back("-fno-spell-checking");
5404
5405   // -fno-asm-blocks is default.
5406   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5407                    false))
5408     CmdArgs.push_back("-fasm-blocks");
5409
5410   // -fgnu-inline-asm is default.
5411   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5412                     options::OPT_fno_gnu_inline_asm, true))
5413     CmdArgs.push_back("-fno-gnu-inline-asm");
5414
5415   // Enable vectorization per default according to the optimization level
5416   // selected. For optimization levels that want vectorization we use the alias
5417   // option to simplify the hasFlag logic.
5418   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5419   OptSpecifier VectorizeAliasOption =
5420       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5421   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5422                    options::OPT_fno_vectorize, EnableVec))
5423     CmdArgs.push_back("-vectorize-loops");
5424
5425   // -fslp-vectorize is enabled based on the optimization level selected.
5426   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5427   OptSpecifier SLPVectAliasOption =
5428       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5429   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5430                    options::OPT_fno_slp_vectorize, EnableSLPVec))
5431     CmdArgs.push_back("-vectorize-slp");
5432
5433   // -fno-slp-vectorize-aggressive is default.
5434   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5435                    options::OPT_fno_slp_vectorize_aggressive, false))
5436     CmdArgs.push_back("-vectorize-slp-aggressive");
5437
5438   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5439     A->render(Args, CmdArgs);
5440
5441   // -fdollars-in-identifiers default varies depending on platform and
5442   // language; only pass if specified.
5443   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5444                                options::OPT_fno_dollars_in_identifiers)) {
5445     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5446       CmdArgs.push_back("-fdollars-in-identifiers");
5447     else
5448       CmdArgs.push_back("-fno-dollars-in-identifiers");
5449   }
5450
5451   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5452   // practical purposes.
5453   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5454                                options::OPT_fno_unit_at_a_time)) {
5455     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5456       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5457   }
5458
5459   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5460                    options::OPT_fno_apple_pragma_pack, false))
5461     CmdArgs.push_back("-fapple-pragma-pack");
5462
5463   // le32-specific flags:
5464   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
5465   //                     by default.
5466   if (getToolChain().getArch() == llvm::Triple::le32) {
5467     CmdArgs.push_back("-fno-math-builtin");
5468   }
5469
5470 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5471 //
5472 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5473 #if 0
5474   if (getToolChain().getTriple().isOSDarwin() &&
5475       (getToolChain().getArch() == llvm::Triple::arm ||
5476        getToolChain().getArch() == llvm::Triple::thumb)) {
5477     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5478       CmdArgs.push_back("-fno-builtin-strcat");
5479     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5480       CmdArgs.push_back("-fno-builtin-strcpy");
5481   }
5482 #endif
5483
5484   // Enable rewrite includes if the user's asked for it or if we're generating
5485   // diagnostics.
5486   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5487   // nice to enable this when doing a crashdump for modules as well.
5488   if (Args.hasFlag(options::OPT_frewrite_includes,
5489                    options::OPT_fno_rewrite_includes, false) ||
5490       (C.isForDiagnostics() && !HaveModules))
5491     CmdArgs.push_back("-frewrite-includes");
5492
5493   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5494   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5495                                options::OPT_traditional_cpp)) {
5496     if (isa<PreprocessJobAction>(JA))
5497       CmdArgs.push_back("-traditional-cpp");
5498     else
5499       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5500   }
5501
5502   Args.AddLastArg(CmdArgs, options::OPT_dM);
5503   Args.AddLastArg(CmdArgs, options::OPT_dD);
5504
5505   // Handle serialized diagnostics.
5506   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5507     CmdArgs.push_back("-serialize-diagnostic-file");
5508     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5509   }
5510
5511   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5512     CmdArgs.push_back("-fretain-comments-from-system-headers");
5513
5514   // Forward -fcomment-block-commands to -cc1.
5515   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5516   // Forward -fparse-all-comments to -cc1.
5517   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5518
5519   // Turn -fplugin=name.so into -load name.so
5520   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5521     CmdArgs.push_back("-load");
5522     CmdArgs.push_back(A->getValue());
5523     A->claim();
5524   }
5525
5526   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5527   // parser.
5528   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5529   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5530     A->claim();
5531
5532     // We translate this by hand to the -cc1 argument, since nightly test uses
5533     // it and developers have been trained to spell it with -mllvm.
5534     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5535       CmdArgs.push_back("-disable-llvm-optzns");
5536     } else
5537       A->render(Args, CmdArgs);
5538   }
5539
5540   // With -save-temps, we want to save the unoptimized bitcode output from the
5541   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5542   // by the frontend.
5543   if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5544     CmdArgs.push_back("-disable-llvm-passes");
5545
5546   if (Output.getType() == types::TY_Dependencies) {
5547     // Handled with other dependency code.
5548   } else if (Output.isFilename()) {
5549     CmdArgs.push_back("-o");
5550     CmdArgs.push_back(Output.getFilename());
5551   } else {
5552     assert(Output.isNothing() && "Invalid output.");
5553   }
5554
5555   addDashXForInput(Args, Input, CmdArgs);
5556
5557   if (Input.isFilename())
5558     CmdArgs.push_back(Input.getFilename());
5559   else
5560     Input.getInputArg().renderAsInput(Args, CmdArgs);
5561
5562   Args.AddAllArgs(CmdArgs, options::OPT_undef);
5563
5564   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5565
5566   // Optionally embed the -cc1 level arguments into the debug info, for build
5567   // analysis.
5568   if (getToolChain().UseDwarfDebugFlags()) {
5569     ArgStringList OriginalArgs;
5570     for (const auto &Arg : Args)
5571       Arg->render(Args, OriginalArgs);
5572
5573     SmallString<256> Flags;
5574     Flags += Exec;
5575     for (const char *OriginalArg : OriginalArgs) {
5576       SmallString<128> EscapedArg;
5577       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5578       Flags += " ";
5579       Flags += EscapedArg;
5580     }
5581     CmdArgs.push_back("-dwarf-debug-flags");
5582     CmdArgs.push_back(Args.MakeArgString(Flags));
5583   }
5584
5585   // Add the split debug info name to the command lines here so we
5586   // can propagate it to the backend.
5587   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5588                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5589                      isa<BackendJobAction>(JA));
5590   const char *SplitDwarfOut;
5591   if (SplitDwarf) {
5592     CmdArgs.push_back("-split-dwarf-file");
5593     SplitDwarfOut = SplitDebugName(Args, Input);
5594     CmdArgs.push_back(SplitDwarfOut);
5595   }
5596
5597   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5598   // Include them with -fcuda-include-gpubinary.
5599   if (IsCuda && Inputs.size() > 1)
5600     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5601       CmdArgs.push_back("-fcuda-include-gpubinary");
5602       CmdArgs.push_back(I->getFilename());
5603     }
5604
5605   // Finally add the compile command to the compilation.
5606   if (Args.hasArg(options::OPT__SLASH_fallback) &&
5607       Output.getType() == types::TY_Object &&
5608       (InputType == types::TY_C || InputType == types::TY_CXX)) {
5609     auto CLCommand =
5610         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5611     C.addCommand(llvm::make_unique<FallbackCommand>(
5612         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5613   } else {
5614     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5615   }
5616
5617   // Handle the debug info splitting at object creation time if we're
5618   // creating an object.
5619   // TODO: Currently only works on linux with newer objcopy.
5620   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5621     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5622
5623   if (Arg *A = Args.getLastArg(options::OPT_pg))
5624     if (Args.hasArg(options::OPT_fomit_frame_pointer))
5625       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5626                                                       << A->getAsString(Args);
5627
5628   // Claim some arguments which clang supports automatically.
5629
5630   // -fpch-preprocess is used with gcc to add a special marker in the output to
5631   // include the PCH file. Clang's PTH solution is completely transparent, so we
5632   // do not need to deal with it at all.
5633   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5634
5635   // Claim some arguments which clang doesn't support, but we don't
5636   // care to warn the user about.
5637   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5638   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5639
5640   // Disable warnings for clang -E -emit-llvm foo.c
5641   Args.ClaimAllArgs(options::OPT_emit_llvm);
5642 }
5643
5644 /// Add options related to the Objective-C runtime/ABI.
5645 ///
5646 /// Returns true if the runtime is non-fragile.
5647 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5648                                       ArgStringList &cmdArgs,
5649                                       RewriteKind rewriteKind) const {
5650   // Look for the controlling runtime option.
5651   Arg *runtimeArg =
5652       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5653                       options::OPT_fobjc_runtime_EQ);
5654
5655   // Just forward -fobjc-runtime= to the frontend.  This supercedes
5656   // options about fragility.
5657   if (runtimeArg &&
5658       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5659     ObjCRuntime runtime;
5660     StringRef value = runtimeArg->getValue();
5661     if (runtime.tryParse(value)) {
5662       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5663           << value;
5664     }
5665
5666     runtimeArg->render(args, cmdArgs);
5667     return runtime;
5668   }
5669
5670   // Otherwise, we'll need the ABI "version".  Version numbers are
5671   // slightly confusing for historical reasons:
5672   //   1 - Traditional "fragile" ABI
5673   //   2 - Non-fragile ABI, version 1
5674   //   3 - Non-fragile ABI, version 2
5675   unsigned objcABIVersion = 1;
5676   // If -fobjc-abi-version= is present, use that to set the version.
5677   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5678     StringRef value = abiArg->getValue();
5679     if (value == "1")
5680       objcABIVersion = 1;
5681     else if (value == "2")
5682       objcABIVersion = 2;
5683     else if (value == "3")
5684       objcABIVersion = 3;
5685     else
5686       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5687   } else {
5688     // Otherwise, determine if we are using the non-fragile ABI.
5689     bool nonFragileABIIsDefault =
5690         (rewriteKind == RK_NonFragile ||
5691          (rewriteKind == RK_None &&
5692           getToolChain().IsObjCNonFragileABIDefault()));
5693     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5694                      options::OPT_fno_objc_nonfragile_abi,
5695                      nonFragileABIIsDefault)) {
5696 // Determine the non-fragile ABI version to use.
5697 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5698       unsigned nonFragileABIVersion = 1;
5699 #else
5700       unsigned nonFragileABIVersion = 2;
5701 #endif
5702
5703       if (Arg *abiArg =
5704               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5705         StringRef value = abiArg->getValue();
5706         if (value == "1")
5707           nonFragileABIVersion = 1;
5708         else if (value == "2")
5709           nonFragileABIVersion = 2;
5710         else
5711           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5712               << value;
5713       }
5714
5715       objcABIVersion = 1 + nonFragileABIVersion;
5716     } else {
5717       objcABIVersion = 1;
5718     }
5719   }
5720
5721   // We don't actually care about the ABI version other than whether
5722   // it's non-fragile.
5723   bool isNonFragile = objcABIVersion != 1;
5724
5725   // If we have no runtime argument, ask the toolchain for its default runtime.
5726   // However, the rewriter only really supports the Mac runtime, so assume that.
5727   ObjCRuntime runtime;
5728   if (!runtimeArg) {
5729     switch (rewriteKind) {
5730     case RK_None:
5731       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5732       break;
5733     case RK_Fragile:
5734       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5735       break;
5736     case RK_NonFragile:
5737       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5738       break;
5739     }
5740
5741     // -fnext-runtime
5742   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5743     // On Darwin, make this use the default behavior for the toolchain.
5744     if (getToolChain().getTriple().isOSDarwin()) {
5745       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5746
5747       // Otherwise, build for a generic macosx port.
5748     } else {
5749       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5750     }
5751
5752     // -fgnu-runtime
5753   } else {
5754     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5755     // Legacy behaviour is to target the gnustep runtime if we are in
5756     // non-fragile mode or the GCC runtime in fragile mode.
5757     if (isNonFragile)
5758       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5759     else
5760       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5761   }
5762
5763   cmdArgs.push_back(
5764       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5765   return runtime;
5766 }
5767
5768 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5769   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5770   I += HaveDash;
5771   return !HaveDash;
5772 }
5773
5774 namespace {
5775 struct EHFlags {
5776   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5777   bool Synch;
5778   bool Asynch;
5779   bool NoExceptC;
5780 };
5781 } // end anonymous namespace
5782
5783 /// /EH controls whether to run destructor cleanups when exceptions are
5784 /// thrown.  There are three modifiers:
5785 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5786 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5787 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5788 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
5789 ///      modifier is an optimization, so we ignore it for now.
5790 /// The default is /EHs-c-, meaning cleanups are disabled.
5791 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5792   EHFlags EH;
5793
5794   std::vector<std::string> EHArgs =
5795       Args.getAllArgValues(options::OPT__SLASH_EH);
5796   for (auto EHVal : EHArgs) {
5797     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5798       switch (EHVal[I]) {
5799       case 'a':
5800         EH.Asynch = maybeConsumeDash(EHVal, I);
5801         continue;
5802       case 'c':
5803         EH.NoExceptC = maybeConsumeDash(EHVal, I);
5804         continue;
5805       case 's':
5806         EH.Synch = maybeConsumeDash(EHVal, I);
5807         continue;
5808       default:
5809         break;
5810       }
5811       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5812       break;
5813     }
5814   }
5815
5816   return EH;
5817 }
5818
5819 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5820                            enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5821                            bool *EmitCodeView) const {
5822   unsigned RTOptionID = options::OPT__SLASH_MT;
5823
5824   if (Args.hasArg(options::OPT__SLASH_LDd))
5825     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5826     // but defining _DEBUG is sticky.
5827     RTOptionID = options::OPT__SLASH_MTd;
5828
5829   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5830     RTOptionID = A->getOption().getID();
5831
5832   StringRef FlagForCRT;
5833   switch (RTOptionID) {
5834   case options::OPT__SLASH_MD:
5835     if (Args.hasArg(options::OPT__SLASH_LDd))
5836       CmdArgs.push_back("-D_DEBUG");
5837     CmdArgs.push_back("-D_MT");
5838     CmdArgs.push_back("-D_DLL");
5839     FlagForCRT = "--dependent-lib=msvcrt";
5840     break;
5841   case options::OPT__SLASH_MDd:
5842     CmdArgs.push_back("-D_DEBUG");
5843     CmdArgs.push_back("-D_MT");
5844     CmdArgs.push_back("-D_DLL");
5845     FlagForCRT = "--dependent-lib=msvcrtd";
5846     break;
5847   case options::OPT__SLASH_MT:
5848     if (Args.hasArg(options::OPT__SLASH_LDd))
5849       CmdArgs.push_back("-D_DEBUG");
5850     CmdArgs.push_back("-D_MT");
5851     FlagForCRT = "--dependent-lib=libcmt";
5852     break;
5853   case options::OPT__SLASH_MTd:
5854     CmdArgs.push_back("-D_DEBUG");
5855     CmdArgs.push_back("-D_MT");
5856     FlagForCRT = "--dependent-lib=libcmtd";
5857     break;
5858   default:
5859     llvm_unreachable("Unexpected option ID.");
5860   }
5861
5862   if (Args.hasArg(options::OPT__SLASH_Zl)) {
5863     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5864   } else {
5865     CmdArgs.push_back(FlagForCRT.data());
5866
5867     // This provides POSIX compatibility (maps 'open' to '_open'), which most
5868     // users want.  The /Za flag to cl.exe turns this off, but it's not
5869     // implemented in clang.
5870     CmdArgs.push_back("--dependent-lib=oldnames");
5871   }
5872
5873   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5874   // would produce interleaved output, so ignore /showIncludes in such cases.
5875   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5876     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5877       A->render(Args, CmdArgs);
5878
5879   // This controls whether or not we emit RTTI data for polymorphic types.
5880   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5881                    /*default=*/false))
5882     CmdArgs.push_back("-fno-rtti-data");
5883
5884   // Emit CodeView if -Z7 is present.
5885   *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5886   bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5887   // If we are emitting CV but not DWARF, don't build information that LLVM
5888   // can't yet process.
5889   if (*EmitCodeView && !EmitDwarf)
5890     *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5891   if (*EmitCodeView)
5892     CmdArgs.push_back("-gcodeview");
5893
5894   const Driver &D = getToolChain().getDriver();
5895   EHFlags EH = parseClangCLEHFlags(D, Args);
5896   // FIXME: Do something with NoExceptC.
5897   if (EH.Synch || EH.Asynch) {
5898     CmdArgs.push_back("-fcxx-exceptions");
5899     CmdArgs.push_back("-fexceptions");
5900   }
5901
5902   // /EP should expand to -E -P.
5903   if (Args.hasArg(options::OPT__SLASH_EP)) {
5904     CmdArgs.push_back("-E");
5905     CmdArgs.push_back("-P");
5906   }
5907
5908   unsigned VolatileOptionID;
5909   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5910       getToolChain().getArch() == llvm::Triple::x86)
5911     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5912   else
5913     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5914
5915   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5916     VolatileOptionID = A->getOption().getID();
5917
5918   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5919     CmdArgs.push_back("-fms-volatile");
5920
5921   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5922   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5923   if (MostGeneralArg && BestCaseArg)
5924     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5925         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5926
5927   if (MostGeneralArg) {
5928     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5929     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5930     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5931
5932     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5933     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5934     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5935       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5936           << FirstConflict->getAsString(Args)
5937           << SecondConflict->getAsString(Args);
5938
5939     if (SingleArg)
5940       CmdArgs.push_back("-fms-memptr-rep=single");
5941     else if (MultipleArg)
5942       CmdArgs.push_back("-fms-memptr-rep=multiple");
5943     else
5944       CmdArgs.push_back("-fms-memptr-rep=virtual");
5945   }
5946
5947   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5948     A->render(Args, CmdArgs);
5949
5950   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5951     CmdArgs.push_back("-fdiagnostics-format");
5952     if (Args.hasArg(options::OPT__SLASH_fallback))
5953       CmdArgs.push_back("msvc-fallback");
5954     else
5955       CmdArgs.push_back("msvc");
5956   }
5957 }
5958
5959 visualstudio::Compiler *Clang::getCLFallback() const {
5960   if (!CLFallback)
5961     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5962   return CLFallback.get();
5963 }
5964
5965 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5966                                 ArgStringList &CmdArgs) const {
5967   StringRef CPUName;
5968   StringRef ABIName;
5969   const llvm::Triple &Triple = getToolChain().getTriple();
5970   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5971
5972   CmdArgs.push_back("-target-abi");
5973   CmdArgs.push_back(ABIName.data());
5974 }
5975
5976 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5977                            const InputInfo &Output, const InputInfoList &Inputs,
5978                            const ArgList &Args,
5979                            const char *LinkingOutput) const {
5980   ArgStringList CmdArgs;
5981
5982   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5983   const InputInfo &Input = Inputs[0];
5984
5985   std::string TripleStr =
5986       getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5987   const llvm::Triple Triple(TripleStr);
5988
5989   // Don't warn about "clang -w -c foo.s"
5990   Args.ClaimAllArgs(options::OPT_w);
5991   // and "clang -emit-llvm -c foo.s"
5992   Args.ClaimAllArgs(options::OPT_emit_llvm);
5993
5994   claimNoWarnArgs(Args);
5995
5996   // Invoke ourselves in -cc1as mode.
5997   //
5998   // FIXME: Implement custom jobs for internal actions.
5999   CmdArgs.push_back("-cc1as");
6000
6001   // Add the "effective" target triple.
6002   CmdArgs.push_back("-triple");
6003   CmdArgs.push_back(Args.MakeArgString(TripleStr));
6004
6005   // Set the output mode, we currently only expect to be used as a real
6006   // assembler.
6007   CmdArgs.push_back("-filetype");
6008   CmdArgs.push_back("obj");
6009
6010   // Set the main file name, so that debug info works even with
6011   // -save-temps or preprocessed assembly.
6012   CmdArgs.push_back("-main-file-name");
6013   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6014
6015   // Add the target cpu
6016   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6017   if (!CPU.empty()) {
6018     CmdArgs.push_back("-target-cpu");
6019     CmdArgs.push_back(Args.MakeArgString(CPU));
6020   }
6021
6022   // Add the target features
6023   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6024
6025   // Ignore explicit -force_cpusubtype_ALL option.
6026   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6027
6028   // Pass along any -I options so we get proper .include search paths.
6029   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6030
6031   // Determine the original source input.
6032   const Action *SourceAction = &JA;
6033   while (SourceAction->getKind() != Action::InputClass) {
6034     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6035     SourceAction = SourceAction->getInputs()[0];
6036   }
6037
6038   // Forward -g and handle debug info related flags, assuming we are dealing
6039   // with an actual assembly file.
6040   if (SourceAction->getType() == types::TY_Asm ||
6041       SourceAction->getType() == types::TY_PP_Asm) {
6042     bool WantDebug = false;
6043     unsigned DwarfVersion = 0;
6044     Args.ClaimAllArgs(options::OPT_g_Group);
6045     if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6046       WantDebug = !A->getOption().matches(options::OPT_g0) &&
6047         !A->getOption().matches(options::OPT_ggdb0);
6048       if (WantDebug)
6049         DwarfVersion = DwarfVersionNum(A->getSpelling());
6050     }
6051     if (DwarfVersion == 0)
6052       DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6053     RenderDebugEnablingArgs(Args, CmdArgs,
6054                             (WantDebug ? CodeGenOptions::LimitedDebugInfo
6055                                        : CodeGenOptions::NoDebugInfo),
6056                             DwarfVersion, llvm::DebuggerKind::Default);
6057
6058     // Add the -fdebug-compilation-dir flag if needed.
6059     addDebugCompDirArg(Args, CmdArgs);
6060
6061     // Set the AT_producer to the clang version when using the integrated
6062     // assembler on assembly source files.
6063     CmdArgs.push_back("-dwarf-debug-producer");
6064     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6065
6066     // And pass along -I options
6067     Args.AddAllArgs(CmdArgs, options::OPT_I);
6068   }
6069
6070   // Handle -fPIC et al -- the relocation-model affects the assembler
6071   // for some targets.
6072   llvm::Reloc::Model RelocationModel;
6073   unsigned PICLevel;
6074   bool IsPIE;
6075   std::tie(RelocationModel, PICLevel, IsPIE) =
6076       ParsePICArgs(getToolChain(), Triple, Args);
6077
6078   const char *RMName = RelocationModelName(RelocationModel);
6079   if (RMName) {
6080     CmdArgs.push_back("-mrelocation-model");
6081     CmdArgs.push_back(RMName);
6082   }
6083
6084   // Optionally embed the -cc1as level arguments into the debug info, for build
6085   // analysis.
6086   if (getToolChain().UseDwarfDebugFlags()) {
6087     ArgStringList OriginalArgs;
6088     for (const auto &Arg : Args)
6089       Arg->render(Args, OriginalArgs);
6090
6091     SmallString<256> Flags;
6092     const char *Exec = getToolChain().getDriver().getClangProgramPath();
6093     Flags += Exec;
6094     for (const char *OriginalArg : OriginalArgs) {
6095       SmallString<128> EscapedArg;
6096       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6097       Flags += " ";
6098       Flags += EscapedArg;
6099     }
6100     CmdArgs.push_back("-dwarf-debug-flags");
6101     CmdArgs.push_back(Args.MakeArgString(Flags));
6102   }
6103
6104   // FIXME: Add -static support, once we have it.
6105
6106   // Add target specific flags.
6107   switch (getToolChain().getArch()) {
6108   default:
6109     break;
6110
6111   case llvm::Triple::mips:
6112   case llvm::Triple::mipsel:
6113   case llvm::Triple::mips64:
6114   case llvm::Triple::mips64el:
6115     AddMIPSTargetArgs(Args, CmdArgs);
6116     break;
6117   }
6118
6119   // Consume all the warning flags. Usually this would be handled more
6120   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6121   // doesn't handle that so rather than warning about unused flags that are
6122   // actually used, we'll lie by omission instead.
6123   // FIXME: Stop lying and consume only the appropriate driver flags
6124   Args.ClaimAllArgs(options::OPT_W_Group);
6125
6126   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6127                                     getToolChain().getDriver());
6128
6129   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6130
6131   assert(Output.isFilename() && "Unexpected lipo output.");
6132   CmdArgs.push_back("-o");
6133   CmdArgs.push_back(Output.getFilename());
6134
6135   assert(Input.isFilename() && "Invalid input.");
6136   CmdArgs.push_back(Input.getFilename());
6137
6138   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6139   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6140
6141   // Handle the debug info splitting at object creation time if we're
6142   // creating an object.
6143   // TODO: Currently only works on linux with newer objcopy.
6144   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6145       getToolChain().getTriple().isOSLinux())
6146     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6147                    SplitDebugName(Args, Input));
6148 }
6149
6150 void GnuTool::anchor() {}
6151
6152 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6153                                const InputInfo &Output,
6154                                const InputInfoList &Inputs, const ArgList &Args,
6155                                const char *LinkingOutput) const {
6156   const Driver &D = getToolChain().getDriver();
6157   ArgStringList CmdArgs;
6158
6159   for (const auto &A : Args) {
6160     if (forwardToGCC(A->getOption())) {
6161       // It is unfortunate that we have to claim here, as this means
6162       // we will basically never report anything interesting for
6163       // platforms using a generic gcc, even if we are just using gcc
6164       // to get to the assembler.
6165       A->claim();
6166
6167       // Don't forward any -g arguments to assembly steps.
6168       if (isa<AssembleJobAction>(JA) &&
6169           A->getOption().matches(options::OPT_g_Group))
6170         continue;
6171
6172       // Don't forward any -W arguments to assembly and link steps.
6173       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6174           A->getOption().matches(options::OPT_W_Group))
6175         continue;
6176
6177       A->render(Args, CmdArgs);
6178     }
6179   }
6180
6181   RenderExtraToolArgs(JA, CmdArgs);
6182
6183   // If using a driver driver, force the arch.
6184   if (getToolChain().getTriple().isOSDarwin()) {
6185     CmdArgs.push_back("-arch");
6186     CmdArgs.push_back(
6187         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6188   }
6189
6190   // Try to force gcc to match the tool chain we want, if we recognize
6191   // the arch.
6192   //
6193   // FIXME: The triple class should directly provide the information we want
6194   // here.
6195   switch (getToolChain().getArch()) {
6196   default:
6197     break;
6198   case llvm::Triple::x86:
6199   case llvm::Triple::ppc:
6200     CmdArgs.push_back("-m32");
6201     break;
6202   case llvm::Triple::x86_64:
6203   case llvm::Triple::ppc64:
6204   case llvm::Triple::ppc64le:
6205     CmdArgs.push_back("-m64");
6206     break;
6207   case llvm::Triple::sparcel:
6208     CmdArgs.push_back("-EL");
6209     break;
6210   }
6211
6212   if (Output.isFilename()) {
6213     CmdArgs.push_back("-o");
6214     CmdArgs.push_back(Output.getFilename());
6215   } else {
6216     assert(Output.isNothing() && "Unexpected output");
6217     CmdArgs.push_back("-fsyntax-only");
6218   }
6219
6220   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6221
6222   // Only pass -x if gcc will understand it; otherwise hope gcc
6223   // understands the suffix correctly. The main use case this would go
6224   // wrong in is for linker inputs if they happened to have an odd
6225   // suffix; really the only way to get this to happen is a command
6226   // like '-x foobar a.c' which will treat a.c like a linker input.
6227   //
6228   // FIXME: For the linker case specifically, can we safely convert
6229   // inputs into '-Wl,' options?
6230   for (const auto &II : Inputs) {
6231     // Don't try to pass LLVM or AST inputs to a generic gcc.
6232     if (types::isLLVMIR(II.getType()))
6233       D.Diag(diag::err_drv_no_linker_llvm_support)
6234           << getToolChain().getTripleString();
6235     else if (II.getType() == types::TY_AST)
6236       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6237     else if (II.getType() == types::TY_ModuleFile)
6238       D.Diag(diag::err_drv_no_module_support)
6239           << getToolChain().getTripleString();
6240
6241     if (types::canTypeBeUserSpecified(II.getType())) {
6242       CmdArgs.push_back("-x");
6243       CmdArgs.push_back(types::getTypeName(II.getType()));
6244     }
6245
6246     if (II.isFilename())
6247       CmdArgs.push_back(II.getFilename());
6248     else {
6249       const Arg &A = II.getInputArg();
6250
6251       // Reverse translate some rewritten options.
6252       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6253         CmdArgs.push_back("-lstdc++");
6254         continue;
6255       }
6256
6257       // Don't render as input, we need gcc to do the translations.
6258       A.render(Args, CmdArgs);
6259     }
6260   }
6261
6262   const std::string customGCCName = D.getCCCGenericGCCName();
6263   const char *GCCName;
6264   if (!customGCCName.empty())
6265     GCCName = customGCCName.c_str();
6266   else if (D.CCCIsCXX()) {
6267     GCCName = "g++";
6268   } else
6269     GCCName = "gcc";
6270
6271   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6272   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6273 }
6274
6275 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6276                                             ArgStringList &CmdArgs) const {
6277   CmdArgs.push_back("-E");
6278 }
6279
6280 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6281                                         ArgStringList &CmdArgs) const {
6282   const Driver &D = getToolChain().getDriver();
6283
6284   switch (JA.getType()) {
6285   // If -flto, etc. are present then make sure not to force assembly output.
6286   case types::TY_LLVM_IR:
6287   case types::TY_LTO_IR:
6288   case types::TY_LLVM_BC:
6289   case types::TY_LTO_BC:
6290     CmdArgs.push_back("-c");
6291     break;
6292   // We assume we've got an "integrated" assembler in that gcc will produce an
6293   // object file itself.
6294   case types::TY_Object:
6295     CmdArgs.push_back("-c");
6296     break;
6297   case types::TY_PP_Asm:
6298     CmdArgs.push_back("-S");
6299     break;
6300   case types::TY_Nothing:
6301     CmdArgs.push_back("-fsyntax-only");
6302     break;
6303   default:
6304     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6305   }
6306 }
6307
6308 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6309                                       ArgStringList &CmdArgs) const {
6310   // The types are (hopefully) good enough.
6311 }
6312
6313 // Hexagon tools start.
6314 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6315                                              ArgStringList &CmdArgs) const {
6316 }
6317
6318 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6319                                       const InputInfo &Output,
6320                                       const InputInfoList &Inputs,
6321                                       const ArgList &Args,
6322                                       const char *LinkingOutput) const {
6323   claimNoWarnArgs(Args);
6324
6325   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6326   const Driver &D = HTC.getDriver();
6327   ArgStringList CmdArgs;
6328
6329   std::string MArchString = "-march=hexagon";
6330   CmdArgs.push_back(Args.MakeArgString(MArchString));
6331
6332   RenderExtraToolArgs(JA, CmdArgs);
6333
6334   std::string AsName = "hexagon-llvm-mc";
6335   std::string MCpuString = "-mcpu=hexagon" +
6336         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6337   CmdArgs.push_back("-filetype=obj");
6338   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6339
6340   if (Output.isFilename()) {
6341     CmdArgs.push_back("-o");
6342     CmdArgs.push_back(Output.getFilename());
6343   } else {
6344     assert(Output.isNothing() && "Unexpected output");
6345     CmdArgs.push_back("-fsyntax-only");
6346   }
6347
6348   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6349     std::string N = llvm::utostr(G.getValue());
6350     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6351   }
6352
6353   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6354
6355   // Only pass -x if gcc will understand it; otherwise hope gcc
6356   // understands the suffix correctly. The main use case this would go
6357   // wrong in is for linker inputs if they happened to have an odd
6358   // suffix; really the only way to get this to happen is a command
6359   // like '-x foobar a.c' which will treat a.c like a linker input.
6360   //
6361   // FIXME: For the linker case specifically, can we safely convert
6362   // inputs into '-Wl,' options?
6363   for (const auto &II : Inputs) {
6364     // Don't try to pass LLVM or AST inputs to a generic gcc.
6365     if (types::isLLVMIR(II.getType()))
6366       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6367           << HTC.getTripleString();
6368     else if (II.getType() == types::TY_AST)
6369       D.Diag(clang::diag::err_drv_no_ast_support)
6370           << HTC.getTripleString();
6371     else if (II.getType() == types::TY_ModuleFile)
6372       D.Diag(diag::err_drv_no_module_support)
6373           << HTC.getTripleString();
6374
6375     if (II.isFilename())
6376       CmdArgs.push_back(II.getFilename());
6377     else
6378       // Don't render as input, we need gcc to do the translations.
6379       // FIXME: What is this?
6380       II.getInputArg().render(Args, CmdArgs);
6381   }
6382
6383   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6384   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6385 }
6386
6387 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6388                                           ArgStringList &CmdArgs) const {
6389 }
6390
6391 static void
6392 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6393                          const toolchains::HexagonToolChain &HTC,
6394                          const InputInfo &Output, const InputInfoList &Inputs,
6395                          const ArgList &Args, ArgStringList &CmdArgs,
6396                          const char *LinkingOutput) {
6397
6398   const Driver &D = HTC.getDriver();
6399
6400   //----------------------------------------------------------------------------
6401   //
6402   //----------------------------------------------------------------------------
6403   bool IsStatic = Args.hasArg(options::OPT_static);
6404   bool IsShared = Args.hasArg(options::OPT_shared);
6405   bool IsPIE = Args.hasArg(options::OPT_pie);
6406   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6407   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6408   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6409   bool UseG0 = false;
6410   bool UseShared = IsShared && !IsStatic;
6411
6412   //----------------------------------------------------------------------------
6413   // Silence warnings for various options
6414   //----------------------------------------------------------------------------
6415   Args.ClaimAllArgs(options::OPT_g_Group);
6416   Args.ClaimAllArgs(options::OPT_emit_llvm);
6417   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6418                                      // handled somewhere else.
6419   Args.ClaimAllArgs(options::OPT_static_libgcc);
6420
6421   //----------------------------------------------------------------------------
6422   //
6423   //----------------------------------------------------------------------------
6424   if (Args.hasArg(options::OPT_s))
6425     CmdArgs.push_back("-s");
6426
6427   if (Args.hasArg(options::OPT_r))
6428     CmdArgs.push_back("-r");
6429
6430   for (const auto &Opt : HTC.ExtraOpts)
6431     CmdArgs.push_back(Opt.c_str());
6432
6433   CmdArgs.push_back("-march=hexagon");
6434   std::string CpuVer =
6435         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6436   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6437   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6438
6439   if (IsShared) {
6440     CmdArgs.push_back("-shared");
6441     // The following should be the default, but doing as hexagon-gcc does.
6442     CmdArgs.push_back("-call_shared");
6443   }
6444
6445   if (IsStatic)
6446     CmdArgs.push_back("-static");
6447
6448   if (IsPIE && !IsShared)
6449     CmdArgs.push_back("-pie");
6450
6451   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6452     std::string N = llvm::utostr(G.getValue());
6453     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6454     UseG0 = G.getValue() == 0;
6455   }
6456
6457   //----------------------------------------------------------------------------
6458   //
6459   //----------------------------------------------------------------------------
6460   CmdArgs.push_back("-o");
6461   CmdArgs.push_back(Output.getFilename());
6462
6463   //----------------------------------------------------------------------------
6464   // moslib
6465   //----------------------------------------------------------------------------
6466   std::vector<std::string> OsLibs;
6467   bool HasStandalone = false;
6468
6469   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6470     A->claim();
6471     OsLibs.emplace_back(A->getValue());
6472     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6473   }
6474   if (OsLibs.empty()) {
6475     OsLibs.push_back("standalone");
6476     HasStandalone = true;
6477   }
6478
6479   //----------------------------------------------------------------------------
6480   // Start Files
6481   //----------------------------------------------------------------------------
6482   const std::string MCpuSuffix = "/" + CpuVer;
6483   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6484   const std::string RootDir =
6485       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6486   const std::string StartSubDir =
6487       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6488
6489   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6490                       const char *Name) -> std::string {
6491     std::string RelName = SubDir + Name;
6492     std::string P = HTC.GetFilePath(RelName.c_str());
6493     if (llvm::sys::fs::exists(P))
6494       return P;
6495     return RootDir + RelName;
6496   };
6497
6498   if (IncStdLib && IncStartFiles) {
6499     if (!IsShared) {
6500       if (HasStandalone) {
6501         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6502         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6503       }
6504       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6505       CmdArgs.push_back(Args.MakeArgString(Crt0));
6506     }
6507     std::string Init = UseShared
6508           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6509           : Find(RootDir, StartSubDir, "/init.o");
6510     CmdArgs.push_back(Args.MakeArgString(Init));
6511   }
6512
6513   //----------------------------------------------------------------------------
6514   // Library Search Paths
6515   //----------------------------------------------------------------------------
6516   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6517   for (const auto &LibPath : LibPaths)
6518     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6519
6520   //----------------------------------------------------------------------------
6521   //
6522   //----------------------------------------------------------------------------
6523   Args.AddAllArgs(CmdArgs,
6524                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6525                    options::OPT_t, options::OPT_u_Group});
6526
6527   AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6528
6529   //----------------------------------------------------------------------------
6530   // Libraries
6531   //----------------------------------------------------------------------------
6532   if (IncStdLib && IncDefLibs) {
6533     if (D.CCCIsCXX()) {
6534       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6535       CmdArgs.push_back("-lm");
6536     }
6537
6538     CmdArgs.push_back("--start-group");
6539
6540     if (!IsShared) {
6541       for (const std::string &Lib : OsLibs)
6542         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6543       CmdArgs.push_back("-lc");
6544     }
6545     CmdArgs.push_back("-lgcc");
6546
6547     CmdArgs.push_back("--end-group");
6548   }
6549
6550   //----------------------------------------------------------------------------
6551   // End files
6552   //----------------------------------------------------------------------------
6553   if (IncStdLib && IncStartFiles) {
6554     std::string Fini = UseShared
6555           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6556           : Find(RootDir, StartSubDir, "/fini.o");
6557     CmdArgs.push_back(Args.MakeArgString(Fini));
6558   }
6559 }
6560
6561 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6562                                    const InputInfo &Output,
6563                                    const InputInfoList &Inputs,
6564                                    const ArgList &Args,
6565                                    const char *LinkingOutput) const {
6566   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6567
6568   ArgStringList CmdArgs;
6569   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6570                            LinkingOutput);
6571
6572   std::string Linker = HTC.GetProgramPath("hexagon-link");
6573   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6574                                           CmdArgs, Inputs));
6575 }
6576 // Hexagon tools end.
6577
6578 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6579                                   const InputInfo &Output,
6580                                   const InputInfoList &Inputs,
6581                                   const ArgList &Args,
6582                                   const char *LinkingOutput) const {
6583
6584   std::string Linker = getToolChain().GetProgramPath(getShortName());
6585   ArgStringList CmdArgs;
6586   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6587   CmdArgs.push_back("-o");
6588   CmdArgs.push_back(Output.getFilename());
6589   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6590                                           CmdArgs, Inputs));
6591 }
6592 // AMDGPU tools end.
6593
6594 wasm::Linker::Linker(const ToolChain &TC)
6595   : GnuTool("wasm::Linker", "lld", TC) {}
6596
6597 bool wasm::Linker::isLinkJob() const {
6598   return true;
6599 }
6600
6601 bool wasm::Linker::hasIntegratedCPP() const {
6602   return false;
6603 }
6604
6605 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6606                                 const InputInfo &Output,
6607                                 const InputInfoList &Inputs,
6608                                 const ArgList &Args,
6609                                 const char *LinkingOutput) const {
6610   const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6611   ArgStringList CmdArgs;
6612   CmdArgs.push_back("-flavor");
6613   CmdArgs.push_back("ld");
6614
6615   // Enable garbage collection of unused input sections by default, since code
6616   // size is of particular importance. This is significantly facilitated by
6617   // the enabling of -ffunction-sections and -fdata-sections in
6618   // Clang::ConstructJob.
6619   if (areOptimizationsEnabled(Args))
6620     CmdArgs.push_back("--gc-sections");
6621
6622   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6623   CmdArgs.push_back("-o");
6624   CmdArgs.push_back(Output.getFilename());
6625   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6626 }
6627
6628 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6629   std::string MArch;
6630   if (!Arch.empty())
6631     MArch = Arch;
6632   else
6633     MArch = Triple.getArchName();
6634   MArch = StringRef(MArch).split("+").first.lower();
6635
6636   // Handle -march=native.
6637   if (MArch == "native") {
6638     std::string CPU = llvm::sys::getHostCPUName();
6639     if (CPU != "generic") {
6640       // Translate the native cpu into the architecture suffix for that CPU.
6641       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6642       // If there is no valid architecture suffix for this CPU we don't know how
6643       // to handle it, so return no architecture.
6644       if (Suffix.empty())
6645         MArch = "";
6646       else
6647         MArch = std::string("arm") + Suffix.str();
6648     }
6649   }
6650
6651   return MArch;
6652 }
6653
6654 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6655 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6656   std::string MArch = getARMArch(Arch, Triple);
6657   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6658   // here means an -march=native that we can't handle, so instead return no CPU.
6659   if (MArch.empty())
6660     return StringRef();
6661
6662   // We need to return an empty string here on invalid MArch values as the
6663   // various places that call this function can't cope with a null result.
6664   return Triple.getARMCPUForArch(MArch);
6665 }
6666
6667 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6668 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6669                                  const llvm::Triple &Triple) {
6670   // FIXME: Warn on inconsistent use of -mcpu and -march.
6671   // If we have -mcpu=, use that.
6672   if (!CPU.empty()) {
6673     std::string MCPU = StringRef(CPU).split("+").first.lower();
6674     // Handle -mcpu=native.
6675     if (MCPU == "native")
6676       return llvm::sys::getHostCPUName();
6677     else
6678       return MCPU;
6679   }
6680
6681   return getARMCPUForMArch(Arch, Triple);
6682 }
6683
6684 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6685 /// CPU  (or Arch, if CPU is generic).
6686 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6687 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6688                                        const llvm::Triple &Triple) {
6689   unsigned ArchKind;
6690   if (CPU == "generic") {
6691     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6692     ArchKind = llvm::ARM::parseArch(ARMArch);
6693     if (ArchKind == llvm::ARM::AK_INVALID)
6694       // In case of generic Arch, i.e. "arm",
6695       // extract arch from default cpu of the Triple
6696       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6697   } else {
6698     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6699     // armv7k triple if it's actually been specified via "-arch armv7k".
6700     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6701                           ? (unsigned)llvm::ARM::AK_ARMV7K
6702                           : llvm::ARM::parseCPUArch(CPU);
6703   }
6704   if (ArchKind == llvm::ARM::AK_INVALID)
6705     return "";
6706   return llvm::ARM::getSubArch(ArchKind);
6707 }
6708
6709 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6710                             const llvm::Triple &Triple) {
6711   if (Args.hasArg(options::OPT_r))
6712     return;
6713
6714   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6715   // to generate BE-8 executables.
6716   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6717     CmdArgs.push_back("--be8");
6718 }
6719
6720 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6721   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6722   // was first introduced in Release 3. However, other compilers have
6723   // traditionally allowed it for Release 2 so we should do the same.
6724   return (NanEncoding)llvm::StringSwitch<int>(CPU)
6725       .Case("mips1", NanLegacy)
6726       .Case("mips2", NanLegacy)
6727       .Case("mips3", NanLegacy)
6728       .Case("mips4", NanLegacy)
6729       .Case("mips5", NanLegacy)
6730       .Case("mips32", NanLegacy)
6731       .Case("mips32r2", NanLegacy | Nan2008)
6732       .Case("mips32r3", NanLegacy | Nan2008)
6733       .Case("mips32r5", NanLegacy | Nan2008)
6734       .Case("mips32r6", Nan2008)
6735       .Case("mips64", NanLegacy)
6736       .Case("mips64r2", NanLegacy | Nan2008)
6737       .Case("mips64r3", NanLegacy | Nan2008)
6738       .Case("mips64r5", NanLegacy | Nan2008)
6739       .Case("mips64r6", Nan2008)
6740       .Default(NanLegacy);
6741 }
6742
6743 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6744   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6745   return A && (A->getValue() == StringRef(Value));
6746 }
6747
6748 bool mips::isUCLibc(const ArgList &Args) {
6749   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6750   return A && A->getOption().matches(options::OPT_muclibc);
6751 }
6752
6753 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6754   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6755     return llvm::StringSwitch<bool>(NaNArg->getValue())
6756         .Case("2008", true)
6757         .Case("legacy", false)
6758         .Default(false);
6759
6760   // NaN2008 is the default for MIPS32r6/MIPS64r6.
6761   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6762       .Cases("mips32r6", "mips64r6", true)
6763       .Default(false);
6764
6765   return false;
6766 }
6767
6768 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6769                          StringRef ABIName, mips::FloatABI FloatABI) {
6770   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6771       Triple.getVendor() != llvm::Triple::MipsTechnologies)
6772     return false;
6773
6774   if (ABIName != "32")
6775     return false;
6776
6777   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6778   // present.
6779   if (FloatABI == mips::FloatABI::Soft)
6780     return false;
6781
6782   return llvm::StringSwitch<bool>(CPUName)
6783       .Cases("mips2", "mips3", "mips4", "mips5", true)
6784       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6785       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6786       .Default(false);
6787 }
6788
6789 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6790                          StringRef CPUName, StringRef ABIName,
6791                          mips::FloatABI FloatABI) {
6792   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6793
6794   // FPXX shouldn't be used if -msingle-float is present.
6795   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6796                                options::OPT_mdouble_float))
6797     if (A->getOption().matches(options::OPT_msingle_float))
6798       UseFPXX = false;
6799
6800   return UseFPXX;
6801 }
6802
6803 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6804   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6805   // archs which Darwin doesn't use.
6806
6807   // The matching this routine does is fairly pointless, since it is neither the
6808   // complete architecture list, nor a reasonable subset. The problem is that
6809   // historically the driver driver accepts this and also ties its -march=
6810   // handling to the architecture name, so we need to be careful before removing
6811   // support for it.
6812
6813   // This code must be kept in sync with Clang's Darwin specific argument
6814   // translation.
6815
6816   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6817       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6818       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6819       .Case("ppc64", llvm::Triple::ppc64)
6820       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6821       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6822              llvm::Triple::x86)
6823       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6824       // This is derived from the driver driver.
6825       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6826       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6827       .Cases("armv7s", "xscale", llvm::Triple::arm)
6828       .Case("arm64", llvm::Triple::aarch64)
6829       .Case("r600", llvm::Triple::r600)
6830       .Case("amdgcn", llvm::Triple::amdgcn)
6831       .Case("nvptx", llvm::Triple::nvptx)
6832       .Case("nvptx64", llvm::Triple::nvptx64)
6833       .Case("amdil", llvm::Triple::amdil)
6834       .Case("spir", llvm::Triple::spir)
6835       .Default(llvm::Triple::UnknownArch);
6836 }
6837
6838 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6839   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6840   T.setArch(Arch);
6841
6842   if (Str == "x86_64h")
6843     T.setArchName(Str);
6844   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6845     T.setOS(llvm::Triple::UnknownOS);
6846     T.setObjectFormat(llvm::Triple::MachO);
6847   }
6848 }
6849
6850 const char *Clang::getBaseInputName(const ArgList &Args,
6851                                     const InputInfo &Input) {
6852   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6853 }
6854
6855 const char *Clang::getBaseInputStem(const ArgList &Args,
6856                                     const InputInfoList &Inputs) {
6857   const char *Str = getBaseInputName(Args, Inputs[0]);
6858
6859   if (const char *End = strrchr(Str, '.'))
6860     return Args.MakeArgString(std::string(Str, End));
6861
6862   return Str;
6863 }
6864
6865 const char *Clang::getDependencyFileName(const ArgList &Args,
6866                                          const InputInfoList &Inputs) {
6867   // FIXME: Think about this more.
6868   std::string Res;
6869
6870   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6871     std::string Str(OutputOpt->getValue());
6872     Res = Str.substr(0, Str.rfind('.'));
6873   } else {
6874     Res = getBaseInputStem(Args, Inputs);
6875   }
6876   return Args.MakeArgString(Res + ".d");
6877 }
6878
6879 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6880                                     const InputInfo &Output,
6881                                     const InputInfoList &Inputs,
6882                                     const ArgList &Args,
6883                                     const char *LinkingOutput) const {
6884   const ToolChain &ToolChain = getToolChain();
6885   const Driver &D = ToolChain.getDriver();
6886   ArgStringList CmdArgs;
6887
6888   // Silence warning for "clang -g foo.o -o foo"
6889   Args.ClaimAllArgs(options::OPT_g_Group);
6890   // and "clang -emit-llvm foo.o -o foo"
6891   Args.ClaimAllArgs(options::OPT_emit_llvm);
6892   // and for "clang -w foo.o -o foo". Other warning options are already
6893   // handled somewhere else.
6894   Args.ClaimAllArgs(options::OPT_w);
6895
6896   if (!D.SysRoot.empty())
6897     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6898
6899   // CloudABI only supports static linkage.
6900   CmdArgs.push_back("-Bstatic");
6901   CmdArgs.push_back("--eh-frame-hdr");
6902   CmdArgs.push_back("--gc-sections");
6903
6904   if (Output.isFilename()) {
6905     CmdArgs.push_back("-o");
6906     CmdArgs.push_back(Output.getFilename());
6907   } else {
6908     assert(Output.isNothing() && "Invalid output.");
6909   }
6910
6911   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6912     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6913     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6914   }
6915
6916   Args.AddAllArgs(CmdArgs, options::OPT_L);
6917   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6918   Args.AddAllArgs(CmdArgs,
6919                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6920                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6921
6922   if (D.isUsingLTO())
6923     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6924
6925   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6926
6927   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6928     if (D.CCCIsCXX())
6929       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6930     CmdArgs.push_back("-lc");
6931     CmdArgs.push_back("-lcompiler_rt");
6932   }
6933
6934   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6935     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6936
6937   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6938   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6939 }
6940
6941 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6942                                      const InputInfo &Output,
6943                                      const InputInfoList &Inputs,
6944                                      const ArgList &Args,
6945                                      const char *LinkingOutput) const {
6946   ArgStringList CmdArgs;
6947
6948   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6949   const InputInfo &Input = Inputs[0];
6950
6951   // Determine the original source input.
6952   const Action *SourceAction = &JA;
6953   while (SourceAction->getKind() != Action::InputClass) {
6954     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6955     SourceAction = SourceAction->getInputs()[0];
6956   }
6957
6958   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6959   // sure it runs its system assembler not clang's integrated assembler.
6960   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
6961   // FIXME: at run-time detect assembler capabilities or rely on version
6962   // information forwarded by -target-assembler-version.
6963   if (Args.hasArg(options::OPT_fno_integrated_as)) {
6964     const llvm::Triple &T(getToolChain().getTriple());
6965     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6966       CmdArgs.push_back("-Q");
6967   }
6968
6969   // Forward -g, assuming we are dealing with an actual assembly file.
6970   if (SourceAction->getType() == types::TY_Asm ||
6971       SourceAction->getType() == types::TY_PP_Asm) {
6972     if (Args.hasArg(options::OPT_gstabs))
6973       CmdArgs.push_back("--gstabs");
6974     else if (Args.hasArg(options::OPT_g_Group))
6975       CmdArgs.push_back("-g");
6976   }
6977
6978   // Derived from asm spec.
6979   AddMachOArch(Args, CmdArgs);
6980
6981   // Use -force_cpusubtype_ALL on x86 by default.
6982   if (getToolChain().getArch() == llvm::Triple::x86 ||
6983       getToolChain().getArch() == llvm::Triple::x86_64 ||
6984       Args.hasArg(options::OPT_force__cpusubtype__ALL))
6985     CmdArgs.push_back("-force_cpusubtype_ALL");
6986
6987   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6988       (((Args.hasArg(options::OPT_mkernel) ||
6989          Args.hasArg(options::OPT_fapple_kext)) &&
6990         getMachOToolChain().isKernelStatic()) ||
6991        Args.hasArg(options::OPT_static)))
6992     CmdArgs.push_back("-static");
6993
6994   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6995
6996   assert(Output.isFilename() && "Unexpected lipo output.");
6997   CmdArgs.push_back("-o");
6998   CmdArgs.push_back(Output.getFilename());
6999
7000   assert(Input.isFilename() && "Invalid input.");
7001   CmdArgs.push_back(Input.getFilename());
7002
7003   // asm_final spec is empty.
7004
7005   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7006   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7007 }
7008
7009 void darwin::MachOTool::anchor() {}
7010
7011 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7012                                      ArgStringList &CmdArgs) const {
7013   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7014
7015   // Derived from darwin_arch spec.
7016   CmdArgs.push_back("-arch");
7017   CmdArgs.push_back(Args.MakeArgString(ArchName));
7018
7019   // FIXME: Is this needed anymore?
7020   if (ArchName == "arm")
7021     CmdArgs.push_back("-force_cpusubtype_ALL");
7022 }
7023
7024 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7025   // We only need to generate a temp path for LTO if we aren't compiling object
7026   // files. When compiling source files, we run 'dsymutil' after linking. We
7027   // don't run 'dsymutil' when compiling object files.
7028   for (const auto &Input : Inputs)
7029     if (Input.getType() != types::TY_Object)
7030       return true;
7031
7032   return false;
7033 }
7034
7035 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7036                                  ArgStringList &CmdArgs,
7037                                  const InputInfoList &Inputs) const {
7038   const Driver &D = getToolChain().getDriver();
7039   const toolchains::MachO &MachOTC = getMachOToolChain();
7040
7041   unsigned Version[3] = {0, 0, 0};
7042   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7043     bool HadExtra;
7044     if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
7045                                    Version[2], HadExtra) ||
7046         HadExtra)
7047       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7048   }
7049
7050   // Newer linkers support -demangle. Pass it if supported and not disabled by
7051   // the user.
7052   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7053     CmdArgs.push_back("-demangle");
7054
7055   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7056     CmdArgs.push_back("-export_dynamic");
7057
7058   // If we are using App Extension restrictions, pass a flag to the linker
7059   // telling it that the compiled code has been audited.
7060   if (Args.hasFlag(options::OPT_fapplication_extension,
7061                    options::OPT_fno_application_extension, false))
7062     CmdArgs.push_back("-application_extension");
7063
7064   if (D.isUsingLTO()) {
7065     // If we are using LTO, then automatically create a temporary file path for
7066     // the linker to use, so that it's lifetime will extend past a possible
7067     // dsymutil step.
7068     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7069       const char *TmpPath = C.getArgs().MakeArgString(
7070           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7071       C.addTempFile(TmpPath);
7072       CmdArgs.push_back("-object_path_lto");
7073       CmdArgs.push_back(TmpPath);
7074     }
7075
7076     // Use -lto_library option to specify the libLTO.dylib path. Try to find
7077     // it in clang installed libraries. If not found, the option is not used
7078     // and 'ld' will use its default mechanism to search for libLTO.dylib.
7079     if (Version[0] >= 133) {
7080       // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7081       StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7082       SmallString<128> LibLTOPath(P);
7083       llvm::sys::path::append(LibLTOPath, "lib");
7084       llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7085       if (llvm::sys::fs::exists(LibLTOPath)) {
7086         CmdArgs.push_back("-lto_library");
7087         CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7088       } else {
7089         D.Diag(diag::warn_drv_lto_libpath);
7090       }
7091     }
7092   }
7093
7094   // Derived from the "link" spec.
7095   Args.AddAllArgs(CmdArgs, options::OPT_static);
7096   if (!Args.hasArg(options::OPT_static))
7097     CmdArgs.push_back("-dynamic");
7098   if (Args.hasArg(options::OPT_fgnu_runtime)) {
7099     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7100     // here. How do we wish to handle such things?
7101   }
7102
7103   if (!Args.hasArg(options::OPT_dynamiclib)) {
7104     AddMachOArch(Args, CmdArgs);
7105     // FIXME: Why do this only on this path?
7106     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7107
7108     Args.AddLastArg(CmdArgs, options::OPT_bundle);
7109     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7110     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7111
7112     Arg *A;
7113     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7114         (A = Args.getLastArg(options::OPT_current__version)) ||
7115         (A = Args.getLastArg(options::OPT_install__name)))
7116       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7117                                                        << "-dynamiclib";
7118
7119     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7120     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7121     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7122   } else {
7123     CmdArgs.push_back("-dylib");
7124
7125     Arg *A;
7126     if ((A = Args.getLastArg(options::OPT_bundle)) ||
7127         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7128         (A = Args.getLastArg(options::OPT_client__name)) ||
7129         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7130         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7131         (A = Args.getLastArg(options::OPT_private__bundle)))
7132       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7133                                                       << "-dynamiclib";
7134
7135     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7136                               "-dylib_compatibility_version");
7137     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7138                               "-dylib_current_version");
7139
7140     AddMachOArch(Args, CmdArgs);
7141
7142     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7143                               "-dylib_install_name");
7144   }
7145
7146   Args.AddLastArg(CmdArgs, options::OPT_all__load);
7147   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7148   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7149   if (MachOTC.isTargetIOSBased())
7150     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7151   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7152   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7153   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7154   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7155   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7156   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7157   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7158   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7159   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7160   Args.AddAllArgs(CmdArgs, options::OPT_init);
7161
7162   // Add the deployment target.
7163   MachOTC.addMinVersionArgs(Args, CmdArgs);
7164
7165   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7166   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7167   Args.AddLastArg(CmdArgs, options::OPT_single__module);
7168   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7169   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7170
7171   if (const Arg *A =
7172           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7173                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
7174     if (A->getOption().matches(options::OPT_fpie) ||
7175         A->getOption().matches(options::OPT_fPIE))
7176       CmdArgs.push_back("-pie");
7177     else
7178       CmdArgs.push_back("-no_pie");
7179   }
7180
7181   Args.AddLastArg(CmdArgs, options::OPT_prebind);
7182   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7183   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7184   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7185   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7186   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7187   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7188   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7189   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7190   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7191   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7192   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7193   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7194   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7195   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7196   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7197
7198   // Give --sysroot= preference, over the Apple specific behavior to also use
7199   // --isysroot as the syslibroot.
7200   StringRef sysroot = C.getSysRoot();
7201   if (sysroot != "") {
7202     CmdArgs.push_back("-syslibroot");
7203     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7204   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7205     CmdArgs.push_back("-syslibroot");
7206     CmdArgs.push_back(A->getValue());
7207   }
7208
7209   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7210   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7211   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7212   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7213   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7214   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7215   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7216   Args.AddAllArgs(CmdArgs, options::OPT_y);
7217   Args.AddLastArg(CmdArgs, options::OPT_w);
7218   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7219   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7220   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7221   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7222   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7223   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7224   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7225   Args.AddLastArg(CmdArgs, options::OPT_whyload);
7226   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7227   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7228   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7229   Args.AddLastArg(CmdArgs, options::OPT_Mach);
7230 }
7231
7232 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7233                                   const InputInfo &Output,
7234                                   const InputInfoList &Inputs,
7235                                   const ArgList &Args,
7236                                   const char *LinkingOutput) const {
7237   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7238
7239   // If the number of arguments surpasses the system limits, we will encode the
7240   // input files in a separate file, shortening the command line. To this end,
7241   // build a list of input file names that can be passed via a file with the
7242   // -filelist linker option.
7243   llvm::opt::ArgStringList InputFileList;
7244
7245   // The logic here is derived from gcc's behavior; most of which
7246   // comes from specs (starting with link_command). Consult gcc for
7247   // more information.
7248   ArgStringList CmdArgs;
7249
7250   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7251   if (Args.hasArg(options::OPT_ccc_arcmt_check,
7252                   options::OPT_ccc_arcmt_migrate)) {
7253     for (const auto &Arg : Args)
7254       Arg->claim();
7255     const char *Exec =
7256         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7257     CmdArgs.push_back(Output.getFilename());
7258     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7259     return;
7260   }
7261
7262   // I'm not sure why this particular decomposition exists in gcc, but
7263   // we follow suite for ease of comparison.
7264   AddLinkArgs(C, Args, CmdArgs, Inputs);
7265
7266   // It seems that the 'e' option is completely ignored for dynamic executables
7267   // (the default), and with static executables, the last one wins, as expected.
7268   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7269                             options::OPT_Z_Flag, options::OPT_u_Group,
7270                             options::OPT_e, options::OPT_r});
7271
7272   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7273   // members of static archive libraries which implement Objective-C classes or
7274   // categories.
7275   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7276     CmdArgs.push_back("-ObjC");
7277
7278   CmdArgs.push_back("-o");
7279   CmdArgs.push_back(Output.getFilename());
7280
7281   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7282     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7283
7284   // SafeStack requires its own runtime libraries
7285   // These libraries should be linked first, to make sure the
7286   // __safestack_init constructor executes before everything else
7287   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7288     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7289                                           "libclang_rt.safestack_osx.a",
7290                                           /*AlwaysLink=*/true);
7291   }
7292
7293   Args.AddAllArgs(CmdArgs, options::OPT_L);
7294
7295   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7296   // Build the input file for -filelist (list of linker input files) in case we
7297   // need it later
7298   for (const auto &II : Inputs) {
7299     if (!II.isFilename()) {
7300       // This is a linker input argument.
7301       // We cannot mix input arguments and file names in a -filelist input, thus
7302       // we prematurely stop our list (remaining files shall be passed as
7303       // arguments).
7304       if (InputFileList.size() > 0)
7305         break;
7306
7307       continue;
7308     }
7309
7310     InputFileList.push_back(II.getFilename());
7311   }
7312
7313   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7314     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7315
7316   if (isObjCRuntimeLinked(Args) &&
7317       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7318     // We use arclite library for both ARC and subscripting support.
7319     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7320
7321     CmdArgs.push_back("-framework");
7322     CmdArgs.push_back("Foundation");
7323     // Link libobj.
7324     CmdArgs.push_back("-lobjc");
7325   }
7326
7327   if (LinkingOutput) {
7328     CmdArgs.push_back("-arch_multiple");
7329     CmdArgs.push_back("-final_output");
7330     CmdArgs.push_back(LinkingOutput);
7331   }
7332
7333   if (Args.hasArg(options::OPT_fnested_functions))
7334     CmdArgs.push_back("-allow_stack_execute");
7335
7336   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7337
7338   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7339     if (getToolChain().getDriver().CCCIsCXX())
7340       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7341
7342     // link_ssp spec is empty.
7343
7344     // Let the tool chain choose which runtime library to link.
7345     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7346   }
7347
7348   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7349     // endfile_spec is empty.
7350   }
7351
7352   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7353   Args.AddAllArgs(CmdArgs, options::OPT_F);
7354
7355   // -iframework should be forwarded as -F.
7356   for (const Arg *A : Args.filtered(options::OPT_iframework))
7357     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7358
7359   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7360     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7361       if (A->getValue() == StringRef("Accelerate")) {
7362         CmdArgs.push_back("-framework");
7363         CmdArgs.push_back("Accelerate");
7364       }
7365     }
7366   }
7367
7368   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7369   std::unique_ptr<Command> Cmd =
7370       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7371   Cmd->setInputFileList(std::move(InputFileList));
7372   C.addCommand(std::move(Cmd));
7373 }
7374
7375 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7376                                 const InputInfo &Output,
7377                                 const InputInfoList &Inputs,
7378                                 const ArgList &Args,
7379                                 const char *LinkingOutput) const {
7380   ArgStringList CmdArgs;
7381
7382   CmdArgs.push_back("-create");
7383   assert(Output.isFilename() && "Unexpected lipo output.");
7384
7385   CmdArgs.push_back("-output");
7386   CmdArgs.push_back(Output.getFilename());
7387
7388   for (const auto &II : Inputs) {
7389     assert(II.isFilename() && "Unexpected lipo input.");
7390     CmdArgs.push_back(II.getFilename());
7391   }
7392
7393   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7394   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7395 }
7396
7397 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7398                                     const InputInfo &Output,
7399                                     const InputInfoList &Inputs,
7400                                     const ArgList &Args,
7401                                     const char *LinkingOutput) const {
7402   ArgStringList CmdArgs;
7403
7404   CmdArgs.push_back("-o");
7405   CmdArgs.push_back(Output.getFilename());
7406
7407   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7408   const InputInfo &Input = Inputs[0];
7409   assert(Input.isFilename() && "Unexpected dsymutil input.");
7410   CmdArgs.push_back(Input.getFilename());
7411
7412   const char *Exec =
7413       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7414   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7415 }
7416
7417 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7418                                        const InputInfo &Output,
7419                                        const InputInfoList &Inputs,
7420                                        const ArgList &Args,
7421                                        const char *LinkingOutput) const {
7422   ArgStringList CmdArgs;
7423   CmdArgs.push_back("--verify");
7424   CmdArgs.push_back("--debug-info");
7425   CmdArgs.push_back("--eh-frame");
7426   CmdArgs.push_back("--quiet");
7427
7428   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7429   const InputInfo &Input = Inputs[0];
7430   assert(Input.isFilename() && "Unexpected verify input");
7431
7432   // Grabbing the output of the earlier dsymutil run.
7433   CmdArgs.push_back(Input.getFilename());
7434
7435   const char *Exec =
7436       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7437   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7438 }
7439
7440 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7441                                       const InputInfo &Output,
7442                                       const InputInfoList &Inputs,
7443                                       const ArgList &Args,
7444                                       const char *LinkingOutput) const {
7445   claimNoWarnArgs(Args);
7446   ArgStringList CmdArgs;
7447
7448   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7449
7450   CmdArgs.push_back("-o");
7451   CmdArgs.push_back(Output.getFilename());
7452
7453   for (const auto &II : Inputs)
7454     CmdArgs.push_back(II.getFilename());
7455
7456   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7457   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7458 }
7459
7460 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7461                                    const InputInfo &Output,
7462                                    const InputInfoList &Inputs,
7463                                    const ArgList &Args,
7464                                    const char *LinkingOutput) const {
7465   ArgStringList CmdArgs;
7466
7467   // Demangle C++ names in errors
7468   CmdArgs.push_back("-C");
7469
7470   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7471     CmdArgs.push_back("-e");
7472     CmdArgs.push_back("_start");
7473   }
7474
7475   if (Args.hasArg(options::OPT_static)) {
7476     CmdArgs.push_back("-Bstatic");
7477     CmdArgs.push_back("-dn");
7478   } else {
7479     CmdArgs.push_back("-Bdynamic");
7480     if (Args.hasArg(options::OPT_shared)) {
7481       CmdArgs.push_back("-shared");
7482     } else {
7483       CmdArgs.push_back("--dynamic-linker");
7484       CmdArgs.push_back(
7485           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7486     }
7487   }
7488
7489   if (Output.isFilename()) {
7490     CmdArgs.push_back("-o");
7491     CmdArgs.push_back(Output.getFilename());
7492   } else {
7493     assert(Output.isNothing() && "Invalid output.");
7494   }
7495
7496   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7497     if (!Args.hasArg(options::OPT_shared))
7498       CmdArgs.push_back(
7499           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7500
7501     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7502     CmdArgs.push_back(
7503         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7504     CmdArgs.push_back(
7505         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7506   }
7507
7508   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7509
7510   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7511                             options::OPT_e, options::OPT_r});
7512
7513   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7514
7515   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7516     if (getToolChain().getDriver().CCCIsCXX())
7517       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7518     CmdArgs.push_back("-lgcc_s");
7519     CmdArgs.push_back("-lc");
7520     if (!Args.hasArg(options::OPT_shared)) {
7521       CmdArgs.push_back("-lgcc");
7522       CmdArgs.push_back("-lm");
7523     }
7524   }
7525
7526   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7527     CmdArgs.push_back(
7528         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7529   }
7530   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7531
7532   getToolChain().addProfileRTLibs(Args, CmdArgs);
7533
7534   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7535   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7536 }
7537
7538 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7539                                       const InputInfo &Output,
7540                                       const InputInfoList &Inputs,
7541                                       const ArgList &Args,
7542                                       const char *LinkingOutput) const {
7543   claimNoWarnArgs(Args);
7544   ArgStringList CmdArgs;
7545
7546   switch (getToolChain().getArch()) {
7547   case llvm::Triple::x86:
7548     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7549     // instruct as in the base system to assemble 32-bit code.
7550     CmdArgs.push_back("--32");
7551     break;
7552
7553   case llvm::Triple::ppc:
7554     CmdArgs.push_back("-mppc");
7555     CmdArgs.push_back("-many");
7556     break;
7557
7558   case llvm::Triple::sparc:
7559   case llvm::Triple::sparcel: {
7560     CmdArgs.push_back("-32");
7561     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7562     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7563     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7564     break;
7565   }
7566
7567   case llvm::Triple::sparcv9: {
7568     CmdArgs.push_back("-64");
7569     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7570     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7571     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7572     break;
7573   }
7574
7575   case llvm::Triple::mips64:
7576   case llvm::Triple::mips64el: {
7577     StringRef CPUName;
7578     StringRef ABIName;
7579     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7580
7581     CmdArgs.push_back("-mabi");
7582     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7583
7584     if (getToolChain().getArch() == llvm::Triple::mips64)
7585       CmdArgs.push_back("-EB");
7586     else
7587       CmdArgs.push_back("-EL");
7588
7589     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7590     break;
7591   }
7592
7593   default:
7594     break;
7595   }
7596
7597   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7598
7599   CmdArgs.push_back("-o");
7600   CmdArgs.push_back(Output.getFilename());
7601
7602   for (const auto &II : Inputs)
7603     CmdArgs.push_back(II.getFilename());
7604
7605   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7606   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7607 }
7608
7609 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7610                                    const InputInfo &Output,
7611                                    const InputInfoList &Inputs,
7612                                    const ArgList &Args,
7613                                    const char *LinkingOutput) const {
7614   const Driver &D = getToolChain().getDriver();
7615   ArgStringList CmdArgs;
7616
7617   // Silence warning for "clang -g foo.o -o foo"
7618   Args.ClaimAllArgs(options::OPT_g_Group);
7619   // and "clang -emit-llvm foo.o -o foo"
7620   Args.ClaimAllArgs(options::OPT_emit_llvm);
7621   // and for "clang -w foo.o -o foo". Other warning options are already
7622   // handled somewhere else.
7623   Args.ClaimAllArgs(options::OPT_w);
7624
7625   if (getToolChain().getArch() == llvm::Triple::mips64)
7626     CmdArgs.push_back("-EB");
7627   else if (getToolChain().getArch() == llvm::Triple::mips64el)
7628     CmdArgs.push_back("-EL");
7629
7630   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7631     CmdArgs.push_back("-e");
7632     CmdArgs.push_back("__start");
7633   }
7634
7635   if (Args.hasArg(options::OPT_static)) {
7636     CmdArgs.push_back("-Bstatic");
7637   } else {
7638     if (Args.hasArg(options::OPT_rdynamic))
7639       CmdArgs.push_back("-export-dynamic");
7640     CmdArgs.push_back("--eh-frame-hdr");
7641     CmdArgs.push_back("-Bdynamic");
7642     if (Args.hasArg(options::OPT_shared)) {
7643       CmdArgs.push_back("-shared");
7644     } else {
7645       CmdArgs.push_back("-dynamic-linker");
7646       CmdArgs.push_back("/usr/libexec/ld.so");
7647     }
7648   }
7649
7650   if (Args.hasArg(options::OPT_nopie))
7651     CmdArgs.push_back("-nopie");
7652
7653   if (Output.isFilename()) {
7654     CmdArgs.push_back("-o");
7655     CmdArgs.push_back(Output.getFilename());
7656   } else {
7657     assert(Output.isNothing() && "Invalid output.");
7658   }
7659
7660   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7661     if (!Args.hasArg(options::OPT_shared)) {
7662       if (Args.hasArg(options::OPT_pg))
7663         CmdArgs.push_back(
7664             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7665       else
7666         CmdArgs.push_back(
7667             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7668       CmdArgs.push_back(
7669           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7670     } else {
7671       CmdArgs.push_back(
7672           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7673     }
7674   }
7675
7676   std::string Triple = getToolChain().getTripleString();
7677   if (Triple.substr(0, 6) == "x86_64")
7678     Triple.replace(0, 6, "amd64");
7679   CmdArgs.push_back(
7680       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7681
7682   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7683                             options::OPT_e, options::OPT_s, options::OPT_t,
7684                             options::OPT_Z_Flag, options::OPT_r});
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     // FIXME: For some reason GCC passes -lgcc before adding
7698     // the default system libraries. Just mimic this for now.
7699     CmdArgs.push_back("-lgcc");
7700
7701     if (Args.hasArg(options::OPT_pthread)) {
7702       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7703         CmdArgs.push_back("-lpthread_p");
7704       else
7705         CmdArgs.push_back("-lpthread");
7706     }
7707
7708     if (!Args.hasArg(options::OPT_shared)) {
7709       if (Args.hasArg(options::OPT_pg))
7710         CmdArgs.push_back("-lc_p");
7711       else
7712         CmdArgs.push_back("-lc");
7713     }
7714
7715     CmdArgs.push_back("-lgcc");
7716   }
7717
7718   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7719     if (!Args.hasArg(options::OPT_shared))
7720       CmdArgs.push_back(
7721           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7722     else
7723       CmdArgs.push_back(
7724           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7725   }
7726
7727   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7728   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7729 }
7730
7731 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7732                                      const InputInfo &Output,
7733                                      const InputInfoList &Inputs,
7734                                      const ArgList &Args,
7735                                      const char *LinkingOutput) const {
7736   claimNoWarnArgs(Args);
7737   ArgStringList CmdArgs;
7738
7739   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7740
7741   CmdArgs.push_back("-o");
7742   CmdArgs.push_back(Output.getFilename());
7743
7744   for (const auto &II : Inputs)
7745     CmdArgs.push_back(II.getFilename());
7746
7747   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7748   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7749 }
7750
7751 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7752                                   const InputInfo &Output,
7753                                   const InputInfoList &Inputs,
7754                                   const ArgList &Args,
7755                                   const char *LinkingOutput) const {
7756   const Driver &D = getToolChain().getDriver();
7757   ArgStringList CmdArgs;
7758
7759   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7760     CmdArgs.push_back("-e");
7761     CmdArgs.push_back("__start");
7762   }
7763
7764   if (Args.hasArg(options::OPT_static)) {
7765     CmdArgs.push_back("-Bstatic");
7766   } else {
7767     if (Args.hasArg(options::OPT_rdynamic))
7768       CmdArgs.push_back("-export-dynamic");
7769     CmdArgs.push_back("--eh-frame-hdr");
7770     CmdArgs.push_back("-Bdynamic");
7771     if (Args.hasArg(options::OPT_shared)) {
7772       CmdArgs.push_back("-shared");
7773     } else {
7774       CmdArgs.push_back("-dynamic-linker");
7775       CmdArgs.push_back("/usr/libexec/ld.so");
7776     }
7777   }
7778
7779   if (Output.isFilename()) {
7780     CmdArgs.push_back("-o");
7781     CmdArgs.push_back(Output.getFilename());
7782   } else {
7783     assert(Output.isNothing() && "Invalid output.");
7784   }
7785
7786   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7787     if (!Args.hasArg(options::OPT_shared)) {
7788       if (Args.hasArg(options::OPT_pg))
7789         CmdArgs.push_back(
7790             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7791       else
7792         CmdArgs.push_back(
7793             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7794       CmdArgs.push_back(
7795           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7796     } else {
7797       CmdArgs.push_back(
7798           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7799     }
7800   }
7801
7802   Args.AddAllArgs(CmdArgs,
7803                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7804
7805   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7806
7807   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7808     if (D.CCCIsCXX()) {
7809       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7810       if (Args.hasArg(options::OPT_pg))
7811         CmdArgs.push_back("-lm_p");
7812       else
7813         CmdArgs.push_back("-lm");
7814     }
7815
7816     if (Args.hasArg(options::OPT_pthread)) {
7817       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7818         CmdArgs.push_back("-lpthread_p");
7819       else
7820         CmdArgs.push_back("-lpthread");
7821     }
7822
7823     if (!Args.hasArg(options::OPT_shared)) {
7824       if (Args.hasArg(options::OPT_pg))
7825         CmdArgs.push_back("-lc_p");
7826       else
7827         CmdArgs.push_back("-lc");
7828     }
7829
7830     StringRef MyArch;
7831     switch (getToolChain().getArch()) {
7832     case llvm::Triple::arm:
7833       MyArch = "arm";
7834       break;
7835     case llvm::Triple::x86:
7836       MyArch = "i386";
7837       break;
7838     case llvm::Triple::x86_64:
7839       MyArch = "amd64";
7840       break;
7841     default:
7842       llvm_unreachable("Unsupported architecture");
7843     }
7844     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7845   }
7846
7847   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7848     if (!Args.hasArg(options::OPT_shared))
7849       CmdArgs.push_back(
7850           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7851     else
7852       CmdArgs.push_back(
7853           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7854   }
7855
7856   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7857   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7858 }
7859
7860 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7861                                       const InputInfo &Output,
7862                                       const InputInfoList &Inputs,
7863                                       const ArgList &Args,
7864                                       const char *LinkingOutput) const {
7865   claimNoWarnArgs(Args);
7866   ArgStringList CmdArgs;
7867
7868   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7869   // instruct as in the base system to assemble 32-bit code.
7870   switch (getToolChain().getArch()) {
7871   default:
7872     break;
7873   case llvm::Triple::x86:
7874     CmdArgs.push_back("--32");
7875     break;
7876   case llvm::Triple::ppc:
7877     CmdArgs.push_back("-a32");
7878     break;
7879   case llvm::Triple::mips:
7880   case llvm::Triple::mipsel:
7881   case llvm::Triple::mips64:
7882   case llvm::Triple::mips64el: {
7883     StringRef CPUName;
7884     StringRef ABIName;
7885     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7886
7887     CmdArgs.push_back("-march");
7888     CmdArgs.push_back(CPUName.data());
7889
7890     CmdArgs.push_back("-mabi");
7891     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7892
7893     if (getToolChain().getArch() == llvm::Triple::mips ||
7894         getToolChain().getArch() == llvm::Triple::mips64)
7895       CmdArgs.push_back("-EB");
7896     else
7897       CmdArgs.push_back("-EL");
7898
7899     if (Arg *A = Args.getLastArg(options::OPT_G)) {
7900       StringRef v = A->getValue();
7901       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7902       A->claim();
7903     }
7904
7905     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7906     break;
7907   }
7908   case llvm::Triple::arm:
7909   case llvm::Triple::armeb:
7910   case llvm::Triple::thumb:
7911   case llvm::Triple::thumbeb: {
7912     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7913
7914     if (ABI == arm::FloatABI::Hard)
7915       CmdArgs.push_back("-mfpu=vfp");
7916     else
7917       CmdArgs.push_back("-mfpu=softvfp");
7918
7919     switch (getToolChain().getTriple().getEnvironment()) {
7920     case llvm::Triple::GNUEABIHF:
7921     case llvm::Triple::GNUEABI:
7922     case llvm::Triple::EABI:
7923       CmdArgs.push_back("-meabi=5");
7924       break;
7925
7926     default:
7927       CmdArgs.push_back("-matpcs");
7928     }
7929     break;
7930   }
7931   case llvm::Triple::sparc:
7932   case llvm::Triple::sparcel:
7933   case llvm::Triple::sparcv9: {
7934     std::string CPU = getCPUName(Args, getToolChain().getTriple());
7935     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7936     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7937     break;
7938   }
7939   }
7940
7941   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7942
7943   CmdArgs.push_back("-o");
7944   CmdArgs.push_back(Output.getFilename());
7945
7946   for (const auto &II : Inputs)
7947     CmdArgs.push_back(II.getFilename());
7948
7949   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7950   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7951 }
7952
7953 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7954                                    const InputInfo &Output,
7955                                    const InputInfoList &Inputs,
7956                                    const ArgList &Args,
7957                                    const char *LinkingOutput) const {
7958   const toolchains::FreeBSD &ToolChain =
7959       static_cast<const toolchains::FreeBSD &>(getToolChain());
7960   const Driver &D = ToolChain.getDriver();
7961   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7962   const bool IsPIE =
7963       !Args.hasArg(options::OPT_shared) &&
7964       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7965   ArgStringList CmdArgs;
7966
7967   // Silence warning for "clang -g foo.o -o foo"
7968   Args.ClaimAllArgs(options::OPT_g_Group);
7969   // and "clang -emit-llvm foo.o -o foo"
7970   Args.ClaimAllArgs(options::OPT_emit_llvm);
7971   // and for "clang -w foo.o -o foo". Other warning options are already
7972   // handled somewhere else.
7973   Args.ClaimAllArgs(options::OPT_w);
7974
7975   if (!D.SysRoot.empty())
7976     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7977
7978   if (IsPIE)
7979     CmdArgs.push_back("-pie");
7980
7981   if (Args.hasArg(options::OPT_static)) {
7982     CmdArgs.push_back("-Bstatic");
7983   } else {
7984     if (Args.hasArg(options::OPT_rdynamic))
7985       CmdArgs.push_back("-export-dynamic");
7986     CmdArgs.push_back("--eh-frame-hdr");
7987     if (Args.hasArg(options::OPT_shared)) {
7988       CmdArgs.push_back("-Bshareable");
7989     } else {
7990       CmdArgs.push_back("-dynamic-linker");
7991       CmdArgs.push_back("/libexec/ld-elf.so.1");
7992     }
7993     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7994       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7995           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7996         CmdArgs.push_back("--hash-style=both");
7997       }
7998     }
7999     CmdArgs.push_back("--enable-new-dtags");
8000   }
8001
8002   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8003   // instruct ld in the base system to link 32-bit code.
8004   if (Arch == llvm::Triple::x86) {
8005     CmdArgs.push_back("-m");
8006     CmdArgs.push_back("elf_i386_fbsd");
8007   }
8008
8009   if (Arch == llvm::Triple::ppc) {
8010     CmdArgs.push_back("-m");
8011     CmdArgs.push_back("elf32ppc_fbsd");
8012   }
8013
8014   if (Arg *A = Args.getLastArg(options::OPT_G)) {
8015     if (ToolChain.getArch() == llvm::Triple::mips ||
8016       ToolChain.getArch() == llvm::Triple::mipsel ||
8017       ToolChain.getArch() == llvm::Triple::mips64 ||
8018       ToolChain.getArch() == llvm::Triple::mips64el) {
8019       StringRef v = A->getValue();
8020       CmdArgs.push_back(Args.MakeArgString("-G" + v));
8021       A->claim();
8022     }
8023   }
8024
8025   if (Output.isFilename()) {
8026     CmdArgs.push_back("-o");
8027     CmdArgs.push_back(Output.getFilename());
8028   } else {
8029     assert(Output.isNothing() && "Invalid output.");
8030   }
8031
8032   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8033     const char *crt1 = nullptr;
8034     if (!Args.hasArg(options::OPT_shared)) {
8035       if (Args.hasArg(options::OPT_pg))
8036         crt1 = "gcrt1.o";
8037       else if (IsPIE)
8038         crt1 = "Scrt1.o";
8039       else
8040         crt1 = "crt1.o";
8041     }
8042     if (crt1)
8043       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8044
8045     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8046
8047     const char *crtbegin = nullptr;
8048     if (Args.hasArg(options::OPT_static))
8049       crtbegin = "crtbeginT.o";
8050     else if (Args.hasArg(options::OPT_shared) || IsPIE)
8051       crtbegin = "crtbeginS.o";
8052     else
8053       crtbegin = "crtbegin.o";
8054
8055     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8056   }
8057
8058   Args.AddAllArgs(CmdArgs, options::OPT_L);
8059   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8060   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8061   Args.AddAllArgs(CmdArgs, options::OPT_e);
8062   Args.AddAllArgs(CmdArgs, options::OPT_s);
8063   Args.AddAllArgs(CmdArgs, options::OPT_t);
8064   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8065   Args.AddAllArgs(CmdArgs, options::OPT_r);
8066
8067   if (D.isUsingLTO())
8068     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8069
8070   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8071   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8072
8073   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8074     addOpenMPRuntime(CmdArgs, ToolChain, Args);
8075     if (D.CCCIsCXX()) {
8076       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8077       if (Args.hasArg(options::OPT_pg))
8078         CmdArgs.push_back("-lm_p");
8079       else
8080         CmdArgs.push_back("-lm");
8081     }
8082     if (NeedsSanitizerDeps)
8083       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8084     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8085     // the default system libraries. Just mimic this for now.
8086     if (Args.hasArg(options::OPT_pg))
8087       CmdArgs.push_back("-lgcc_p");
8088     else
8089       CmdArgs.push_back("-lgcc");
8090     if (Args.hasArg(options::OPT_static)) {
8091       CmdArgs.push_back("-lgcc_eh");
8092     } else if (Args.hasArg(options::OPT_pg)) {
8093       CmdArgs.push_back("-lgcc_eh_p");
8094     } else {
8095       CmdArgs.push_back("--as-needed");
8096       CmdArgs.push_back("-lgcc_s");
8097       CmdArgs.push_back("--no-as-needed");
8098     }
8099
8100     if (Args.hasArg(options::OPT_pthread)) {
8101       if (Args.hasArg(options::OPT_pg))
8102         CmdArgs.push_back("-lpthread_p");
8103       else
8104         CmdArgs.push_back("-lpthread");
8105     }
8106
8107     if (Args.hasArg(options::OPT_pg)) {
8108       if (Args.hasArg(options::OPT_shared))
8109         CmdArgs.push_back("-lc");
8110       else
8111         CmdArgs.push_back("-lc_p");
8112       CmdArgs.push_back("-lgcc_p");
8113     } else {
8114       CmdArgs.push_back("-lc");
8115       CmdArgs.push_back("-lgcc");
8116     }
8117
8118     if (Args.hasArg(options::OPT_static)) {
8119       CmdArgs.push_back("-lgcc_eh");
8120     } else if (Args.hasArg(options::OPT_pg)) {
8121       CmdArgs.push_back("-lgcc_eh_p");
8122     } else {
8123       CmdArgs.push_back("--as-needed");
8124       CmdArgs.push_back("-lgcc_s");
8125       CmdArgs.push_back("--no-as-needed");
8126     }
8127   }
8128
8129   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8130     if (Args.hasArg(options::OPT_shared) || IsPIE)
8131       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8132     else
8133       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8134     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8135   }
8136
8137   ToolChain.addProfileRTLibs(Args, CmdArgs);
8138
8139   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8140   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8141 }
8142
8143 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8144                                      const InputInfo &Output,
8145                                      const InputInfoList &Inputs,
8146                                      const ArgList &Args,
8147                                      const char *LinkingOutput) const {
8148   claimNoWarnArgs(Args);
8149   ArgStringList CmdArgs;
8150
8151   // GNU as needs different flags for creating the correct output format
8152   // on architectures with different ABIs or optional feature sets.
8153   switch (getToolChain().getArch()) {
8154   case llvm::Triple::x86:
8155     CmdArgs.push_back("--32");
8156     break;
8157   case llvm::Triple::arm:
8158   case llvm::Triple::armeb:
8159   case llvm::Triple::thumb:
8160   case llvm::Triple::thumbeb: {
8161     StringRef MArch, MCPU;
8162     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8163     std::string Arch =
8164         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8165     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8166     break;
8167   }
8168
8169   case llvm::Triple::mips:
8170   case llvm::Triple::mipsel:
8171   case llvm::Triple::mips64:
8172   case llvm::Triple::mips64el: {
8173     StringRef CPUName;
8174     StringRef ABIName;
8175     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8176
8177     CmdArgs.push_back("-march");
8178     CmdArgs.push_back(CPUName.data());
8179
8180     CmdArgs.push_back("-mabi");
8181     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8182
8183     if (getToolChain().getArch() == llvm::Triple::mips ||
8184         getToolChain().getArch() == llvm::Triple::mips64)
8185       CmdArgs.push_back("-EB");
8186     else
8187       CmdArgs.push_back("-EL");
8188
8189     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8190     break;
8191   }
8192
8193   case llvm::Triple::sparc:
8194   case llvm::Triple::sparcel: {
8195     CmdArgs.push_back("-32");
8196     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8197     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8198     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8199     break;
8200   }
8201
8202   case llvm::Triple::sparcv9: {
8203     CmdArgs.push_back("-64");
8204     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8205     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8206     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8207     break;
8208   }
8209
8210   default:
8211     break;
8212   }
8213
8214   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8215
8216   CmdArgs.push_back("-o");
8217   CmdArgs.push_back(Output.getFilename());
8218
8219   for (const auto &II : Inputs)
8220     CmdArgs.push_back(II.getFilename());
8221
8222   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8223   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8224 }
8225
8226 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8227                                   const InputInfo &Output,
8228                                   const InputInfoList &Inputs,
8229                                   const ArgList &Args,
8230                                   const char *LinkingOutput) const {
8231   const Driver &D = getToolChain().getDriver();
8232   ArgStringList CmdArgs;
8233
8234   if (!D.SysRoot.empty())
8235     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8236
8237   CmdArgs.push_back("--eh-frame-hdr");
8238   if (Args.hasArg(options::OPT_static)) {
8239     CmdArgs.push_back("-Bstatic");
8240   } else {
8241     if (Args.hasArg(options::OPT_rdynamic))
8242       CmdArgs.push_back("-export-dynamic");
8243     if (Args.hasArg(options::OPT_shared)) {
8244       CmdArgs.push_back("-Bshareable");
8245     } else {
8246       CmdArgs.push_back("-dynamic-linker");
8247       CmdArgs.push_back("/libexec/ld.elf_so");
8248     }
8249   }
8250
8251   // Many NetBSD architectures support more than one ABI.
8252   // Determine the correct emulation for ld.
8253   switch (getToolChain().getArch()) {
8254   case llvm::Triple::x86:
8255     CmdArgs.push_back("-m");
8256     CmdArgs.push_back("elf_i386");
8257     break;
8258   case llvm::Triple::arm:
8259   case llvm::Triple::thumb:
8260     CmdArgs.push_back("-m");
8261     switch (getToolChain().getTriple().getEnvironment()) {
8262     case llvm::Triple::EABI:
8263     case llvm::Triple::GNUEABI:
8264       CmdArgs.push_back("armelf_nbsd_eabi");
8265       break;
8266     case llvm::Triple::EABIHF:
8267     case llvm::Triple::GNUEABIHF:
8268       CmdArgs.push_back("armelf_nbsd_eabihf");
8269       break;
8270     default:
8271       CmdArgs.push_back("armelf_nbsd");
8272       break;
8273     }
8274     break;
8275   case llvm::Triple::armeb:
8276   case llvm::Triple::thumbeb:
8277     arm::appendEBLinkFlags(
8278         Args, CmdArgs,
8279         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8280     CmdArgs.push_back("-m");
8281     switch (getToolChain().getTriple().getEnvironment()) {
8282     case llvm::Triple::EABI:
8283     case llvm::Triple::GNUEABI:
8284       CmdArgs.push_back("armelfb_nbsd_eabi");
8285       break;
8286     case llvm::Triple::EABIHF:
8287     case llvm::Triple::GNUEABIHF:
8288       CmdArgs.push_back("armelfb_nbsd_eabihf");
8289       break;
8290     default:
8291       CmdArgs.push_back("armelfb_nbsd");
8292       break;
8293     }
8294     break;
8295   case llvm::Triple::mips64:
8296   case llvm::Triple::mips64el:
8297     if (mips::hasMipsAbiArg(Args, "32")) {
8298       CmdArgs.push_back("-m");
8299       if (getToolChain().getArch() == llvm::Triple::mips64)
8300         CmdArgs.push_back("elf32btsmip");
8301       else
8302         CmdArgs.push_back("elf32ltsmip");
8303     } else if (mips::hasMipsAbiArg(Args, "64")) {
8304       CmdArgs.push_back("-m");
8305       if (getToolChain().getArch() == llvm::Triple::mips64)
8306         CmdArgs.push_back("elf64btsmip");
8307       else
8308         CmdArgs.push_back("elf64ltsmip");
8309     }
8310     break;
8311   case llvm::Triple::ppc:
8312     CmdArgs.push_back("-m");
8313     CmdArgs.push_back("elf32ppc_nbsd");
8314     break;
8315
8316   case llvm::Triple::ppc64:
8317   case llvm::Triple::ppc64le:
8318     CmdArgs.push_back("-m");
8319     CmdArgs.push_back("elf64ppc");
8320     break;
8321
8322   case llvm::Triple::sparc:
8323     CmdArgs.push_back("-m");
8324     CmdArgs.push_back("elf32_sparc");
8325     break;
8326
8327   case llvm::Triple::sparcv9:
8328     CmdArgs.push_back("-m");
8329     CmdArgs.push_back("elf64_sparc");
8330     break;
8331
8332   default:
8333     break;
8334   }
8335
8336   if (Output.isFilename()) {
8337     CmdArgs.push_back("-o");
8338     CmdArgs.push_back(Output.getFilename());
8339   } else {
8340     assert(Output.isNothing() && "Invalid output.");
8341   }
8342
8343   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8344     if (!Args.hasArg(options::OPT_shared)) {
8345       CmdArgs.push_back(
8346           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8347       CmdArgs.push_back(
8348           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8349       CmdArgs.push_back(
8350           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8351     } else {
8352       CmdArgs.push_back(
8353           Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8354       CmdArgs.push_back(
8355           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8356     }
8357   }
8358
8359   Args.AddAllArgs(CmdArgs, options::OPT_L);
8360   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8361   Args.AddAllArgs(CmdArgs, options::OPT_e);
8362   Args.AddAllArgs(CmdArgs, options::OPT_s);
8363   Args.AddAllArgs(CmdArgs, options::OPT_t);
8364   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8365   Args.AddAllArgs(CmdArgs, options::OPT_r);
8366
8367   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8368
8369   unsigned Major, Minor, Micro;
8370   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8371   bool useLibgcc = true;
8372   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8373     switch (getToolChain().getArch()) {
8374     case llvm::Triple::aarch64:
8375     case llvm::Triple::arm:
8376     case llvm::Triple::armeb:
8377     case llvm::Triple::thumb:
8378     case llvm::Triple::thumbeb:
8379     case llvm::Triple::ppc:
8380     case llvm::Triple::ppc64:
8381     case llvm::Triple::ppc64le:
8382     case llvm::Triple::x86:
8383     case llvm::Triple::x86_64:
8384       useLibgcc = false;
8385       break;
8386     default:
8387       break;
8388     }
8389   }
8390
8391   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8392     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8393     if (D.CCCIsCXX()) {
8394       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8395       CmdArgs.push_back("-lm");
8396     }
8397     if (Args.hasArg(options::OPT_pthread))
8398       CmdArgs.push_back("-lpthread");
8399     CmdArgs.push_back("-lc");
8400
8401     if (useLibgcc) {
8402       if (Args.hasArg(options::OPT_static)) {
8403         // libgcc_eh depends on libc, so resolve as much as possible,
8404         // pull in any new requirements from libc and then get the rest
8405         // of libgcc.
8406         CmdArgs.push_back("-lgcc_eh");
8407         CmdArgs.push_back("-lc");
8408         CmdArgs.push_back("-lgcc");
8409       } else {
8410         CmdArgs.push_back("-lgcc");
8411         CmdArgs.push_back("--as-needed");
8412         CmdArgs.push_back("-lgcc_s");
8413         CmdArgs.push_back("--no-as-needed");
8414       }
8415     }
8416   }
8417
8418   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8419     if (!Args.hasArg(options::OPT_shared))
8420       CmdArgs.push_back(
8421           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8422     else
8423       CmdArgs.push_back(
8424           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8425     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8426   }
8427
8428   getToolChain().addProfileRTLibs(Args, CmdArgs);
8429
8430   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8431   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8432 }
8433
8434 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8435                                        const InputInfo &Output,
8436                                        const InputInfoList &Inputs,
8437                                        const ArgList &Args,
8438                                        const char *LinkingOutput) const {
8439   claimNoWarnArgs(Args);
8440
8441   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8442   llvm::Triple Triple = llvm::Triple(TripleStr);
8443
8444   ArgStringList CmdArgs;
8445
8446   llvm::Reloc::Model RelocationModel;
8447   unsigned PICLevel;
8448   bool IsPIE;
8449   std::tie(RelocationModel, PICLevel, IsPIE) =
8450       ParsePICArgs(getToolChain(), Triple, Args);
8451
8452   switch (getToolChain().getArch()) {
8453   default:
8454     break;
8455   // Add --32/--64 to make sure we get the format we want.
8456   // This is incomplete
8457   case llvm::Triple::x86:
8458     CmdArgs.push_back("--32");
8459     break;
8460   case llvm::Triple::x86_64:
8461     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8462       CmdArgs.push_back("--x32");
8463     else
8464       CmdArgs.push_back("--64");
8465     break;
8466   case llvm::Triple::ppc:
8467     CmdArgs.push_back("-a32");
8468     CmdArgs.push_back("-mppc");
8469     CmdArgs.push_back("-many");
8470     break;
8471   case llvm::Triple::ppc64:
8472     CmdArgs.push_back("-a64");
8473     CmdArgs.push_back("-mppc64");
8474     CmdArgs.push_back("-many");
8475     break;
8476   case llvm::Triple::ppc64le:
8477     CmdArgs.push_back("-a64");
8478     CmdArgs.push_back("-mppc64");
8479     CmdArgs.push_back("-many");
8480     CmdArgs.push_back("-mlittle-endian");
8481     break;
8482   case llvm::Triple::sparc:
8483   case llvm::Triple::sparcel: {
8484     CmdArgs.push_back("-32");
8485     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8486     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8487     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8488     break;
8489   }
8490   case llvm::Triple::sparcv9: {
8491     CmdArgs.push_back("-64");
8492     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8493     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8494     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8495     break;
8496   }
8497   case llvm::Triple::arm:
8498   case llvm::Triple::armeb:
8499   case llvm::Triple::thumb:
8500   case llvm::Triple::thumbeb: {
8501     const llvm::Triple &Triple2 = getToolChain().getTriple();
8502     switch (Triple2.getSubArch()) {
8503     case llvm::Triple::ARMSubArch_v7:
8504       CmdArgs.push_back("-mfpu=neon");
8505       break;
8506     case llvm::Triple::ARMSubArch_v8:
8507       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8508       break;
8509     default:
8510       break;
8511     }
8512
8513     switch (arm::getARMFloatABI(getToolChain(), Args)) {
8514     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8515     case arm::FloatABI::Soft:
8516       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8517       break;
8518     case arm::FloatABI::SoftFP:
8519       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8520       break;
8521     case arm::FloatABI::Hard:
8522       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8523       break;
8524     }
8525
8526     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8527
8528     // FIXME: remove krait check when GNU tools support krait cpu
8529     // for now replace it with -march=armv7-a  to avoid a lower
8530     // march from being picked in the absence of a cpu flag.
8531     Arg *A;
8532     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8533         StringRef(A->getValue()).lower() == "krait")
8534       CmdArgs.push_back("-march=armv7-a");
8535     else
8536       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8537     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8538     break;
8539   }
8540   case llvm::Triple::mips:
8541   case llvm::Triple::mipsel:
8542   case llvm::Triple::mips64:
8543   case llvm::Triple::mips64el: {
8544     StringRef CPUName;
8545     StringRef ABIName;
8546     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8547     ABIName = getGnuCompatibleMipsABIName(ABIName);
8548
8549     CmdArgs.push_back("-march");
8550     CmdArgs.push_back(CPUName.data());
8551
8552     CmdArgs.push_back("-mabi");
8553     CmdArgs.push_back(ABIName.data());
8554
8555     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8556     // or -mshared (not implemented) is in effect.
8557     if (RelocationModel == llvm::Reloc::Static)
8558       CmdArgs.push_back("-mno-shared");
8559
8560     // LLVM doesn't support -mplt yet and acts as if it is always given.
8561     // However, -mplt has no effect with the N64 ABI.
8562     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8563
8564     if (getToolChain().getArch() == llvm::Triple::mips ||
8565         getToolChain().getArch() == llvm::Triple::mips64)
8566       CmdArgs.push_back("-EB");
8567     else
8568       CmdArgs.push_back("-EL");
8569
8570     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8571       if (StringRef(A->getValue()) == "2008")
8572         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8573     }
8574
8575     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8576     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8577                                  options::OPT_mfp64)) {
8578       A->claim();
8579       A->render(Args, CmdArgs);
8580     } else if (mips::shouldUseFPXX(
8581                    Args, getToolChain().getTriple(), CPUName, ABIName,
8582                    getMipsFloatABI(getToolChain().getDriver(), Args)))
8583       CmdArgs.push_back("-mfpxx");
8584
8585     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8586     // -mno-mips16 is actually -no-mips16.
8587     if (Arg *A =
8588             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8589       if (A->getOption().matches(options::OPT_mips16)) {
8590         A->claim();
8591         A->render(Args, CmdArgs);
8592       } else {
8593         A->claim();
8594         CmdArgs.push_back("-no-mips16");
8595       }
8596     }
8597
8598     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8599                     options::OPT_mno_micromips);
8600     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8601     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8602
8603     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8604       // Do not use AddLastArg because not all versions of MIPS assembler
8605       // support -mmsa / -mno-msa options.
8606       if (A->getOption().matches(options::OPT_mmsa))
8607         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8608     }
8609
8610     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8611                     options::OPT_msoft_float);
8612
8613     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8614                     options::OPT_msingle_float);
8615
8616     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8617                     options::OPT_mno_odd_spreg);
8618
8619     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8620     break;
8621   }
8622   case llvm::Triple::systemz: {
8623     // Always pass an -march option, since our default of z10 is later
8624     // than the GNU assembler's default.
8625     StringRef CPUName = getSystemZTargetCPU(Args);
8626     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8627     break;
8628   }
8629   }
8630
8631   Args.AddAllArgs(CmdArgs, options::OPT_I);
8632   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8633
8634   CmdArgs.push_back("-o");
8635   CmdArgs.push_back(Output.getFilename());
8636
8637   for (const auto &II : Inputs)
8638     CmdArgs.push_back(II.getFilename());
8639
8640   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8641   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8642
8643   // Handle the debug info splitting at object creation time if we're
8644   // creating an object.
8645   // TODO: Currently only works on linux with newer objcopy.
8646   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8647       getToolChain().getTriple().isOSLinux())
8648     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8649                    SplitDebugName(Args, Inputs[0]));
8650 }
8651
8652 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8653                       ArgStringList &CmdArgs, const ArgList &Args) {
8654   bool isAndroid = Triple.isAndroid();
8655   bool isCygMing = Triple.isOSCygMing();
8656   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8657                       Args.hasArg(options::OPT_static);
8658   if (!D.CCCIsCXX())
8659     CmdArgs.push_back("-lgcc");
8660
8661   if (StaticLibgcc || isAndroid) {
8662     if (D.CCCIsCXX())
8663       CmdArgs.push_back("-lgcc");
8664   } else {
8665     if (!D.CCCIsCXX() && !isCygMing)
8666       CmdArgs.push_back("--as-needed");
8667     CmdArgs.push_back("-lgcc_s");
8668     if (!D.CCCIsCXX() && !isCygMing)
8669       CmdArgs.push_back("--no-as-needed");
8670   }
8671
8672   if (StaticLibgcc && !isAndroid)
8673     CmdArgs.push_back("-lgcc_eh");
8674   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8675     CmdArgs.push_back("-lgcc");
8676
8677   // According to Android ABI, we have to link with libdl if we are
8678   // linking with non-static libgcc.
8679   //
8680   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
8681   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8682   if (isAndroid && !StaticLibgcc)
8683     CmdArgs.push_back("-ldl");
8684 }
8685
8686 static std::string getLinuxDynamicLinker(const ArgList &Args,
8687                                          const toolchains::Linux &ToolChain) {
8688   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8689
8690   if (ToolChain.getTriple().isAndroid()) {
8691     if (ToolChain.getTriple().isArch64Bit())
8692       return "/system/bin/linker64";
8693     else
8694       return "/system/bin/linker";
8695   } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8696              Arch == llvm::Triple::sparcel)
8697     return "/lib/ld-linux.so.2";
8698   else if (Arch == llvm::Triple::aarch64)
8699     return "/lib/ld-linux-aarch64.so.1";
8700   else if (Arch == llvm::Triple::aarch64_be)
8701     return "/lib/ld-linux-aarch64_be.so.1";
8702   else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8703     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8704         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8705       return "/lib/ld-linux-armhf.so.3";
8706     else
8707       return "/lib/ld-linux.so.3";
8708   } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8709     // TODO: check which dynamic linker name.
8710     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8711         arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8712       return "/lib/ld-linux-armhf.so.3";
8713     else
8714       return "/lib/ld-linux.so.3";
8715   } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8716              Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8717     std::string LibDir =
8718         "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8719     StringRef LibName;
8720     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8721     if (mips::isUCLibc(Args))
8722       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8723     else if (!ToolChain.getTriple().hasEnvironment()) {
8724       bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8725                 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8726       LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8727     } else
8728       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8729
8730     return (LibDir + "/" + LibName).str();
8731   } else if (Arch == llvm::Triple::ppc)
8732     return "/lib/ld.so.1";
8733   else if (Arch == llvm::Triple::ppc64) {
8734     if (ppc::hasPPCAbiArg(Args, "elfv2"))
8735       return "/lib64/ld64.so.2";
8736     return "/lib64/ld64.so.1";
8737   } else if (Arch == llvm::Triple::ppc64le) {
8738     if (ppc::hasPPCAbiArg(Args, "elfv1"))
8739       return "/lib64/ld64.so.1";
8740     return "/lib64/ld64.so.2";
8741   } else if (Arch == llvm::Triple::systemz)
8742     return "/lib/ld64.so.1";
8743   else if (Arch == llvm::Triple::sparcv9)
8744     return "/lib64/ld-linux.so.2";
8745   else if (Arch == llvm::Triple::x86_64 &&
8746            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8747     return "/libx32/ld-linux-x32.so.2";
8748   else
8749     return "/lib64/ld-linux-x86-64.so.2";
8750 }
8751
8752 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8753                            ArgStringList &CmdArgs, const ArgList &Args) {
8754   // Make use of compiler-rt if --rtlib option is used
8755   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8756
8757   switch (RLT) {
8758   case ToolChain::RLT_CompilerRT:
8759     switch (TC.getTriple().getOS()) {
8760     default:
8761       llvm_unreachable("unsupported OS");
8762     case llvm::Triple::Win32:
8763     case llvm::Triple::Linux:
8764       addClangRT(TC, Args, CmdArgs);
8765       break;
8766     }
8767     break;
8768   case ToolChain::RLT_Libgcc:
8769     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8770     break;
8771   }
8772 }
8773
8774 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8775   switch (T.getArch()) {
8776   case llvm::Triple::x86:
8777     return "elf_i386";
8778   case llvm::Triple::aarch64:
8779     return "aarch64linux";
8780   case llvm::Triple::aarch64_be:
8781     return "aarch64_be_linux";
8782   case llvm::Triple::arm:
8783   case llvm::Triple::thumb:
8784     return "armelf_linux_eabi";
8785   case llvm::Triple::armeb:
8786   case llvm::Triple::thumbeb:
8787     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
8788   case llvm::Triple::ppc:
8789     return "elf32ppclinux";
8790   case llvm::Triple::ppc64:
8791     return "elf64ppc";
8792   case llvm::Triple::ppc64le:
8793     return "elf64lppc";
8794   case llvm::Triple::sparc:
8795   case llvm::Triple::sparcel:
8796     return "elf32_sparc";
8797   case llvm::Triple::sparcv9:
8798     return "elf64_sparc";
8799   case llvm::Triple::mips:
8800     return "elf32btsmip";
8801   case llvm::Triple::mipsel:
8802     return "elf32ltsmip";
8803   case llvm::Triple::mips64:
8804     if (mips::hasMipsAbiArg(Args, "n32"))
8805       return "elf32btsmipn32";
8806     return "elf64btsmip";
8807   case llvm::Triple::mips64el:
8808     if (mips::hasMipsAbiArg(Args, "n32"))
8809       return "elf32ltsmipn32";
8810     return "elf64ltsmip";
8811   case llvm::Triple::systemz:
8812     return "elf64_s390";
8813   case llvm::Triple::x86_64:
8814     if (T.getEnvironment() == llvm::Triple::GNUX32)
8815       return "elf32_x86_64";
8816     return "elf_x86_64";
8817   default:
8818     llvm_unreachable("Unexpected arch");
8819   }
8820 }
8821
8822 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8823                                     const InputInfo &Output,
8824                                     const InputInfoList &Inputs,
8825                                     const ArgList &Args,
8826                                     const char *LinkingOutput) const {
8827   const toolchains::Linux &ToolChain =
8828       static_cast<const toolchains::Linux &>(getToolChain());
8829   const Driver &D = ToolChain.getDriver();
8830
8831   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8832   llvm::Triple Triple = llvm::Triple(TripleStr);
8833
8834   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8835   const bool isAndroid = ToolChain.getTriple().isAndroid();
8836   const bool IsPIE =
8837       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8838       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8839   const bool HasCRTBeginEndFiles =
8840       ToolChain.getTriple().hasEnvironment() ||
8841       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8842
8843   ArgStringList CmdArgs;
8844
8845   // Silence warning for "clang -g foo.o -o foo"
8846   Args.ClaimAllArgs(options::OPT_g_Group);
8847   // and "clang -emit-llvm foo.o -o foo"
8848   Args.ClaimAllArgs(options::OPT_emit_llvm);
8849   // and for "clang -w foo.o -o foo". Other warning options are already
8850   // handled somewhere else.
8851   Args.ClaimAllArgs(options::OPT_w);
8852
8853   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8854   if (llvm::sys::path::filename(Exec) == "lld") {
8855     CmdArgs.push_back("-flavor");
8856     CmdArgs.push_back("old-gnu");
8857     CmdArgs.push_back("-target");
8858     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8859   }
8860
8861   if (!D.SysRoot.empty())
8862     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8863
8864   if (IsPIE)
8865     CmdArgs.push_back("-pie");
8866
8867   if (Args.hasArg(options::OPT_rdynamic))
8868     CmdArgs.push_back("-export-dynamic");
8869
8870   if (Args.hasArg(options::OPT_s))
8871     CmdArgs.push_back("-s");
8872
8873   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8874     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8875
8876   for (const auto &Opt : ToolChain.ExtraOpts)
8877     CmdArgs.push_back(Opt.c_str());
8878
8879   if (!Args.hasArg(options::OPT_static)) {
8880     CmdArgs.push_back("--eh-frame-hdr");
8881   }
8882
8883   CmdArgs.push_back("-m");
8884   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8885
8886   if (Args.hasArg(options::OPT_static)) {
8887     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8888         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8889       CmdArgs.push_back("-Bstatic");
8890     else
8891       CmdArgs.push_back("-static");
8892   } else if (Args.hasArg(options::OPT_shared)) {
8893     CmdArgs.push_back("-shared");
8894   }
8895
8896   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8897       Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8898       (!Args.hasArg(options::OPT_static) &&
8899        !Args.hasArg(options::OPT_shared))) {
8900     CmdArgs.push_back("-dynamic-linker");
8901     CmdArgs.push_back(Args.MakeArgString(
8902         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8903   }
8904
8905   CmdArgs.push_back("-o");
8906   CmdArgs.push_back(Output.getFilename());
8907
8908   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8909     if (!isAndroid) {
8910       const char *crt1 = nullptr;
8911       if (!Args.hasArg(options::OPT_shared)) {
8912         if (Args.hasArg(options::OPT_pg))
8913           crt1 = "gcrt1.o";
8914         else if (IsPIE)
8915           crt1 = "Scrt1.o";
8916         else
8917           crt1 = "crt1.o";
8918       }
8919       if (crt1)
8920         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8921
8922       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8923     }
8924
8925     const char *crtbegin;
8926     if (Args.hasArg(options::OPT_static))
8927       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8928     else if (Args.hasArg(options::OPT_shared))
8929       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8930     else if (IsPIE)
8931       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8932     else
8933       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8934
8935     if (HasCRTBeginEndFiles)
8936       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8937
8938     // Add crtfastmath.o if available and fast math is enabled.
8939     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8940   }
8941
8942   Args.AddAllArgs(CmdArgs, options::OPT_L);
8943   Args.AddAllArgs(CmdArgs, options::OPT_u);
8944
8945   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8946
8947   if (D.isUsingLTO())
8948     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8949
8950   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8951     CmdArgs.push_back("--no-demangle");
8952
8953   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8954   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8955   // The profile runtime also needs access to system libraries.
8956   getToolChain().addProfileRTLibs(Args, CmdArgs);
8957
8958   if (D.CCCIsCXX() &&
8959       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8960     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8961                                !Args.hasArg(options::OPT_static);
8962     if (OnlyLibstdcxxStatic)
8963       CmdArgs.push_back("-Bstatic");
8964     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8965     if (OnlyLibstdcxxStatic)
8966       CmdArgs.push_back("-Bdynamic");
8967     CmdArgs.push_back("-lm");
8968   }
8969   // Silence warnings when linking C code with a C++ '-stdlib' argument.
8970   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8971
8972   if (!Args.hasArg(options::OPT_nostdlib)) {
8973     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8974       if (Args.hasArg(options::OPT_static))
8975         CmdArgs.push_back("--start-group");
8976
8977       if (NeedsSanitizerDeps)
8978         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8979
8980       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8981                          Args.hasArg(options::OPT_pthreads);
8982
8983       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8984                        options::OPT_fno_openmp, false)) {
8985         // OpenMP runtimes implies pthreads when using the GNU toolchain.
8986         // FIXME: Does this really make sense for all GNU toolchains?
8987         WantPthread = true;
8988
8989         // Also link the particular OpenMP runtimes.
8990         switch (getOpenMPRuntime(ToolChain, Args)) {
8991         case OMPRT_OMP:
8992           CmdArgs.push_back("-lomp");
8993           break;
8994         case OMPRT_GOMP:
8995           CmdArgs.push_back("-lgomp");
8996
8997           // FIXME: Exclude this for platforms with libgomp that don't require
8998           // librt. Most modern Linux platforms require it, but some may not.
8999           CmdArgs.push_back("-lrt");
9000           break;
9001         case OMPRT_IOMP5:
9002           CmdArgs.push_back("-liomp5");
9003           break;
9004         case OMPRT_Unknown:
9005           // Already diagnosed.
9006           break;
9007         }
9008       }
9009
9010       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9011
9012       if (WantPthread && !isAndroid)
9013         CmdArgs.push_back("-lpthread");
9014
9015       if (Args.hasArg(options::OPT_fsplit_stack))
9016         CmdArgs.push_back("--wrap=pthread_create");
9017
9018       CmdArgs.push_back("-lc");
9019
9020       if (Args.hasArg(options::OPT_static))
9021         CmdArgs.push_back("--end-group");
9022       else
9023         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9024     }
9025
9026     if (!Args.hasArg(options::OPT_nostartfiles)) {
9027       const char *crtend;
9028       if (Args.hasArg(options::OPT_shared))
9029         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9030       else if (IsPIE)
9031         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9032       else
9033         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9034
9035       if (HasCRTBeginEndFiles)
9036         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9037       if (!isAndroid)
9038         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9039     }
9040   }
9041
9042   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9043 }
9044
9045 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9046 // for the various SFI requirements like register masking. The assembly tool
9047 // inserts the file containing the macros as an input into all the assembly
9048 // jobs.
9049 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9050                                            const InputInfo &Output,
9051                                            const InputInfoList &Inputs,
9052                                            const ArgList &Args,
9053                                            const char *LinkingOutput) const {
9054   const toolchains::NaClToolChain &ToolChain =
9055       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9056   InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9057                        "nacl-arm-macros.s");
9058   InputInfoList NewInputs;
9059   NewInputs.push_back(NaClMacros);
9060   NewInputs.append(Inputs.begin(), Inputs.end());
9061   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9062                                     LinkingOutput);
9063 }
9064
9065 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9066 // we use static by default, do not yet support sanitizers or LTO, and a few
9067 // others. Eventually we can support more of that and hopefully migrate back
9068 // to gnutools::Linker.
9069 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9070                                      const InputInfo &Output,
9071                                      const InputInfoList &Inputs,
9072                                      const ArgList &Args,
9073                                      const char *LinkingOutput) const {
9074
9075   const toolchains::NaClToolChain &ToolChain =
9076       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9077   const Driver &D = ToolChain.getDriver();
9078   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9079   const bool IsStatic =
9080       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9081
9082   ArgStringList CmdArgs;
9083
9084   // Silence warning for "clang -g foo.o -o foo"
9085   Args.ClaimAllArgs(options::OPT_g_Group);
9086   // and "clang -emit-llvm foo.o -o foo"
9087   Args.ClaimAllArgs(options::OPT_emit_llvm);
9088   // and for "clang -w foo.o -o foo". Other warning options are already
9089   // handled somewhere else.
9090   Args.ClaimAllArgs(options::OPT_w);
9091
9092   if (!D.SysRoot.empty())
9093     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9094
9095   if (Args.hasArg(options::OPT_rdynamic))
9096     CmdArgs.push_back("-export-dynamic");
9097
9098   if (Args.hasArg(options::OPT_s))
9099     CmdArgs.push_back("-s");
9100
9101   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9102   // from there is --build-id, which we do want.
9103   CmdArgs.push_back("--build-id");
9104
9105   if (!IsStatic)
9106     CmdArgs.push_back("--eh-frame-hdr");
9107
9108   CmdArgs.push_back("-m");
9109   if (Arch == llvm::Triple::x86)
9110     CmdArgs.push_back("elf_i386_nacl");
9111   else if (Arch == llvm::Triple::arm)
9112     CmdArgs.push_back("armelf_nacl");
9113   else if (Arch == llvm::Triple::x86_64)
9114     CmdArgs.push_back("elf_x86_64_nacl");
9115   else if (Arch == llvm::Triple::mipsel)
9116     CmdArgs.push_back("mipselelf_nacl");
9117   else
9118     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9119                                               << "Native Client";
9120
9121   if (IsStatic)
9122     CmdArgs.push_back("-static");
9123   else if (Args.hasArg(options::OPT_shared))
9124     CmdArgs.push_back("-shared");
9125
9126   CmdArgs.push_back("-o");
9127   CmdArgs.push_back(Output.getFilename());
9128   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9129     if (!Args.hasArg(options::OPT_shared))
9130       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9131     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9132
9133     const char *crtbegin;
9134     if (IsStatic)
9135       crtbegin = "crtbeginT.o";
9136     else if (Args.hasArg(options::OPT_shared))
9137       crtbegin = "crtbeginS.o";
9138     else
9139       crtbegin = "crtbegin.o";
9140     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9141   }
9142
9143   Args.AddAllArgs(CmdArgs, options::OPT_L);
9144   Args.AddAllArgs(CmdArgs, options::OPT_u);
9145
9146   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9147
9148   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9149     CmdArgs.push_back("--no-demangle");
9150
9151   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9152
9153   if (D.CCCIsCXX() &&
9154       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9155     bool OnlyLibstdcxxStatic =
9156         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9157     if (OnlyLibstdcxxStatic)
9158       CmdArgs.push_back("-Bstatic");
9159     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9160     if (OnlyLibstdcxxStatic)
9161       CmdArgs.push_back("-Bdynamic");
9162     CmdArgs.push_back("-lm");
9163   }
9164
9165   if (!Args.hasArg(options::OPT_nostdlib)) {
9166     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9167       // Always use groups, since it has no effect on dynamic libraries.
9168       CmdArgs.push_back("--start-group");
9169       CmdArgs.push_back("-lc");
9170       // NaCl's libc++ currently requires libpthread, so just always include it
9171       // in the group for C++.
9172       if (Args.hasArg(options::OPT_pthread) ||
9173           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9174         // Gold, used by Mips, handles nested groups differently than ld, and
9175         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9176         // which is not a desired behaviour here.
9177         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9178         if (getToolChain().getArch() == llvm::Triple::mipsel)
9179           CmdArgs.push_back("-lnacl");
9180
9181         CmdArgs.push_back("-lpthread");
9182       }
9183
9184       CmdArgs.push_back("-lgcc");
9185       CmdArgs.push_back("--as-needed");
9186       if (IsStatic)
9187         CmdArgs.push_back("-lgcc_eh");
9188       else
9189         CmdArgs.push_back("-lgcc_s");
9190       CmdArgs.push_back("--no-as-needed");
9191
9192       // Mips needs to create and use pnacl_legacy library that contains
9193       // definitions from bitcode/pnaclmm.c and definitions for
9194       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9195       if (getToolChain().getArch() == llvm::Triple::mipsel)
9196         CmdArgs.push_back("-lpnacl_legacy");
9197
9198       CmdArgs.push_back("--end-group");
9199     }
9200
9201     if (!Args.hasArg(options::OPT_nostartfiles)) {
9202       const char *crtend;
9203       if (Args.hasArg(options::OPT_shared))
9204         crtend = "crtendS.o";
9205       else
9206         crtend = "crtend.o";
9207
9208       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9209       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9210     }
9211   }
9212
9213   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9214   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9215 }
9216
9217 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9218                                     const InputInfo &Output,
9219                                     const InputInfoList &Inputs,
9220                                     const ArgList &Args,
9221                                     const char *LinkingOutput) const {
9222   claimNoWarnArgs(Args);
9223   ArgStringList CmdArgs;
9224
9225   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9226
9227   CmdArgs.push_back("-o");
9228   CmdArgs.push_back(Output.getFilename());
9229
9230   for (const auto &II : Inputs)
9231     CmdArgs.push_back(II.getFilename());
9232
9233   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9234   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9235 }
9236
9237 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9238                                  const InputInfo &Output,
9239                                  const InputInfoList &Inputs,
9240                                  const ArgList &Args,
9241                                  const char *LinkingOutput) const {
9242   const Driver &D = getToolChain().getDriver();
9243   ArgStringList CmdArgs;
9244
9245   if (Output.isFilename()) {
9246     CmdArgs.push_back("-o");
9247     CmdArgs.push_back(Output.getFilename());
9248   } else {
9249     assert(Output.isNothing() && "Invalid output.");
9250   }
9251
9252   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9253     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9254     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9255     CmdArgs.push_back(
9256         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9257     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9258   }
9259
9260   Args.AddAllArgs(CmdArgs,
9261                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9262
9263   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9264
9265   getToolChain().addProfileRTLibs(Args, CmdArgs);
9266
9267   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9268     if (D.CCCIsCXX()) {
9269       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9270       CmdArgs.push_back("-lm");
9271     }
9272   }
9273
9274   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9275     if (Args.hasArg(options::OPT_pthread))
9276       CmdArgs.push_back("-lpthread");
9277     CmdArgs.push_back("-lc");
9278     CmdArgs.push_back("-lCompilerRT-Generic");
9279     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9280     CmdArgs.push_back(
9281         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9282   }
9283
9284   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9285   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9286 }
9287
9288 /// DragonFly Tools
9289
9290 // For now, DragonFly Assemble does just about the same as for
9291 // FreeBSD, but this may change soon.
9292 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9293                                         const InputInfo &Output,
9294                                         const InputInfoList &Inputs,
9295                                         const ArgList &Args,
9296                                         const char *LinkingOutput) const {
9297   claimNoWarnArgs(Args);
9298   ArgStringList CmdArgs;
9299
9300   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9301   // instruct as in the base system to assemble 32-bit code.
9302   if (getToolChain().getArch() == llvm::Triple::x86)
9303     CmdArgs.push_back("--32");
9304
9305   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9306
9307   CmdArgs.push_back("-o");
9308   CmdArgs.push_back(Output.getFilename());
9309
9310   for (const auto &II : Inputs)
9311     CmdArgs.push_back(II.getFilename());
9312
9313   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9314   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9315 }
9316
9317 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9318                                      const InputInfo &Output,
9319                                      const InputInfoList &Inputs,
9320                                      const ArgList &Args,
9321                                      const char *LinkingOutput) const {
9322   const Driver &D = getToolChain().getDriver();
9323   ArgStringList CmdArgs;
9324
9325   if (!D.SysRoot.empty())
9326     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9327
9328   CmdArgs.push_back("--eh-frame-hdr");
9329   if (Args.hasArg(options::OPT_static)) {
9330     CmdArgs.push_back("-Bstatic");
9331   } else {
9332     if (Args.hasArg(options::OPT_rdynamic))
9333       CmdArgs.push_back("-export-dynamic");
9334     if (Args.hasArg(options::OPT_shared))
9335       CmdArgs.push_back("-Bshareable");
9336     else {
9337       CmdArgs.push_back("-dynamic-linker");
9338       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9339     }
9340     CmdArgs.push_back("--hash-style=gnu");
9341     CmdArgs.push_back("--enable-new-dtags");
9342   }
9343
9344   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9345   // instruct ld in the base system to link 32-bit code.
9346   if (getToolChain().getArch() == llvm::Triple::x86) {
9347     CmdArgs.push_back("-m");
9348     CmdArgs.push_back("elf_i386");
9349   }
9350
9351   if (Output.isFilename()) {
9352     CmdArgs.push_back("-o");
9353     CmdArgs.push_back(Output.getFilename());
9354   } else {
9355     assert(Output.isNothing() && "Invalid output.");
9356   }
9357
9358   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9359     if (!Args.hasArg(options::OPT_shared)) {
9360       if (Args.hasArg(options::OPT_pg))
9361         CmdArgs.push_back(
9362             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9363       else {
9364         if (Args.hasArg(options::OPT_pie))
9365           CmdArgs.push_back(
9366               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9367         else
9368           CmdArgs.push_back(
9369               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9370       }
9371     }
9372     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9373     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9374       CmdArgs.push_back(
9375           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9376     else
9377       CmdArgs.push_back(
9378           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9379   }
9380
9381   Args.AddAllArgs(CmdArgs,
9382                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9383
9384   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9385
9386   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9387     CmdArgs.push_back("-L/usr/lib/gcc50");
9388
9389     if (!Args.hasArg(options::OPT_static)) {
9390       CmdArgs.push_back("-rpath");
9391       CmdArgs.push_back("/usr/lib/gcc50");
9392     }
9393
9394     if (D.CCCIsCXX()) {
9395       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9396       CmdArgs.push_back("-lm");
9397     }
9398
9399     if (Args.hasArg(options::OPT_pthread))
9400       CmdArgs.push_back("-lpthread");
9401
9402     if (!Args.hasArg(options::OPT_nolibc)) {
9403       CmdArgs.push_back("-lc");
9404     }
9405
9406     if (Args.hasArg(options::OPT_static) ||
9407         Args.hasArg(options::OPT_static_libgcc)) {
9408         CmdArgs.push_back("-lgcc");
9409         CmdArgs.push_back("-lgcc_eh");
9410     } else {
9411       if (Args.hasArg(options::OPT_shared_libgcc)) {
9412           CmdArgs.push_back("-lgcc_pic");
9413           if (!Args.hasArg(options::OPT_shared))
9414             CmdArgs.push_back("-lgcc");
9415       } else {
9416           CmdArgs.push_back("-lgcc");
9417           CmdArgs.push_back("--as-needed");
9418           CmdArgs.push_back("-lgcc_pic");
9419           CmdArgs.push_back("--no-as-needed");
9420       }
9421     }
9422   }
9423
9424   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9425     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9426       CmdArgs.push_back(
9427           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9428     else
9429       CmdArgs.push_back(
9430           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9431     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9432   }
9433
9434   getToolChain().addProfileRTLibs(Args, CmdArgs);
9435
9436   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9437   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9438 }
9439
9440 // Try to find Exe from a Visual Studio distribution.  This first tries to find
9441 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9442 // making sure that whatever executable that's found is not a same-named exe
9443 // from clang itself to prevent clang from falling back to itself.
9444 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9445                                               const char *Exe,
9446                                               const char *ClangProgramPath) {
9447   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9448   std::string visualStudioBinDir;
9449   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9450                                          visualStudioBinDir)) {
9451     SmallString<128> FilePath(visualStudioBinDir);
9452     llvm::sys::path::append(FilePath, Exe);
9453     if (llvm::sys::fs::can_execute(FilePath.c_str()))
9454       return FilePath.str();
9455   }
9456
9457   return Exe;
9458 }
9459
9460 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9461                                         const InputInfo &Output,
9462                                         const InputInfoList &Inputs,
9463                                         const ArgList &Args,
9464                                         const char *LinkingOutput) const {
9465   ArgStringList CmdArgs;
9466   const ToolChain &TC = getToolChain();
9467
9468   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9469   if (Output.isFilename())
9470     CmdArgs.push_back(
9471         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9472
9473   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9474       !C.getDriver().IsCLMode())
9475     CmdArgs.push_back("-defaultlib:libcmt");
9476
9477   if (!llvm::sys::Process::GetEnv("LIB")) {
9478     // If the VC environment hasn't been configured (perhaps because the user
9479     // did not run vcvarsall), try to build a consistent link environment.  If
9480     // the environment variable is set however, assume the user knows what
9481     // they're doing.
9482     std::string VisualStudioDir;
9483     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9484     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9485       SmallString<128> LibDir(VisualStudioDir);
9486       llvm::sys::path::append(LibDir, "VC", "lib");
9487       switch (MSVC.getArch()) {
9488       case llvm::Triple::x86:
9489         // x86 just puts the libraries directly in lib
9490         break;
9491       case llvm::Triple::x86_64:
9492         llvm::sys::path::append(LibDir, "amd64");
9493         break;
9494       case llvm::Triple::arm:
9495         llvm::sys::path::append(LibDir, "arm");
9496         break;
9497       default:
9498         break;
9499       }
9500       CmdArgs.push_back(
9501           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9502
9503       if (MSVC.useUniversalCRT(VisualStudioDir)) {
9504         std::string UniversalCRTLibPath;
9505         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9506           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9507                                                UniversalCRTLibPath.c_str()));
9508       }
9509     }
9510
9511     std::string WindowsSdkLibPath;
9512     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9513       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9514                                            WindowsSdkLibPath.c_str()));
9515   }
9516
9517   CmdArgs.push_back("-nologo");
9518
9519   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9520     CmdArgs.push_back("-debug");
9521
9522   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9523                          options::OPT_shared);
9524   if (DLL) {
9525     CmdArgs.push_back(Args.MakeArgString("-dll"));
9526
9527     SmallString<128> ImplibName(Output.getFilename());
9528     llvm::sys::path::replace_extension(ImplibName, "lib");
9529     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9530   }
9531
9532   if (TC.getSanitizerArgs().needsAsanRt()) {
9533     CmdArgs.push_back(Args.MakeArgString("-debug"));
9534     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9535     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9536       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9537         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9538       // Make sure the dynamic runtime thunk is not optimized out at link time
9539       // to ensure proper SEH handling.
9540       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9541     } else if (DLL) {
9542       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9543     } else {
9544       for (const auto &Lib : {"asan", "asan_cxx"})
9545         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9546     }
9547   }
9548
9549   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9550
9551   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9552                    options::OPT_fno_openmp, false)) {
9553     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9554     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9555     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9556                                          TC.getDriver().Dir + "/../lib"));
9557     switch (getOpenMPRuntime(getToolChain(), Args)) {
9558     case OMPRT_OMP:
9559       CmdArgs.push_back("-defaultlib:libomp.lib");
9560       break;
9561     case OMPRT_IOMP5:
9562       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9563       break;
9564     case OMPRT_GOMP:
9565       break;
9566     case OMPRT_Unknown:
9567       // Already diagnosed.
9568       break;
9569     }
9570   }
9571
9572   // Add filenames, libraries, and other linker inputs.
9573   for (const auto &Input : Inputs) {
9574     if (Input.isFilename()) {
9575       CmdArgs.push_back(Input.getFilename());
9576       continue;
9577     }
9578
9579     const Arg &A = Input.getInputArg();
9580
9581     // Render -l options differently for the MSVC linker.
9582     if (A.getOption().matches(options::OPT_l)) {
9583       StringRef Lib = A.getValue();
9584       const char *LinkLibArg;
9585       if (Lib.endswith(".lib"))
9586         LinkLibArg = Args.MakeArgString(Lib);
9587       else
9588         LinkLibArg = Args.MakeArgString(Lib + ".lib");
9589       CmdArgs.push_back(LinkLibArg);
9590       continue;
9591     }
9592
9593     // Otherwise, this is some other kind of linker input option like -Wl, -z,
9594     // or -L. Render it, even if MSVC doesn't understand it.
9595     A.renderAsInput(Args, CmdArgs);
9596   }
9597
9598   TC.addProfileRTLibs(Args, CmdArgs);
9599
9600   // We need to special case some linker paths.  In the case of lld, we need to
9601   // translate 'lld' into 'lld-link', and in the case of the regular msvc
9602   // linker, we need to use a special search algorithm.
9603   llvm::SmallString<128> linkPath;
9604   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9605   if (Linker.equals_lower("lld"))
9606     Linker = "lld-link";
9607
9608   if (Linker.equals_lower("link")) {
9609     // If we're using the MSVC linker, it's not sufficient to just use link
9610     // from the program PATH, because other environments like GnuWin32 install
9611     // their own link.exe which may come first.
9612     linkPath = FindVisualStudioExecutable(TC, "link.exe",
9613                                           C.getDriver().getClangProgramPath());
9614   } else {
9615     linkPath = Linker;
9616     llvm::sys::path::replace_extension(linkPath, "exe");
9617     linkPath = TC.GetProgramPath(linkPath.c_str());
9618   }
9619
9620   const char *Exec = Args.MakeArgString(linkPath);
9621   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9622 }
9623
9624 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9625                                           const InputInfo &Output,
9626                                           const InputInfoList &Inputs,
9627                                           const ArgList &Args,
9628                                           const char *LinkingOutput) const {
9629   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9630 }
9631
9632 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9633     Compilation &C, const JobAction &JA, const InputInfo &Output,
9634     const InputInfoList &Inputs, const ArgList &Args,
9635     const char *LinkingOutput) const {
9636   ArgStringList CmdArgs;
9637   CmdArgs.push_back("/nologo");
9638   CmdArgs.push_back("/c");  // Compile only.
9639   CmdArgs.push_back("/W0"); // No warnings.
9640
9641   // The goal is to be able to invoke this tool correctly based on
9642   // any flag accepted by clang-cl.
9643
9644   // These are spelled the same way in clang and cl.exe,.
9645   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9646
9647   // Optimization level.
9648   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9649     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9650                                                                       : "/Oi-");
9651   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9652     if (A->getOption().getID() == options::OPT_O0) {
9653       CmdArgs.push_back("/Od");
9654     } else {
9655       CmdArgs.push_back("/Og");
9656
9657       StringRef OptLevel = A->getValue();
9658       if (OptLevel == "s" || OptLevel == "z")
9659         CmdArgs.push_back("/Os");
9660       else
9661         CmdArgs.push_back("/Ot");
9662
9663       CmdArgs.push_back("/Ob2");
9664     }
9665   }
9666   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9667                                options::OPT_fno_omit_frame_pointer))
9668     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9669                           ? "/Oy"
9670                           : "/Oy-");
9671   if (!Args.hasArg(options::OPT_fwritable_strings))
9672     CmdArgs.push_back("/GF");
9673
9674   // Flags for which clang-cl has an alias.
9675   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9676
9677   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9678                    /*default=*/false))
9679     CmdArgs.push_back("/GR-");
9680   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9681                                options::OPT_fno_function_sections))
9682     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9683                           ? "/Gy"
9684                           : "/Gy-");
9685   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9686                                options::OPT_fno_data_sections))
9687     CmdArgs.push_back(
9688         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9689   if (Args.hasArg(options::OPT_fsyntax_only))
9690     CmdArgs.push_back("/Zs");
9691   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9692                   options::OPT__SLASH_Z7))
9693     CmdArgs.push_back("/Z7");
9694
9695   std::vector<std::string> Includes =
9696       Args.getAllArgValues(options::OPT_include);
9697   for (const auto &Include : Includes)
9698     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9699
9700   // Flags that can simply be passed through.
9701   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9702   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9703   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9704   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9705
9706   // The order of these flags is relevant, so pick the last one.
9707   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9708                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9709     A->render(Args, CmdArgs);
9710
9711   // Input filename.
9712   assert(Inputs.size() == 1);
9713   const InputInfo &II = Inputs[0];
9714   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9715   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9716   if (II.isFilename())
9717     CmdArgs.push_back(II.getFilename());
9718   else
9719     II.getInputArg().renderAsInput(Args, CmdArgs);
9720
9721   // Output filename.
9722   assert(Output.getType() == types::TY_Object);
9723   const char *Fo =
9724       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9725   CmdArgs.push_back(Fo);
9726
9727   const Driver &D = getToolChain().getDriver();
9728   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9729                                                 D.getClangProgramPath());
9730   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9731                                     CmdArgs, Inputs);
9732 }
9733
9734 /// MinGW Tools
9735 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9736                                     const InputInfo &Output,
9737                                     const InputInfoList &Inputs,
9738                                     const ArgList &Args,
9739                                     const char *LinkingOutput) const {
9740   claimNoWarnArgs(Args);
9741   ArgStringList CmdArgs;
9742
9743   if (getToolChain().getArch() == llvm::Triple::x86) {
9744     CmdArgs.push_back("--32");
9745   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9746     CmdArgs.push_back("--64");
9747   }
9748
9749   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9750
9751   CmdArgs.push_back("-o");
9752   CmdArgs.push_back(Output.getFilename());
9753
9754   for (const auto &II : Inputs)
9755     CmdArgs.push_back(II.getFilename());
9756
9757   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9758   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9759
9760   if (Args.hasArg(options::OPT_gsplit_dwarf))
9761     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9762                    SplitDebugName(Args, Inputs[0]));
9763 }
9764
9765 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9766                               ArgStringList &CmdArgs) const {
9767   if (Args.hasArg(options::OPT_mthreads))
9768     CmdArgs.push_back("-lmingwthrd");
9769   CmdArgs.push_back("-lmingw32");
9770
9771   // Make use of compiler-rt if --rtlib option is used
9772   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9773   if (RLT == ToolChain::RLT_Libgcc) {
9774     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9775                   Args.hasArg(options::OPT_static);
9776     bool Shared = Args.hasArg(options::OPT_shared);
9777     bool CXX = getToolChain().getDriver().CCCIsCXX();
9778
9779     if (Static || (!CXX && !Shared)) {
9780       CmdArgs.push_back("-lgcc");
9781       CmdArgs.push_back("-lgcc_eh");
9782     } else {
9783       CmdArgs.push_back("-lgcc_s");
9784       CmdArgs.push_back("-lgcc");
9785     }
9786   } else {
9787     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9788   }
9789
9790   CmdArgs.push_back("-lmoldname");
9791   CmdArgs.push_back("-lmingwex");
9792   CmdArgs.push_back("-lmsvcrt");
9793 }
9794
9795 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9796                                  const InputInfo &Output,
9797                                  const InputInfoList &Inputs,
9798                                  const ArgList &Args,
9799                                  const char *LinkingOutput) const {
9800   const ToolChain &TC = getToolChain();
9801   const Driver &D = TC.getDriver();
9802   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9803
9804   ArgStringList CmdArgs;
9805
9806   // Silence warning for "clang -g foo.o -o foo"
9807   Args.ClaimAllArgs(options::OPT_g_Group);
9808   // and "clang -emit-llvm foo.o -o foo"
9809   Args.ClaimAllArgs(options::OPT_emit_llvm);
9810   // and for "clang -w foo.o -o foo". Other warning options are already
9811   // handled somewhere else.
9812   Args.ClaimAllArgs(options::OPT_w);
9813
9814   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9815   if (LinkerName.equals_lower("lld")) {
9816     CmdArgs.push_back("-flavor");
9817     CmdArgs.push_back("gnu");
9818   } else if (!LinkerName.equals_lower("ld")) {
9819     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9820   }
9821
9822   if (!D.SysRoot.empty())
9823     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9824
9825   if (Args.hasArg(options::OPT_s))
9826     CmdArgs.push_back("-s");
9827
9828   CmdArgs.push_back("-m");
9829   if (TC.getArch() == llvm::Triple::x86)
9830     CmdArgs.push_back("i386pe");
9831   if (TC.getArch() == llvm::Triple::x86_64)
9832     CmdArgs.push_back("i386pep");
9833   if (TC.getArch() == llvm::Triple::arm)
9834     CmdArgs.push_back("thumb2pe");
9835
9836   if (Args.hasArg(options::OPT_mwindows)) {
9837     CmdArgs.push_back("--subsystem");
9838     CmdArgs.push_back("windows");
9839   } else if (Args.hasArg(options::OPT_mconsole)) {
9840     CmdArgs.push_back("--subsystem");
9841     CmdArgs.push_back("console");
9842   }
9843
9844   if (Args.hasArg(options::OPT_static))
9845     CmdArgs.push_back("-Bstatic");
9846   else {
9847     if (Args.hasArg(options::OPT_mdll))
9848       CmdArgs.push_back("--dll");
9849     else if (Args.hasArg(options::OPT_shared))
9850       CmdArgs.push_back("--shared");
9851     CmdArgs.push_back("-Bdynamic");
9852     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9853       CmdArgs.push_back("-e");
9854       if (TC.getArch() == llvm::Triple::x86)
9855         CmdArgs.push_back("_DllMainCRTStartup@12");
9856       else
9857         CmdArgs.push_back("DllMainCRTStartup");
9858       CmdArgs.push_back("--enable-auto-image-base");
9859     }
9860   }
9861
9862   CmdArgs.push_back("-o");
9863   CmdArgs.push_back(Output.getFilename());
9864
9865   Args.AddAllArgs(CmdArgs, options::OPT_e);
9866   // FIXME: add -N, -n flags
9867   Args.AddLastArg(CmdArgs, options::OPT_r);
9868   Args.AddLastArg(CmdArgs, options::OPT_s);
9869   Args.AddLastArg(CmdArgs, options::OPT_t);
9870   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9871   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9872
9873   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9874     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9875       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9876     } else {
9877       if (Args.hasArg(options::OPT_municode))
9878         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9879       else
9880         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9881     }
9882     if (Args.hasArg(options::OPT_pg))
9883       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9884     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9885   }
9886
9887   Args.AddAllArgs(CmdArgs, options::OPT_L);
9888   TC.AddFilePathLibArgs(Args, CmdArgs);
9889   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9890
9891   // TODO: Add ASan stuff here
9892
9893   // TODO: Add profile stuff here
9894
9895   if (D.CCCIsCXX() &&
9896       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9897     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9898                                !Args.hasArg(options::OPT_static);
9899     if (OnlyLibstdcxxStatic)
9900       CmdArgs.push_back("-Bstatic");
9901     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9902     if (OnlyLibstdcxxStatic)
9903       CmdArgs.push_back("-Bdynamic");
9904   }
9905
9906   if (!Args.hasArg(options::OPT_nostdlib)) {
9907     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9908       if (Args.hasArg(options::OPT_static))
9909         CmdArgs.push_back("--start-group");
9910
9911       if (Args.hasArg(options::OPT_fstack_protector) ||
9912           Args.hasArg(options::OPT_fstack_protector_strong) ||
9913           Args.hasArg(options::OPT_fstack_protector_all)) {
9914         CmdArgs.push_back("-lssp_nonshared");
9915         CmdArgs.push_back("-lssp");
9916       }
9917       if (Args.hasArg(options::OPT_fopenmp))
9918         CmdArgs.push_back("-lgomp");
9919
9920       AddLibGCC(Args, CmdArgs);
9921
9922       if (Args.hasArg(options::OPT_pg))
9923         CmdArgs.push_back("-lgmon");
9924
9925       if (Args.hasArg(options::OPT_pthread))
9926         CmdArgs.push_back("-lpthread");
9927
9928       // add system libraries
9929       if (Args.hasArg(options::OPT_mwindows)) {
9930         CmdArgs.push_back("-lgdi32");
9931         CmdArgs.push_back("-lcomdlg32");
9932       }
9933       CmdArgs.push_back("-ladvapi32");
9934       CmdArgs.push_back("-lshell32");
9935       CmdArgs.push_back("-luser32");
9936       CmdArgs.push_back("-lkernel32");
9937
9938       if (Args.hasArg(options::OPT_static))
9939         CmdArgs.push_back("--end-group");
9940       else if (!LinkerName.equals_lower("lld"))
9941         AddLibGCC(Args, CmdArgs);
9942     }
9943
9944     if (!Args.hasArg(options::OPT_nostartfiles)) {
9945       // Add crtfastmath.o if available and fast math is enabled.
9946       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9947
9948       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9949     }
9950   }
9951   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9952   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9953 }
9954
9955 /// XCore Tools
9956 // We pass assemble and link construction to the xcc tool.
9957
9958 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9959                                     const InputInfo &Output,
9960                                     const InputInfoList &Inputs,
9961                                     const ArgList &Args,
9962                                     const char *LinkingOutput) const {
9963   claimNoWarnArgs(Args);
9964   ArgStringList CmdArgs;
9965
9966   CmdArgs.push_back("-o");
9967   CmdArgs.push_back(Output.getFilename());
9968
9969   CmdArgs.push_back("-c");
9970
9971   if (Args.hasArg(options::OPT_v))
9972     CmdArgs.push_back("-v");
9973
9974   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9975     if (!A->getOption().matches(options::OPT_g0))
9976       CmdArgs.push_back("-g");
9977
9978   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9979                    false))
9980     CmdArgs.push_back("-fverbose-asm");
9981
9982   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9983
9984   for (const auto &II : Inputs)
9985     CmdArgs.push_back(II.getFilename());
9986
9987   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9988   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9989 }
9990
9991 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9992                                  const InputInfo &Output,
9993                                  const InputInfoList &Inputs,
9994                                  const ArgList &Args,
9995                                  const char *LinkingOutput) const {
9996   ArgStringList CmdArgs;
9997
9998   if (Output.isFilename()) {
9999     CmdArgs.push_back("-o");
10000     CmdArgs.push_back(Output.getFilename());
10001   } else {
10002     assert(Output.isNothing() && "Invalid output.");
10003   }
10004
10005   if (Args.hasArg(options::OPT_v))
10006     CmdArgs.push_back("-v");
10007
10008   // Pass -fexceptions through to the linker if it was present.
10009   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10010                    false))
10011     CmdArgs.push_back("-fexceptions");
10012
10013   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10014
10015   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10016   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10017 }
10018
10019 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10020                                            const InputInfo &Output,
10021                                            const InputInfoList &Inputs,
10022                                            const ArgList &Args,
10023                                            const char *LinkingOutput) const {
10024   claimNoWarnArgs(Args);
10025   const auto &TC =
10026       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10027   ArgStringList CmdArgs;
10028   const char *Exec;
10029
10030   switch (TC.getArch()) {
10031   default:
10032     llvm_unreachable("unsupported architecture");
10033   case llvm::Triple::arm:
10034   case llvm::Triple::thumb:
10035     break;
10036   case llvm::Triple::x86:
10037     CmdArgs.push_back("--32");
10038     break;
10039   case llvm::Triple::x86_64:
10040     CmdArgs.push_back("--64");
10041     break;
10042   }
10043
10044   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10045
10046   CmdArgs.push_back("-o");
10047   CmdArgs.push_back(Output.getFilename());
10048
10049   for (const auto &Input : Inputs)
10050     CmdArgs.push_back(Input.getFilename());
10051
10052   const std::string Assembler = TC.GetProgramPath("as");
10053   Exec = Args.MakeArgString(Assembler);
10054
10055   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10056 }
10057
10058 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10059                                         const InputInfo &Output,
10060                                         const InputInfoList &Inputs,
10061                                         const ArgList &Args,
10062                                         const char *LinkingOutput) const {
10063   const auto &TC =
10064       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10065   const llvm::Triple &T = TC.getTriple();
10066   const Driver &D = TC.getDriver();
10067   SmallString<128> EntryPoint;
10068   ArgStringList CmdArgs;
10069   const char *Exec;
10070
10071   // Silence warning for "clang -g foo.o -o foo"
10072   Args.ClaimAllArgs(options::OPT_g_Group);
10073   // and "clang -emit-llvm foo.o -o foo"
10074   Args.ClaimAllArgs(options::OPT_emit_llvm);
10075   // and for "clang -w foo.o -o foo"
10076   Args.ClaimAllArgs(options::OPT_w);
10077   // Other warning options are already handled somewhere else.
10078
10079   if (!D.SysRoot.empty())
10080     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10081
10082   if (Args.hasArg(options::OPT_pie))
10083     CmdArgs.push_back("-pie");
10084   if (Args.hasArg(options::OPT_rdynamic))
10085     CmdArgs.push_back("-export-dynamic");
10086   if (Args.hasArg(options::OPT_s))
10087     CmdArgs.push_back("--strip-all");
10088
10089   CmdArgs.push_back("-m");
10090   switch (TC.getArch()) {
10091   default:
10092     llvm_unreachable("unsupported architecture");
10093   case llvm::Triple::arm:
10094   case llvm::Triple::thumb:
10095     // FIXME: this is incorrect for WinCE
10096     CmdArgs.push_back("thumb2pe");
10097     break;
10098   case llvm::Triple::x86:
10099     CmdArgs.push_back("i386pe");
10100     EntryPoint.append("_");
10101     break;
10102   case llvm::Triple::x86_64:
10103     CmdArgs.push_back("i386pep");
10104     break;
10105   }
10106
10107   if (Args.hasArg(options::OPT_shared)) {
10108     switch (T.getArch()) {
10109     default:
10110       llvm_unreachable("unsupported architecture");
10111     case llvm::Triple::arm:
10112     case llvm::Triple::thumb:
10113     case llvm::Triple::x86_64:
10114       EntryPoint.append("_DllMainCRTStartup");
10115       break;
10116     case llvm::Triple::x86:
10117       EntryPoint.append("_DllMainCRTStartup@12");
10118       break;
10119     }
10120
10121     CmdArgs.push_back("-shared");
10122     CmdArgs.push_back("-Bdynamic");
10123
10124     CmdArgs.push_back("--enable-auto-image-base");
10125
10126     CmdArgs.push_back("--entry");
10127     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10128   } else {
10129     EntryPoint.append("mainCRTStartup");
10130
10131     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10132                                                        : "-Bdynamic");
10133
10134     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10135       CmdArgs.push_back("--entry");
10136       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10137     }
10138
10139     // FIXME: handle subsystem
10140   }
10141
10142   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10143   CmdArgs.push_back("--allow-multiple-definition");
10144
10145   CmdArgs.push_back("-o");
10146   CmdArgs.push_back(Output.getFilename());
10147
10148   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10149     SmallString<261> ImpLib(Output.getFilename());
10150     llvm::sys::path::replace_extension(ImpLib, ".lib");
10151
10152     CmdArgs.push_back("--out-implib");
10153     CmdArgs.push_back(Args.MakeArgString(ImpLib));
10154   }
10155
10156   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10157     const std::string CRTPath(D.SysRoot + "/usr/lib/");
10158     const char *CRTBegin;
10159
10160     CRTBegin =
10161         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10162     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10163   }
10164
10165   Args.AddAllArgs(CmdArgs, options::OPT_L);
10166   TC.AddFilePathLibArgs(Args, CmdArgs);
10167   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10168
10169   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10170       !Args.hasArg(options::OPT_nodefaultlibs)) {
10171     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10172                      !Args.hasArg(options::OPT_static);
10173     if (StaticCXX)
10174       CmdArgs.push_back("-Bstatic");
10175     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10176     if (StaticCXX)
10177       CmdArgs.push_back("-Bdynamic");
10178   }
10179
10180   if (!Args.hasArg(options::OPT_nostdlib)) {
10181     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10182       // TODO handle /MT[d] /MD[d]
10183       CmdArgs.push_back("-lmsvcrt");
10184       AddRunTimeLibs(TC, D, CmdArgs, Args);
10185     }
10186   }
10187
10188   if (TC.getSanitizerArgs().needsAsanRt()) {
10189     // TODO handle /MT[d] /MD[d]
10190     if (Args.hasArg(options::OPT_shared)) {
10191       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10192     } else {
10193       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10194         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10195         // Make sure the dynamic runtime thunk is not optimized out at link time
10196         // to ensure proper SEH handling.
10197         CmdArgs.push_back(Args.MakeArgString("--undefined"));
10198         CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10199                                                  ? "___asan_seh_interceptor"
10200                                                  : "__asan_seh_interceptor"));
10201     }
10202   }
10203
10204   Exec = Args.MakeArgString(TC.GetLinkerPath());
10205
10206   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10207 }
10208
10209 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10210                                           const InputInfo &Output,
10211                                           const InputInfoList &Inputs,
10212                                           const ArgList &Args,
10213                                           const char *LinkingOutput) const {
10214   ArgStringList CmdArgs;
10215   assert(Inputs.size() == 1);
10216   const InputInfo &II = Inputs[0];
10217   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10218          II.getType() == types::TY_PP_CXX);
10219
10220   if (JA.getKind() == Action::PreprocessJobClass) {
10221     Args.ClaimAllArgs();
10222     CmdArgs.push_back("-E");
10223   } else {
10224     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10225     CmdArgs.push_back("-S");
10226     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10227   }
10228   CmdArgs.push_back("-mcpu=myriad2");
10229   CmdArgs.push_back("-DMYRIAD2");
10230
10231   // Append all -I, -iquote, -isystem paths, defines/undefines,
10232   // 'f' flags, optimize flags, and warning options.
10233   // These are spelled the same way in clang and moviCompile.
10234   Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10235                             options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10236                             options::OPT_f_Group, options::OPT_f_clang_Group,
10237                             options::OPT_g_Group, options::OPT_M_Group,
10238                             options::OPT_O_Group, options::OPT_W_Group});
10239
10240   // If we're producing a dependency file, and assembly is the final action,
10241   // then the name of the target in the dependency file should be the '.o'
10242   // file, not the '.s' file produced by this step. For example, instead of
10243   //  /tmp/mumble.s: mumble.c .../someheader.h
10244   // the filename on the lefthand side should be "mumble.o"
10245   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10246       C.getActions().size() == 1 &&
10247       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10248     Arg *A = Args.getLastArg(options::OPT_o);
10249     if (A) {
10250       CmdArgs.push_back("-MT");
10251       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10252     }
10253   }
10254
10255   CmdArgs.push_back(II.getFilename());
10256   CmdArgs.push_back("-o");
10257   CmdArgs.push_back(Output.getFilename());
10258
10259   std::string Exec =
10260       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10261   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10262                                           CmdArgs, Inputs));
10263 }
10264
10265 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10266                                            const InputInfo &Output,
10267                                            const InputInfoList &Inputs,
10268                                            const ArgList &Args,
10269                                            const char *LinkingOutput) const {
10270   ArgStringList CmdArgs;
10271
10272   assert(Inputs.size() == 1);
10273   const InputInfo &II = Inputs[0];
10274   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10275   assert(Output.getType() == types::TY_Object);
10276
10277   CmdArgs.push_back("-no6thSlotCompression");
10278   CmdArgs.push_back("-cv:myriad2"); // Chip Version
10279   CmdArgs.push_back("-noSPrefixing");
10280   CmdArgs.push_back("-a"); // Mystery option.
10281   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10282   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10283     A->claim();
10284     CmdArgs.push_back(
10285         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10286   }
10287   CmdArgs.push_back("-elf"); // Output format.
10288   CmdArgs.push_back(II.getFilename());
10289   CmdArgs.push_back(
10290       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10291
10292   std::string Exec =
10293       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10294   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10295                                           CmdArgs, Inputs));
10296 }
10297
10298 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10299                                          const InputInfo &Output,
10300                                          const InputInfoList &Inputs,
10301                                          const ArgList &Args,
10302                                          const char *LinkingOutput) const {
10303   const auto &TC =
10304       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10305   const llvm::Triple &T = TC.getTriple();
10306   ArgStringList CmdArgs;
10307   bool UseStartfiles =
10308       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10309   bool UseDefaultLibs =
10310       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10311
10312   if (T.getArch() == llvm::Triple::sparc)
10313     CmdArgs.push_back("-EB");
10314   else // SHAVE assumes little-endian, and sparcel is expressly so.
10315     CmdArgs.push_back("-EL");
10316
10317   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10318   // but we never pass through a --sysroot option and various other bits.
10319   // For example, there are no sanitizers (yet) nor gold linker.
10320
10321   // Eat some arguments that may be present but have no effect.
10322   Args.ClaimAllArgs(options::OPT_g_Group);
10323   Args.ClaimAllArgs(options::OPT_w);
10324   Args.ClaimAllArgs(options::OPT_static_libgcc);
10325
10326   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10327     CmdArgs.push_back("-s");
10328
10329   CmdArgs.push_back("-o");
10330   CmdArgs.push_back(Output.getFilename());
10331
10332   if (UseStartfiles) {
10333     // If you want startfiles, it means you want the builtin crti and crtbegin,
10334     // but not crt0. Myriad link commands provide their own crt0.o as needed.
10335     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10336     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10337   }
10338
10339   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10340                             options::OPT_e, options::OPT_s, options::OPT_t,
10341                             options::OPT_Z_Flag, options::OPT_r});
10342
10343   TC.AddFilePathLibArgs(Args, CmdArgs);
10344
10345   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10346
10347   if (UseDefaultLibs) {
10348     if (C.getDriver().CCCIsCXX())
10349       CmdArgs.push_back("-lstdc++");
10350     if (T.getOS() == llvm::Triple::RTEMS) {
10351       CmdArgs.push_back("--start-group");
10352       CmdArgs.push_back("-lc");
10353       // You must provide your own "-L" option to enable finding these.
10354       CmdArgs.push_back("-lrtemscpu");
10355       CmdArgs.push_back("-lrtemsbsp");
10356       CmdArgs.push_back("--end-group");
10357     } else {
10358       CmdArgs.push_back("-lc");
10359     }
10360     CmdArgs.push_back("-lgcc");
10361   }
10362   if (UseStartfiles) {
10363     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10364     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10365   }
10366
10367   std::string Exec =
10368       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10369   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10370                                           CmdArgs, Inputs));
10371 }
10372
10373 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10374                                     const InputInfo &Output,
10375                                     const InputInfoList &Inputs,
10376                                     const ArgList &Args,
10377                                     const char *LinkingOutput) const {
10378   claimNoWarnArgs(Args);
10379   ArgStringList CmdArgs;
10380
10381   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10382
10383   CmdArgs.push_back("-o");
10384   CmdArgs.push_back(Output.getFilename());
10385
10386   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10387   const InputInfo &Input = Inputs[0];
10388   assert(Input.isFilename() && "Invalid input.");
10389   CmdArgs.push_back(Input.getFilename());
10390
10391   const char *Exec =
10392       Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10393   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10394 }
10395
10396 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10397   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10398   if (SanArgs.needsUbsanRt()) {
10399     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10400   }
10401   if (SanArgs.needsAsanRt()) {
10402     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10403   }
10404 }
10405
10406 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10407                                 const JobAction &JA, const InputInfo &Output,
10408                                 const InputInfoList &Inputs,
10409                                 const ArgList &Args,
10410                                 const char *LinkingOutput) {
10411   const toolchains::FreeBSD &ToolChain =
10412       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10413   const Driver &D = ToolChain.getDriver();
10414   ArgStringList CmdArgs;
10415
10416   // Silence warning for "clang -g foo.o -o foo"
10417   Args.ClaimAllArgs(options::OPT_g_Group);
10418   // and "clang -emit-llvm foo.o -o foo"
10419   Args.ClaimAllArgs(options::OPT_emit_llvm);
10420   // and for "clang -w foo.o -o foo". Other warning options are already
10421   // handled somewhere else.
10422   Args.ClaimAllArgs(options::OPT_w);
10423
10424   if (!D.SysRoot.empty())
10425     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10426
10427   if (Args.hasArg(options::OPT_pie))
10428     CmdArgs.push_back("-pie");
10429
10430   if (Args.hasArg(options::OPT_rdynamic))
10431     CmdArgs.push_back("-export-dynamic");
10432   if (Args.hasArg(options::OPT_shared))
10433     CmdArgs.push_back("--oformat=so");
10434
10435   if (Output.isFilename()) {
10436     CmdArgs.push_back("-o");
10437     CmdArgs.push_back(Output.getFilename());
10438   } else {
10439     assert(Output.isNothing() && "Invalid output.");
10440   }
10441
10442   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10443
10444   Args.AddAllArgs(CmdArgs, options::OPT_L);
10445   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10446   Args.AddAllArgs(CmdArgs, options::OPT_e);
10447   Args.AddAllArgs(CmdArgs, options::OPT_s);
10448   Args.AddAllArgs(CmdArgs, options::OPT_t);
10449   Args.AddAllArgs(CmdArgs, options::OPT_r);
10450
10451   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10452     CmdArgs.push_back("--no-demangle");
10453
10454   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10455
10456   if (Args.hasArg(options::OPT_pthread)) {
10457     CmdArgs.push_back("-lpthread");
10458   }
10459
10460   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10461
10462   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10463 }
10464
10465 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10466                                  const JobAction &JA, const InputInfo &Output,
10467                                  const InputInfoList &Inputs,
10468                                  const ArgList &Args,
10469                                  const char *LinkingOutput) {
10470   const toolchains::FreeBSD &ToolChain =
10471       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10472   const Driver &D = ToolChain.getDriver();
10473   ArgStringList CmdArgs;
10474
10475   // Silence warning for "clang -g foo.o -o foo"
10476   Args.ClaimAllArgs(options::OPT_g_Group);
10477   // and "clang -emit-llvm foo.o -o foo"
10478   Args.ClaimAllArgs(options::OPT_emit_llvm);
10479   // and for "clang -w foo.o -o foo". Other warning options are already
10480   // handled somewhere else.
10481   Args.ClaimAllArgs(options::OPT_w);
10482
10483   if (!D.SysRoot.empty())
10484     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10485
10486   if (Args.hasArg(options::OPT_pie))
10487     CmdArgs.push_back("-pie");
10488
10489   if (Args.hasArg(options::OPT_static)) {
10490     CmdArgs.push_back("-Bstatic");
10491   } else {
10492     if (Args.hasArg(options::OPT_rdynamic))
10493       CmdArgs.push_back("-export-dynamic");
10494     CmdArgs.push_back("--eh-frame-hdr");
10495     if (Args.hasArg(options::OPT_shared)) {
10496       CmdArgs.push_back("-Bshareable");
10497     } else {
10498       CmdArgs.push_back("-dynamic-linker");
10499       CmdArgs.push_back("/libexec/ld-elf.so.1");
10500     }
10501     CmdArgs.push_back("--enable-new-dtags");
10502   }
10503
10504   if (Output.isFilename()) {
10505     CmdArgs.push_back("-o");
10506     CmdArgs.push_back(Output.getFilename());
10507   } else {
10508     assert(Output.isNothing() && "Invalid output.");
10509   }
10510
10511   AddPS4SanitizerArgs(ToolChain, CmdArgs);
10512
10513   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10514     const char *crt1 = nullptr;
10515     if (!Args.hasArg(options::OPT_shared)) {
10516       if (Args.hasArg(options::OPT_pg))
10517         crt1 = "gcrt1.o";
10518       else if (Args.hasArg(options::OPT_pie))
10519         crt1 = "Scrt1.o";
10520       else
10521         crt1 = "crt1.o";
10522     }
10523     if (crt1)
10524       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10525
10526     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10527
10528     const char *crtbegin = nullptr;
10529     if (Args.hasArg(options::OPT_static))
10530       crtbegin = "crtbeginT.o";
10531     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10532       crtbegin = "crtbeginS.o";
10533     else
10534       crtbegin = "crtbegin.o";
10535
10536     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10537   }
10538
10539   Args.AddAllArgs(CmdArgs, options::OPT_L);
10540   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10541   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10542   Args.AddAllArgs(CmdArgs, options::OPT_e);
10543   Args.AddAllArgs(CmdArgs, options::OPT_s);
10544   Args.AddAllArgs(CmdArgs, options::OPT_t);
10545   Args.AddAllArgs(CmdArgs, options::OPT_r);
10546
10547   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10548     CmdArgs.push_back("--no-demangle");
10549
10550   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10551
10552   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10553     // For PS4, we always want to pass libm, libstdc++ and libkernel
10554     // libraries for both C and C++ compilations.
10555     CmdArgs.push_back("-lkernel");
10556     if (D.CCCIsCXX()) {
10557       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10558       if (Args.hasArg(options::OPT_pg))
10559         CmdArgs.push_back("-lm_p");
10560       else
10561         CmdArgs.push_back("-lm");
10562     }
10563     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10564     // the default system libraries. Just mimic this for now.
10565     if (Args.hasArg(options::OPT_pg))
10566       CmdArgs.push_back("-lgcc_p");
10567     else
10568       CmdArgs.push_back("-lcompiler_rt");
10569     if (Args.hasArg(options::OPT_static)) {
10570       CmdArgs.push_back("-lstdc++");
10571     } else if (Args.hasArg(options::OPT_pg)) {
10572       CmdArgs.push_back("-lgcc_eh_p");
10573     } else {
10574       CmdArgs.push_back("--as-needed");
10575       CmdArgs.push_back("-lstdc++");
10576       CmdArgs.push_back("--no-as-needed");
10577     }
10578
10579     if (Args.hasArg(options::OPT_pthread)) {
10580       if (Args.hasArg(options::OPT_pg))
10581         CmdArgs.push_back("-lpthread_p");
10582       else
10583         CmdArgs.push_back("-lpthread");
10584     }
10585
10586     if (Args.hasArg(options::OPT_pg)) {
10587       if (Args.hasArg(options::OPT_shared))
10588         CmdArgs.push_back("-lc");
10589       else {
10590         if (Args.hasArg(options::OPT_static)) {
10591           CmdArgs.push_back("--start-group");
10592           CmdArgs.push_back("-lc_p");
10593           CmdArgs.push_back("-lpthread_p");
10594           CmdArgs.push_back("--end-group");
10595         } else {
10596           CmdArgs.push_back("-lc_p");
10597         }
10598       }
10599       CmdArgs.push_back("-lgcc_p");
10600     } else {
10601       if (Args.hasArg(options::OPT_static)) {
10602         CmdArgs.push_back("--start-group");
10603         CmdArgs.push_back("-lc");
10604         CmdArgs.push_back("-lpthread");
10605         CmdArgs.push_back("--end-group");
10606       } else {
10607         CmdArgs.push_back("-lc");
10608       }
10609       CmdArgs.push_back("-lcompiler_rt");
10610     }
10611
10612     if (Args.hasArg(options::OPT_static)) {
10613       CmdArgs.push_back("-lstdc++");
10614     } else if (Args.hasArg(options::OPT_pg)) {
10615       CmdArgs.push_back("-lgcc_eh_p");
10616     } else {
10617       CmdArgs.push_back("--as-needed");
10618       CmdArgs.push_back("-lstdc++");
10619       CmdArgs.push_back("--no-as-needed");
10620     }
10621   }
10622
10623   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10624     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10625       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10626     else
10627       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10628     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10629   }
10630
10631   const char *Exec =
10632 #ifdef LLVM_ON_WIN32
10633       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10634 #else
10635       Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10636 #endif
10637
10638   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10639 }
10640
10641 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10642                                 const InputInfo &Output,
10643                                 const InputInfoList &Inputs,
10644                                 const ArgList &Args,
10645                                 const char *LinkingOutput) const {
10646   const toolchains::FreeBSD &ToolChain =
10647       static_cast<const toolchains::FreeBSD &>(getToolChain());
10648   const Driver &D = ToolChain.getDriver();
10649   bool PS4Linker;
10650   StringRef LinkerOptName;
10651   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10652     LinkerOptName = A->getValue();
10653     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10654       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10655   }
10656
10657   if (LinkerOptName == "gold")
10658     PS4Linker = false;
10659   else if (LinkerOptName == "ps4")
10660     PS4Linker = true;
10661   else
10662     PS4Linker = !Args.hasArg(options::OPT_shared);
10663
10664   if (PS4Linker)
10665     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10666   else
10667     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10668 }
10669
10670 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10671                                     const InputInfo &Output,
10672                                     const InputInfoList &Inputs,
10673                                     const ArgList &Args,
10674                                     const char *LinkingOutput) const {
10675   const auto &TC =
10676       static_cast<const toolchains::CudaToolChain &>(getToolChain());
10677   assert(TC.getTriple().isNVPTX() && "Wrong platform");
10678
10679   std::vector<std::string> gpu_archs =
10680       Args.getAllArgValues(options::OPT_march_EQ);
10681   assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
10682   const std::string& gpu_arch = gpu_archs[0];
10683
10684
10685   ArgStringList CmdArgs;
10686   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
10687
10688   // Map the -O we received to -O{0,1,2,3}.
10689   //
10690   // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's default,
10691   // so it may correspond more closely to the spirit of clang -O2.
10692   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
10693     // -O3 seems like the least-bad option when -Osomething is specified to
10694     // clang but it isn't handled below.
10695     StringRef OOpt = "3";
10696     if (A->getOption().matches(options::OPT_O4) ||
10697         A->getOption().matches(options::OPT_Ofast))
10698       OOpt = "3";
10699     else if (A->getOption().matches(options::OPT_O0))
10700       OOpt = "0";
10701     else if (A->getOption().matches(options::OPT_O)) {
10702       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
10703       OOpt = llvm::StringSwitch<const char *>(A->getValue())
10704                  .Case("1", "1")
10705                  .Case("2", "2")
10706                  .Case("3", "3")
10707                  .Case("s", "2")
10708                  .Case("z", "2")
10709                  .Default("2");
10710     }
10711     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
10712   } else {
10713     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
10714     // to no optimizations, but ptxas's default is -O3.
10715     CmdArgs.push_back("-O0");
10716   }
10717
10718   // Don't bother passing -g to ptxas: It's enabled by default at -O0, and
10719   // not supported at other optimization levels.
10720
10721   CmdArgs.push_back("--gpu-name");
10722   CmdArgs.push_back(Args.MakeArgString(gpu_arch));
10723   CmdArgs.push_back("--output-file");
10724   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
10725   for (const auto& II : Inputs)
10726     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
10727
10728   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
10729     CmdArgs.push_back(Args.MakeArgString(A));
10730
10731   const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
10732   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10733 }
10734
10735 // All inputs to this linker must be from CudaDeviceActions, as we need to look
10736 // at the Inputs' Actions in order to figure out which GPU architecture they
10737 // correspond to.
10738 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10739                                  const InputInfo &Output,
10740                                  const InputInfoList &Inputs,
10741                                  const ArgList &Args,
10742                                  const char *LinkingOutput) const {
10743   const auto &TC =
10744       static_cast<const toolchains::CudaToolChain &>(getToolChain());
10745   assert(TC.getTriple().isNVPTX() && "Wrong platform");
10746
10747   ArgStringList CmdArgs;
10748   CmdArgs.push_back("--cuda");
10749   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
10750   CmdArgs.push_back(Args.MakeArgString("--create"));
10751   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
10752
10753   for (const auto& II : Inputs) {
10754     auto* A = cast<const CudaDeviceAction>(II.getAction());
10755     // We need to pass an Arch of the form "sm_XX" for cubin files and
10756     // "compute_XX" for ptx.
10757     const char *Arch = (II.getType() == types::TY_PP_Asm)
10758                            ? A->getComputeArchName()
10759                            : A->getGpuArchName();
10760     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
10761                                          Arch + ",file=" + II.getFilename()));
10762   }
10763
10764   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
10765     CmdArgs.push_back(Args.MakeArgString(A));
10766
10767   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
10768   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10769 }