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