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