]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains/Clang.cpp
Merge lld release_80 branch r351543, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains / Clang.cpp
1 //===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Clang.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/Mips.h"
14 #include "Arch/PPC.h"
15 #include "Arch/RISCV.h"
16 #include "Arch/Sparc.h"
17 #include "Arch/SystemZ.h"
18 #include "Arch/X86.h"
19 #include "AMDGPU.h"
20 #include "CommonArgs.h"
21 #include "Hexagon.h"
22 #include "MSP430.h"
23 #include "InputInfo.h"
24 #include "PS4CPU.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/ObjCRuntime.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Driver/Distro.h"
30 #include "clang/Driver/DriverDiagnostic.h"
31 #include "clang/Driver/Options.h"
32 #include "clang/Driver/SanitizerArgs.h"
33 #include "clang/Driver/XRayArgs.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Config/llvm-config.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/Compression.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/TargetParser.h"
43 #include "llvm/Support/YAMLParser.h"
44
45 #ifdef LLVM_ON_UNIX
46 #include <unistd.h> // For getuid().
47 #endif
48
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
53
54 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
55   if (Arg *A =
56           Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60           << A->getBaseArg().getAsString(Args)
61           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
62     }
63   }
64 }
65
66 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67   // In gcc, only ARM checks this, but it seems reasonable to check universally.
68   if (Args.hasArg(options::OPT_static))
69     if (const Arg *A =
70             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
72                                                       << "-static";
73 }
74
75 // Add backslashes to escape spaces and other backslashes.
76 // This is used for the space-separated argument list specified with
77 // the -dwarf-debug-flags option.
78 static void EscapeSpacesAndBackslashes(const char *Arg,
79                                        SmallVectorImpl<char> &Res) {
80   for (; *Arg; ++Arg) {
81     switch (*Arg) {
82     default:
83       break;
84     case ' ':
85     case '\\':
86       Res.push_back('\\');
87       break;
88     }
89     Res.push_back(*Arg);
90   }
91 }
92
93 // Quote target names for inclusion in GNU Make dependency files.
94 // Only the characters '$', '#', ' ', '\t' are quoted.
95 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
97     switch (Target[i]) {
98     case ' ':
99     case '\t':
100       // Escape the preceding backslashes
101       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
102         Res.push_back('\\');
103
104       // Escape the space/tab
105       Res.push_back('\\');
106       break;
107     case '$':
108       Res.push_back('$');
109       break;
110     case '#':
111       Res.push_back('\\');
112       break;
113     default:
114       break;
115     }
116
117     Res.push_back(Target[i]);
118   }
119 }
120
121 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
122 /// offloading tool chain that is associated with the current action \a JA.
123 static void
124 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125                            const ToolChain &RegularToolChain,
126                            llvm::function_ref<void(const ToolChain &)> Work) {
127   // Apply Work on the current/regular tool chain.
128   Work(RegularToolChain);
129
130   // Apply Work on all the offloading tool chains associated with the current
131   // action.
132   if (JA.isHostOffloading(Action::OFK_Cuda))
133     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
136   else if (JA.isHostOffloading(Action::OFK_HIP))
137     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138   else if (JA.isDeviceOffloading(Action::OFK_HIP))
139     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
140
141   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
144       Work(*II->second);
145   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
147
148   //
149   // TODO: Add support for other offloading programming models here.
150   //
151 }
152
153 /// This is a helper function for validating the optional refinement step
154 /// parameter in reciprocal argument strings. Return false if there is an error
155 /// parsing the refinement step. Otherwise, return true and set the Position
156 /// of the refinement step in the input string.
157 static bool getRefinementStep(StringRef In, const Driver &D,
158                               const Arg &A, size_t &Position) {
159   const char RefinementStepToken = ':';
160   Position = In.find(RefinementStepToken);
161   if (Position != StringRef::npos) {
162     StringRef Option = A.getOption().getName();
163     StringRef RefStep = In.substr(Position + 1);
164     // Allow exactly one numeric character for the additional refinement
165     // step parameter. This is reasonable for all currently-supported
166     // operations and architectures because we would expect that a larger value
167     // of refinement steps would cause the estimate "optimization" to
168     // under-perform the native operation. Also, if the estimate does not
169     // converge quickly, it probably will not ever converge, so further
170     // refinement steps will not produce a better answer.
171     if (RefStep.size() != 1) {
172       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
173       return false;
174     }
175     char RefStepChar = RefStep[0];
176     if (RefStepChar < '0' || RefStepChar > '9') {
177       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
178       return false;
179     }
180   }
181   return true;
182 }
183
184 /// The -mrecip flag requires processing of many optional parameters.
185 static void ParseMRecip(const Driver &D, const ArgList &Args,
186                         ArgStringList &OutStrings) {
187   StringRef DisabledPrefixIn = "!";
188   StringRef DisabledPrefixOut = "!";
189   StringRef EnabledPrefixOut = "";
190   StringRef Out = "-mrecip=";
191
192   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
193   if (!A)
194     return;
195
196   unsigned NumOptions = A->getNumValues();
197   if (NumOptions == 0) {
198     // No option is the same as "all".
199     OutStrings.push_back(Args.MakeArgString(Out + "all"));
200     return;
201   }
202
203   // Pass through "all", "none", or "default" with an optional refinement step.
204   if (NumOptions == 1) {
205     StringRef Val = A->getValue(0);
206     size_t RefStepLoc;
207     if (!getRefinementStep(Val, D, *A, RefStepLoc))
208       return;
209     StringRef ValBase = Val.slice(0, RefStepLoc);
210     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211       OutStrings.push_back(Args.MakeArgString(Out + Val));
212       return;
213     }
214   }
215
216   // Each reciprocal type may be enabled or disabled individually.
217   // Check each input value for validity, concatenate them all back together,
218   // and pass through.
219
220   llvm::StringMap<bool> OptionStrings;
221   OptionStrings.insert(std::make_pair("divd", false));
222   OptionStrings.insert(std::make_pair("divf", false));
223   OptionStrings.insert(std::make_pair("vec-divd", false));
224   OptionStrings.insert(std::make_pair("vec-divf", false));
225   OptionStrings.insert(std::make_pair("sqrtd", false));
226   OptionStrings.insert(std::make_pair("sqrtf", false));
227   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
229
230   for (unsigned i = 0; i != NumOptions; ++i) {
231     StringRef Val = A->getValue(i);
232
233     bool IsDisabled = Val.startswith(DisabledPrefixIn);
234     // Ignore the disablement token for string matching.
235     if (IsDisabled)
236       Val = Val.substr(1);
237
238     size_t RefStep;
239     if (!getRefinementStep(Val, D, *A, RefStep))
240       return;
241
242     StringRef ValBase = Val.slice(0, RefStep);
243     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244     if (OptionIter == OptionStrings.end()) {
245       // Try again specifying float suffix.
246       OptionIter = OptionStrings.find(ValBase.str() + 'f');
247       if (OptionIter == OptionStrings.end()) {
248         // The input name did not match any known option string.
249         D.Diag(diag::err_drv_unknown_argument) << Val;
250         return;
251       }
252       // The option was specified without a float or double suffix.
253       // Make sure that the double entry was not already specified.
254       // The float entry will be checked below.
255       if (OptionStrings[ValBase.str() + 'd']) {
256         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
257         return;
258       }
259     }
260
261     if (OptionIter->second == true) {
262       // Duplicate option specified.
263       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
264       return;
265     }
266
267     // Mark the matched option as found. Do not allow duplicate specifiers.
268     OptionIter->second = true;
269
270     // If the precision was not specified, also mark the double entry as found.
271     if (ValBase.back() != 'f' && ValBase.back() != 'd')
272       OptionStrings[ValBase.str() + 'd'] = true;
273
274     // Build the output string.
275     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276     Out = Args.MakeArgString(Out + Prefix + Val);
277     if (i != NumOptions - 1)
278       Out = Args.MakeArgString(Out + ",");
279   }
280
281   OutStrings.push_back(Args.MakeArgString(Out));
282 }
283
284 /// The -mprefer-vector-width option accepts either a positive integer
285 /// or the string "none".
286 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287                                     ArgStringList &CmdArgs) {
288   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
289   if (!A)
290     return;
291
292   StringRef Value = A->getValue();
293   if (Value == "none") {
294     CmdArgs.push_back("-mprefer-vector-width=none");
295   } else {
296     unsigned Width;
297     if (Value.getAsInteger(10, Width)) {
298       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
299       return;
300     }
301     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302   }
303 }
304
305 static void getWebAssemblyTargetFeatures(const ArgList &Args,
306                                          std::vector<StringRef> &Features) {
307   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308 }
309
310 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
311                               const ArgList &Args, ArgStringList &CmdArgs,
312                               bool ForAS) {
313   const Driver &D = TC.getDriver();
314   std::vector<StringRef> Features;
315   switch (Triple.getArch()) {
316   default:
317     break;
318   case llvm::Triple::mips:
319   case llvm::Triple::mipsel:
320   case llvm::Triple::mips64:
321   case llvm::Triple::mips64el:
322     mips::getMIPSTargetFeatures(D, Triple, Args, Features);
323     break;
324
325   case llvm::Triple::arm:
326   case llvm::Triple::armeb:
327   case llvm::Triple::thumb:
328   case llvm::Triple::thumbeb:
329     arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
330     break;
331
332   case llvm::Triple::ppc:
333   case llvm::Triple::ppc64:
334   case llvm::Triple::ppc64le:
335     ppc::getPPCTargetFeatures(D, Triple, Args, Features);
336     break;
337   case llvm::Triple::riscv32:
338   case llvm::Triple::riscv64:
339     riscv::getRISCVTargetFeatures(D, Args, Features);
340     break;
341   case llvm::Triple::systemz:
342     systemz::getSystemZTargetFeatures(Args, Features);
343     break;
344   case llvm::Triple::aarch64:
345   case llvm::Triple::aarch64_be:
346     aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
347     break;
348   case llvm::Triple::x86:
349   case llvm::Triple::x86_64:
350     x86::getX86TargetFeatures(D, Triple, Args, Features);
351     break;
352   case llvm::Triple::hexagon:
353     hexagon::getHexagonTargetFeatures(D, Args, Features);
354     break;
355   case llvm::Triple::wasm32:
356   case llvm::Triple::wasm64:
357     getWebAssemblyTargetFeatures(Args, Features);
358     break;
359   case llvm::Triple::sparc:
360   case llvm::Triple::sparcel:
361   case llvm::Triple::sparcv9:
362     sparc::getSparcTargetFeatures(D, Args, Features);
363     break;
364   case llvm::Triple::r600:
365   case llvm::Triple::amdgcn:
366     amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
367     break;
368   case llvm::Triple::msp430:
369     msp430::getMSP430TargetFeatures(D, Args, Features);
370   }
371
372   // Find the last of each feature.
373   llvm::StringMap<unsigned> LastOpt;
374   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
375     StringRef Name = Features[I];
376     assert(Name[0] == '-' || Name[0] == '+');
377     LastOpt[Name.drop_front(1)] = I;
378   }
379
380   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
381     // If this feature was overridden, ignore it.
382     StringRef Name = Features[I];
383     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
384     assert(LastI != LastOpt.end());
385     unsigned Last = LastI->second;
386     if (Last != I)
387       continue;
388
389     CmdArgs.push_back("-target-feature");
390     CmdArgs.push_back(Name.data());
391   }
392 }
393
394 static bool
395 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
396                                           const llvm::Triple &Triple) {
397   // We use the zero-cost exception tables for Objective-C if the non-fragile
398   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
399   // later.
400   if (runtime.isNonFragile())
401     return true;
402
403   if (!Triple.isMacOSX())
404     return false;
405
406   return (!Triple.isMacOSXVersionLT(10, 5) &&
407           (Triple.getArch() == llvm::Triple::x86_64 ||
408            Triple.getArch() == llvm::Triple::arm));
409 }
410
411 /// Adds exception related arguments to the driver command arguments. There's a
412 /// master flag, -fexceptions and also language specific flags to enable/disable
413 /// C++ and Objective-C exceptions. This makes it possible to for example
414 /// disable C++ exceptions but enable Objective-C exceptions.
415 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
416                              const ToolChain &TC, bool KernelOrKext,
417                              const ObjCRuntime &objcRuntime,
418                              ArgStringList &CmdArgs) {
419   const llvm::Triple &Triple = TC.getTriple();
420
421   if (KernelOrKext) {
422     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
423     // arguments now to avoid warnings about unused arguments.
424     Args.ClaimAllArgs(options::OPT_fexceptions);
425     Args.ClaimAllArgs(options::OPT_fno_exceptions);
426     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
427     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
428     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
429     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
430     return;
431   }
432
433   // See if the user explicitly enabled exceptions.
434   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
435                          false);
436
437   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
438   // is not necessarily sensible, but follows GCC.
439   if (types::isObjC(InputType) &&
440       Args.hasFlag(options::OPT_fobjc_exceptions,
441                    options::OPT_fno_objc_exceptions, true)) {
442     CmdArgs.push_back("-fobjc-exceptions");
443
444     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
445   }
446
447   if (types::isCXX(InputType)) {
448     // Disable C++ EH by default on XCore and PS4.
449     bool CXXExceptionsEnabled =
450         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
451     Arg *ExceptionArg = Args.getLastArg(
452         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
453         options::OPT_fexceptions, options::OPT_fno_exceptions);
454     if (ExceptionArg)
455       CXXExceptionsEnabled =
456           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
457           ExceptionArg->getOption().matches(options::OPT_fexceptions);
458
459     if (CXXExceptionsEnabled) {
460       CmdArgs.push_back("-fcxx-exceptions");
461
462       EH = true;
463     }
464   }
465
466   if (EH)
467     CmdArgs.push_back("-fexceptions");
468 }
469
470 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
471   bool Default = true;
472   if (TC.getTriple().isOSDarwin()) {
473     // The native darwin assembler doesn't support the linker_option directives,
474     // so we disable them if we think the .s file will be passed to it.
475     Default = TC.useIntegratedAs();
476   }
477   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
478                        Default);
479 }
480
481 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482                                         const ToolChain &TC) {
483   bool UseDwarfDirectory =
484       Args.hasFlag(options::OPT_fdwarf_directory_asm,
485                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486   return !UseDwarfDirectory;
487 }
488
489 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490 // to the corresponding DebugInfoKind.
491 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492   assert(A.getOption().matches(options::OPT_gN_Group) &&
493          "Not a -g option that specifies a debug-info level");
494   if (A.getOption().matches(options::OPT_g0) ||
495       A.getOption().matches(options::OPT_ggdb0))
496     return codegenoptions::NoDebugInfo;
497   if (A.getOption().matches(options::OPT_gline_tables_only) ||
498       A.getOption().matches(options::OPT_ggdb1))
499     return codegenoptions::DebugLineTablesOnly;
500   if (A.getOption().matches(options::OPT_gline_directives_only))
501     return codegenoptions::DebugDirectivesOnly;
502   return codegenoptions::LimitedDebugInfo;
503 }
504
505 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506   switch (Triple.getArch()){
507   default:
508     return false;
509   case llvm::Triple::arm:
510   case llvm::Triple::thumb:
511     // ARM Darwin targets require a frame pointer to be always present to aid
512     // offline debugging via backtraces.
513     return Triple.isOSDarwin();
514   }
515 }
516
517 static bool useFramePointerForTargetByDefault(const ArgList &Args,
518                                               const llvm::Triple &Triple) {
519   switch (Triple.getArch()) {
520   case llvm::Triple::xcore:
521   case llvm::Triple::wasm32:
522   case llvm::Triple::wasm64:
523     // XCore never wants frame pointers, regardless of OS.
524     // WebAssembly never wants frame pointers.
525     return false;
526   case llvm::Triple::riscv32:
527   case llvm::Triple::riscv64:
528     return !areOptimizationsEnabled(Args);
529   default:
530     break;
531   }
532
533   if (Triple.isOSNetBSD()) {
534     return !areOptimizationsEnabled(Args);
535   }
536
537   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
538       Triple.isOSHurd()) {
539     switch (Triple.getArch()) {
540     // Don't use a frame pointer on linux if optimizing for certain targets.
541     case llvm::Triple::mips64:
542     case llvm::Triple::mips64el:
543     case llvm::Triple::mips:
544     case llvm::Triple::mipsel:
545     case llvm::Triple::ppc:
546     case llvm::Triple::ppc64:
547     case llvm::Triple::ppc64le:
548     case llvm::Triple::systemz:
549     case llvm::Triple::x86:
550     case llvm::Triple::x86_64:
551       return !areOptimizationsEnabled(Args);
552     default:
553       return true;
554     }
555   }
556
557   if (Triple.isOSWindows()) {
558     switch (Triple.getArch()) {
559     case llvm::Triple::x86:
560       return !areOptimizationsEnabled(Args);
561     case llvm::Triple::x86_64:
562       return Triple.isOSBinFormatMachO();
563     case llvm::Triple::arm:
564     case llvm::Triple::thumb:
565       // Windows on ARM builds with FPO disabled to aid fast stack walking
566       return true;
567     default:
568       // All other supported Windows ISAs use xdata unwind information, so frame
569       // pointers are not generally useful.
570       return false;
571     }
572   }
573
574   return true;
575 }
576
577 static bool shouldUseFramePointer(const ArgList &Args,
578                                   const llvm::Triple &Triple) {
579   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
580                                options::OPT_fomit_frame_pointer))
581     return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
582            mustUseNonLeafFramePointerForTarget(Triple);
583
584   if (Args.hasArg(options::OPT_pg))
585     return true;
586
587   return useFramePointerForTargetByDefault(Args, Triple);
588 }
589
590 static bool shouldUseLeafFramePointer(const ArgList &Args,
591                                       const llvm::Triple &Triple) {
592   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
593                                options::OPT_momit_leaf_frame_pointer))
594     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
595
596   if (Args.hasArg(options::OPT_pg))
597     return true;
598
599   if (Triple.isPS4CPU())
600     return false;
601
602   return useFramePointerForTargetByDefault(Args, Triple);
603 }
604
605 /// Add a CC1 option to specify the debug compilation directory.
606 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
607   SmallString<128> cwd;
608   if (!llvm::sys::fs::current_path(cwd)) {
609     CmdArgs.push_back("-fdebug-compilation-dir");
610     CmdArgs.push_back(Args.MakeArgString(cwd));
611   }
612 }
613
614 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
615 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
616   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
617     StringRef Map = A->getValue();
618     if (Map.find('=') == StringRef::npos)
619       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
620     else
621       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
622     A->claim();
623   }
624 }
625
626 /// Vectorize at all optimization levels greater than 1 except for -Oz.
627 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
628 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
629   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
630     if (A->getOption().matches(options::OPT_O4) ||
631         A->getOption().matches(options::OPT_Ofast))
632       return true;
633
634     if (A->getOption().matches(options::OPT_O0))
635       return false;
636
637     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
638
639     // Vectorize -Os.
640     StringRef S(A->getValue());
641     if (S == "s")
642       return true;
643
644     // Don't vectorize -Oz, unless it's the slp vectorizer.
645     if (S == "z")
646       return isSlpVec;
647
648     unsigned OptLevel = 0;
649     if (S.getAsInteger(10, OptLevel))
650       return false;
651
652     return OptLevel > 1;
653   }
654
655   return false;
656 }
657
658 /// Add -x lang to \p CmdArgs for \p Input.
659 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
660                              ArgStringList &CmdArgs) {
661   // When using -verify-pch, we don't want to provide the type
662   // 'precompiled-header' if it was inferred from the file extension
663   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
664     return;
665
666   CmdArgs.push_back("-x");
667   if (Args.hasArg(options::OPT_rewrite_objc))
668     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
669   else {
670     // Map the driver type to the frontend type. This is mostly an identity
671     // mapping, except that the distinction between module interface units
672     // and other source files does not exist at the frontend layer.
673     const char *ClangType;
674     switch (Input.getType()) {
675     case types::TY_CXXModule:
676       ClangType = "c++";
677       break;
678     case types::TY_PP_CXXModule:
679       ClangType = "c++-cpp-output";
680       break;
681     default:
682       ClangType = types::getTypeName(Input.getType());
683       break;
684     }
685     CmdArgs.push_back(ClangType);
686   }
687 }
688
689 static void appendUserToPath(SmallVectorImpl<char> &Result) {
690 #ifdef LLVM_ON_UNIX
691   const char *Username = getenv("LOGNAME");
692 #else
693   const char *Username = getenv("USERNAME");
694 #endif
695   if (Username) {
696     // Validate that LoginName can be used in a path, and get its length.
697     size_t Len = 0;
698     for (const char *P = Username; *P; ++P, ++Len) {
699       if (!clang::isAlphanumeric(*P) && *P != '_') {
700         Username = nullptr;
701         break;
702       }
703     }
704
705     if (Username && Len > 0) {
706       Result.append(Username, Username + Len);
707       return;
708     }
709   }
710
711 // Fallback to user id.
712 #ifdef LLVM_ON_UNIX
713   std::string UID = llvm::utostr(getuid());
714 #else
715   // FIXME: Windows seems to have an 'SID' that might work.
716   std::string UID = "9999";
717 #endif
718   Result.append(UID.begin(), UID.end());
719 }
720
721 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
722                                    const InputInfo &Output, const ArgList &Args,
723                                    ArgStringList &CmdArgs) {
724
725   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726                                          options::OPT_fprofile_generate_EQ,
727                                          options::OPT_fno_profile_generate);
728   if (PGOGenerateArg &&
729       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730     PGOGenerateArg = nullptr;
731
732   auto *ProfileGenerateArg = Args.getLastArg(
733       options::OPT_fprofile_instr_generate,
734       options::OPT_fprofile_instr_generate_EQ,
735       options::OPT_fno_profile_instr_generate);
736   if (ProfileGenerateArg &&
737       ProfileGenerateArg->getOption().matches(
738           options::OPT_fno_profile_instr_generate))
739     ProfileGenerateArg = nullptr;
740
741   if (PGOGenerateArg && ProfileGenerateArg)
742     D.Diag(diag::err_drv_argument_not_allowed_with)
743         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
744
745   auto *ProfileUseArg = getLastProfileUseArg(Args);
746
747   if (PGOGenerateArg && ProfileUseArg)
748     D.Diag(diag::err_drv_argument_not_allowed_with)
749         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
750
751   if (ProfileGenerateArg && ProfileUseArg)
752     D.Diag(diag::err_drv_argument_not_allowed_with)
753         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
754
755   if (ProfileGenerateArg) {
756     if (ProfileGenerateArg->getOption().matches(
757             options::OPT_fprofile_instr_generate_EQ))
758       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
759                                            ProfileGenerateArg->getValue()));
760     // The default is to use Clang Instrumentation.
761     CmdArgs.push_back("-fprofile-instrument=clang");
762   }
763
764   if (PGOGenerateArg) {
765     CmdArgs.push_back("-fprofile-instrument=llvm");
766     if (PGOGenerateArg->getOption().matches(
767             options::OPT_fprofile_generate_EQ)) {
768       SmallString<128> Path(PGOGenerateArg->getValue());
769       llvm::sys::path::append(Path, "default_%m.profraw");
770       CmdArgs.push_back(
771           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
772     }
773   }
774
775   if (ProfileUseArg) {
776     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
777       CmdArgs.push_back(Args.MakeArgString(
778           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
779     else if ((ProfileUseArg->getOption().matches(
780                   options::OPT_fprofile_use_EQ) ||
781               ProfileUseArg->getOption().matches(
782                   options::OPT_fprofile_instr_use))) {
783       SmallString<128> Path(
784           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
785       if (Path.empty() || llvm::sys::fs::is_directory(Path))
786         llvm::sys::path::append(Path, "default.profdata");
787       CmdArgs.push_back(
788           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
789     }
790   }
791
792   if (Args.hasArg(options::OPT_ftest_coverage) ||
793       Args.hasArg(options::OPT_coverage))
794     CmdArgs.push_back("-femit-coverage-notes");
795   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
796                    false) ||
797       Args.hasArg(options::OPT_coverage))
798     CmdArgs.push_back("-femit-coverage-data");
799
800   if (Args.hasFlag(options::OPT_fcoverage_mapping,
801                    options::OPT_fno_coverage_mapping, false)) {
802     if (!ProfileGenerateArg)
803       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
804           << "-fcoverage-mapping"
805           << "-fprofile-instr-generate";
806
807     CmdArgs.push_back("-fcoverage-mapping");
808   }
809
810   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
811     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
812     if (!Args.hasArg(options::OPT_coverage))
813       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
814           << "-fprofile-exclude-files="
815           << "--coverage";
816
817     StringRef v = Arg->getValue();
818     CmdArgs.push_back(
819         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
820   }
821
822   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
823     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
824     if (!Args.hasArg(options::OPT_coverage))
825       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
826           << "-fprofile-filter-files="
827           << "--coverage";
828
829     StringRef v = Arg->getValue();
830     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
831   }
832
833   if (C.getArgs().hasArg(options::OPT_c) ||
834       C.getArgs().hasArg(options::OPT_S)) {
835     if (Output.isFilename()) {
836       CmdArgs.push_back("-coverage-notes-file");
837       SmallString<128> OutputFilename;
838       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
839         OutputFilename = FinalOutput->getValue();
840       else
841         OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
842       SmallString<128> CoverageFilename = OutputFilename;
843       if (llvm::sys::path::is_relative(CoverageFilename)) {
844         SmallString<128> Pwd;
845         if (!llvm::sys::fs::current_path(Pwd)) {
846           llvm::sys::path::append(Pwd, CoverageFilename);
847           CoverageFilename.swap(Pwd);
848         }
849       }
850       llvm::sys::path::replace_extension(CoverageFilename, "gcno");
851       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
852
853       // Leave -fprofile-dir= an unused argument unless .gcda emission is
854       // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
855       // the flag used. There is no -fno-profile-dir, so the user has no
856       // targeted way to suppress the warning.
857       if (Args.hasArg(options::OPT_fprofile_arcs) ||
858           Args.hasArg(options::OPT_coverage)) {
859         CmdArgs.push_back("-coverage-data-file");
860         if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
861           CoverageFilename = FProfileDir->getValue();
862           llvm::sys::path::append(CoverageFilename, OutputFilename);
863         }
864         llvm::sys::path::replace_extension(CoverageFilename, "gcda");
865         CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
866       }
867     }
868   }
869 }
870
871 /// Check whether the given input tree contains any compilation actions.
872 static bool ContainsCompileAction(const Action *A) {
873   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
874     return true;
875
876   for (const auto &AI : A->inputs())
877     if (ContainsCompileAction(AI))
878       return true;
879
880   return false;
881 }
882
883 /// Check if -relax-all should be passed to the internal assembler.
884 /// This is done by default when compiling non-assembler source with -O0.
885 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
886   bool RelaxDefault = true;
887
888   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
889     RelaxDefault = A->getOption().matches(options::OPT_O0);
890
891   if (RelaxDefault) {
892     RelaxDefault = false;
893     for (const auto &Act : C.getActions()) {
894       if (ContainsCompileAction(Act)) {
895         RelaxDefault = true;
896         break;
897       }
898     }
899   }
900
901   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
902                       RelaxDefault);
903 }
904
905 // Extract the integer N from a string spelled "-dwarf-N", returning 0
906 // on mismatch. The StringRef input (rather than an Arg) allows
907 // for use by the "-Xassembler" option parser.
908 static unsigned DwarfVersionNum(StringRef ArgValue) {
909   return llvm::StringSwitch<unsigned>(ArgValue)
910       .Case("-gdwarf-2", 2)
911       .Case("-gdwarf-3", 3)
912       .Case("-gdwarf-4", 4)
913       .Case("-gdwarf-5", 5)
914       .Default(0);
915 }
916
917 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
918                                     codegenoptions::DebugInfoKind DebugInfoKind,
919                                     unsigned DwarfVersion,
920                                     llvm::DebuggerKind DebuggerTuning) {
921   switch (DebugInfoKind) {
922   case codegenoptions::DebugDirectivesOnly:
923     CmdArgs.push_back("-debug-info-kind=line-directives-only");
924     break;
925   case codegenoptions::DebugLineTablesOnly:
926     CmdArgs.push_back("-debug-info-kind=line-tables-only");
927     break;
928   case codegenoptions::LimitedDebugInfo:
929     CmdArgs.push_back("-debug-info-kind=limited");
930     break;
931   case codegenoptions::FullDebugInfo:
932     CmdArgs.push_back("-debug-info-kind=standalone");
933     break;
934   default:
935     break;
936   }
937   if (DwarfVersion > 0)
938     CmdArgs.push_back(
939         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
940   switch (DebuggerTuning) {
941   case llvm::DebuggerKind::GDB:
942     CmdArgs.push_back("-debugger-tuning=gdb");
943     break;
944   case llvm::DebuggerKind::LLDB:
945     CmdArgs.push_back("-debugger-tuning=lldb");
946     break;
947   case llvm::DebuggerKind::SCE:
948     CmdArgs.push_back("-debugger-tuning=sce");
949     break;
950   default:
951     break;
952   }
953 }
954
955 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
956                                  const Driver &D, const ToolChain &TC) {
957   assert(A && "Expected non-nullptr argument.");
958   if (TC.supportsDebugInfoOption(A))
959     return true;
960   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
961       << A->getAsString(Args) << TC.getTripleString();
962   return false;
963 }
964
965 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
966                                            ArgStringList &CmdArgs,
967                                            const Driver &D,
968                                            const ToolChain &TC) {
969   const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
970   if (!A)
971     return;
972   if (checkDebugInfoOption(A, Args, D, TC)) {
973     if (A->getOption().getID() == options::OPT_gz) {
974       if (llvm::zlib::isAvailable())
975         CmdArgs.push_back("-compress-debug-sections");
976       else
977         D.Diag(diag::warn_debug_compression_unavailable);
978       return;
979     }
980
981     StringRef Value = A->getValue();
982     if (Value == "none") {
983       CmdArgs.push_back("-compress-debug-sections=none");
984     } else if (Value == "zlib" || Value == "zlib-gnu") {
985       if (llvm::zlib::isAvailable()) {
986         CmdArgs.push_back(
987             Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
988       } else {
989         D.Diag(diag::warn_debug_compression_unavailable);
990       }
991     } else {
992       D.Diag(diag::err_drv_unsupported_option_argument)
993           << A->getOption().getName() << Value;
994     }
995   }
996 }
997
998 static const char *RelocationModelName(llvm::Reloc::Model Model) {
999   switch (Model) {
1000   case llvm::Reloc::Static:
1001     return "static";
1002   case llvm::Reloc::PIC_:
1003     return "pic";
1004   case llvm::Reloc::DynamicNoPIC:
1005     return "dynamic-no-pic";
1006   case llvm::Reloc::ROPI:
1007     return "ropi";
1008   case llvm::Reloc::RWPI:
1009     return "rwpi";
1010   case llvm::Reloc::ROPI_RWPI:
1011     return "ropi-rwpi";
1012   }
1013   llvm_unreachable("Unknown Reloc::Model kind");
1014 }
1015
1016 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1017                                     const Driver &D, const ArgList &Args,
1018                                     ArgStringList &CmdArgs,
1019                                     const InputInfo &Output,
1020                                     const InputInfoList &Inputs) const {
1021   Arg *A;
1022   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1023
1024   CheckPreprocessingOptions(D, Args);
1025
1026   Args.AddLastArg(CmdArgs, options::OPT_C);
1027   Args.AddLastArg(CmdArgs, options::OPT_CC);
1028
1029   // Handle dependency file generation.
1030   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1031       (A = Args.getLastArg(options::OPT_MD)) ||
1032       (A = Args.getLastArg(options::OPT_MMD))) {
1033     // Determine the output location.
1034     const char *DepFile;
1035     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1036       DepFile = MF->getValue();
1037       C.addFailureResultFile(DepFile, &JA);
1038     } else if (Output.getType() == types::TY_Dependencies) {
1039       DepFile = Output.getFilename();
1040     } else if (A->getOption().matches(options::OPT_M) ||
1041                A->getOption().matches(options::OPT_MM)) {
1042       DepFile = "-";
1043     } else {
1044       DepFile = getDependencyFileName(Args, Inputs);
1045       C.addFailureResultFile(DepFile, &JA);
1046     }
1047     CmdArgs.push_back("-dependency-file");
1048     CmdArgs.push_back(DepFile);
1049
1050     // Add a default target if one wasn't specified.
1051     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1052       const char *DepTarget;
1053
1054       // If user provided -o, that is the dependency target, except
1055       // when we are only generating a dependency file.
1056       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1057       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1058         DepTarget = OutputOpt->getValue();
1059       } else {
1060         // Otherwise derive from the base input.
1061         //
1062         // FIXME: This should use the computed output file location.
1063         SmallString<128> P(Inputs[0].getBaseInput());
1064         llvm::sys::path::replace_extension(P, "o");
1065         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1066       }
1067
1068       if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1069         CmdArgs.push_back("-w");
1070       }
1071       CmdArgs.push_back("-MT");
1072       SmallString<128> Quoted;
1073       QuoteTarget(DepTarget, Quoted);
1074       CmdArgs.push_back(Args.MakeArgString(Quoted));
1075     }
1076
1077     if (A->getOption().matches(options::OPT_M) ||
1078         A->getOption().matches(options::OPT_MD))
1079       CmdArgs.push_back("-sys-header-deps");
1080     if ((isa<PrecompileJobAction>(JA) &&
1081          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1082         Args.hasArg(options::OPT_fmodule_file_deps))
1083       CmdArgs.push_back("-module-file-deps");
1084   }
1085
1086   if (Args.hasArg(options::OPT_MG)) {
1087     if (!A || A->getOption().matches(options::OPT_MD) ||
1088         A->getOption().matches(options::OPT_MMD))
1089       D.Diag(diag::err_drv_mg_requires_m_or_mm);
1090     CmdArgs.push_back("-MG");
1091   }
1092
1093   Args.AddLastArg(CmdArgs, options::OPT_MP);
1094   Args.AddLastArg(CmdArgs, options::OPT_MV);
1095
1096   // Convert all -MQ <target> args to -MT <quoted target>
1097   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1098     A->claim();
1099
1100     if (A->getOption().matches(options::OPT_MQ)) {
1101       CmdArgs.push_back("-MT");
1102       SmallString<128> Quoted;
1103       QuoteTarget(A->getValue(), Quoted);
1104       CmdArgs.push_back(Args.MakeArgString(Quoted));
1105
1106       // -MT flag - no change
1107     } else {
1108       A->render(Args, CmdArgs);
1109     }
1110   }
1111
1112   // Add offload include arguments specific for CUDA.  This must happen before
1113   // we -I or -include anything else, because we must pick up the CUDA headers
1114   // from the particular CUDA installation, rather than from e.g.
1115   // /usr/local/include.
1116   if (JA.isOffloading(Action::OFK_Cuda))
1117     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1118
1119   // Add -i* options, and automatically translate to
1120   // -include-pch/-include-pth for transparent PCH support. It's
1121   // wonky, but we include looking for .gch so we can support seamless
1122   // replacement into a build system already set up to be generating
1123   // .gch files.
1124
1125   if (getToolChain().getDriver().IsCLMode()) {
1126     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1127     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1128     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1129         JA.getKind() <= Action::AssembleJobClass) {
1130       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1131     }
1132     if (YcArg || YuArg) {
1133       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1134       if (!isa<PrecompileJobAction>(JA)) {
1135         CmdArgs.push_back("-include-pch");
1136         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1137             C, !ThroughHeader.empty()
1138                    ? ThroughHeader
1139                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1140       }
1141
1142       if (ThroughHeader.empty()) {
1143         CmdArgs.push_back(Args.MakeArgString(
1144             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1145       } else {
1146         CmdArgs.push_back(
1147             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1148       }
1149     }
1150   }
1151
1152   bool RenderedImplicitInclude = false;
1153   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1154     if (A->getOption().matches(options::OPT_include)) {
1155       // Handling of gcc-style gch precompiled headers.
1156       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1157       RenderedImplicitInclude = true;
1158
1159       bool FoundPCH = false;
1160       SmallString<128> P(A->getValue());
1161       // We want the files to have a name like foo.h.pch. Add a dummy extension
1162       // so that replace_extension does the right thing.
1163       P += ".dummy";
1164       llvm::sys::path::replace_extension(P, "pch");
1165       if (llvm::sys::fs::exists(P))
1166         FoundPCH = true;
1167
1168       if (!FoundPCH) {
1169         llvm::sys::path::replace_extension(P, "gch");
1170         if (llvm::sys::fs::exists(P)) {
1171           FoundPCH = true;
1172         }
1173       }
1174
1175       if (FoundPCH) {
1176         if (IsFirstImplicitInclude) {
1177           A->claim();
1178           CmdArgs.push_back("-include-pch");
1179           CmdArgs.push_back(Args.MakeArgString(P));
1180           continue;
1181         } else {
1182           // Ignore the PCH if not first on command line and emit warning.
1183           D.Diag(diag::warn_drv_pch_not_first_include) << P
1184                                                        << A->getAsString(Args);
1185         }
1186       }
1187     } else if (A->getOption().matches(options::OPT_isystem_after)) {
1188       // Handling of paths which must come late.  These entries are handled by
1189       // the toolchain itself after the resource dir is inserted in the right
1190       // search order.
1191       // Do not claim the argument so that the use of the argument does not
1192       // silently go unnoticed on toolchains which do not honour the option.
1193       continue;
1194     }
1195
1196     // Not translated, render as usual.
1197     A->claim();
1198     A->render(Args, CmdArgs);
1199   }
1200
1201   Args.AddAllArgs(CmdArgs,
1202                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1203                    options::OPT_F, options::OPT_index_header_map});
1204
1205   // Add -Wp, and -Xpreprocessor if using the preprocessor.
1206
1207   // FIXME: There is a very unfortunate problem here, some troubled
1208   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1209   // really support that we would have to parse and then translate
1210   // those options. :(
1211   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1212                        options::OPT_Xpreprocessor);
1213
1214   // -I- is a deprecated GCC feature, reject it.
1215   if (Arg *A = Args.getLastArg(options::OPT_I_))
1216     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1217
1218   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1219   // -isysroot to the CC1 invocation.
1220   StringRef sysroot = C.getSysRoot();
1221   if (sysroot != "") {
1222     if (!Args.hasArg(options::OPT_isysroot)) {
1223       CmdArgs.push_back("-isysroot");
1224       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1225     }
1226   }
1227
1228   // Parse additional include paths from environment variables.
1229   // FIXME: We should probably sink the logic for handling these from the
1230   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1231   // CPATH - included following the user specified includes (but prior to
1232   // builtin and standard includes).
1233   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1234   // C_INCLUDE_PATH - system includes enabled when compiling C.
1235   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1236   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1237   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1238   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1239   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1240   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1241   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1242
1243   // While adding the include arguments, we also attempt to retrieve the
1244   // arguments of related offloading toolchains or arguments that are specific
1245   // of an offloading programming model.
1246
1247   // Add C++ include arguments, if needed.
1248   if (types::isCXX(Inputs[0].getType()))
1249     forAllAssociatedToolChains(C, JA, getToolChain(),
1250                                [&Args, &CmdArgs](const ToolChain &TC) {
1251                                  TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1252                                });
1253
1254   // Add system include arguments for all targets but IAMCU.
1255   if (!IsIAMCU)
1256     forAllAssociatedToolChains(C, JA, getToolChain(),
1257                                [&Args, &CmdArgs](const ToolChain &TC) {
1258                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1259                                });
1260   else {
1261     // For IAMCU add special include arguments.
1262     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1263   }
1264 }
1265
1266 // FIXME: Move to target hook.
1267 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1268   switch (Triple.getArch()) {
1269   default:
1270     return true;
1271
1272   case llvm::Triple::aarch64:
1273   case llvm::Triple::aarch64_be:
1274   case llvm::Triple::arm:
1275   case llvm::Triple::armeb:
1276   case llvm::Triple::thumb:
1277   case llvm::Triple::thumbeb:
1278     if (Triple.isOSDarwin() || Triple.isOSWindows())
1279       return true;
1280     return false;
1281
1282   case llvm::Triple::ppc:
1283   case llvm::Triple::ppc64:
1284     if (Triple.isOSDarwin())
1285       return true;
1286     return false;
1287
1288   case llvm::Triple::hexagon:
1289   case llvm::Triple::ppc64le:
1290   case llvm::Triple::riscv32:
1291   case llvm::Triple::riscv64:
1292   case llvm::Triple::systemz:
1293   case llvm::Triple::xcore:
1294     return false;
1295   }
1296 }
1297
1298 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1299   switch (Triple.getArch()) {
1300   default:
1301     if (Triple.isOSFuchsia())
1302       return true;
1303     return false;
1304
1305   case llvm::Triple::xcore:
1306   case llvm::Triple::wasm32:
1307   case llvm::Triple::wasm64:
1308     return true;
1309   }
1310 }
1311
1312 namespace {
1313 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1314                   ArgStringList &CmdArgs) {
1315   // Select the ABI to use.
1316   // FIXME: Support -meabi.
1317   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1318   const char *ABIName = nullptr;
1319   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1320     ABIName = A->getValue();
1321   } else {
1322     std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1323     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1324   }
1325
1326   CmdArgs.push_back("-target-abi");
1327   CmdArgs.push_back(ABIName);
1328 }
1329 }
1330
1331 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1332                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1333   RenderARMABI(Triple, Args, CmdArgs);
1334
1335   // Determine floating point ABI from the options & target defaults.
1336   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1337   if (ABI == arm::FloatABI::Soft) {
1338     // Floating point operations and argument passing are soft.
1339     // FIXME: This changes CPP defines, we need -target-soft-float.
1340     CmdArgs.push_back("-msoft-float");
1341     CmdArgs.push_back("-mfloat-abi");
1342     CmdArgs.push_back("soft");
1343   } else if (ABI == arm::FloatABI::SoftFP) {
1344     // Floating point operations are hard, but argument passing is soft.
1345     CmdArgs.push_back("-mfloat-abi");
1346     CmdArgs.push_back("soft");
1347   } else {
1348     // Floating point operations and argument passing are hard.
1349     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1350     CmdArgs.push_back("-mfloat-abi");
1351     CmdArgs.push_back("hard");
1352   }
1353
1354   // Forward the -mglobal-merge option for explicit control over the pass.
1355   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1356                                options::OPT_mno_global_merge)) {
1357     CmdArgs.push_back("-mllvm");
1358     if (A->getOption().matches(options::OPT_mno_global_merge))
1359       CmdArgs.push_back("-arm-global-merge=false");
1360     else
1361       CmdArgs.push_back("-arm-global-merge=true");
1362   }
1363
1364   if (!Args.hasFlag(options::OPT_mimplicit_float,
1365                     options::OPT_mno_implicit_float, true))
1366     CmdArgs.push_back("-no-implicit-float");
1367 }
1368
1369 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1370                                 const ArgList &Args, bool KernelOrKext,
1371                                 ArgStringList &CmdArgs) const {
1372   const ToolChain &TC = getToolChain();
1373
1374   // Add the target features
1375   getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1376
1377   // Add target specific flags.
1378   switch (TC.getArch()) {
1379   default:
1380     break;
1381
1382   case llvm::Triple::arm:
1383   case llvm::Triple::armeb:
1384   case llvm::Triple::thumb:
1385   case llvm::Triple::thumbeb:
1386     // Use the effective triple, which takes into account the deployment target.
1387     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1388     CmdArgs.push_back("-fallow-half-arguments-and-returns");
1389     break;
1390
1391   case llvm::Triple::aarch64:
1392   case llvm::Triple::aarch64_be:
1393     AddAArch64TargetArgs(Args, CmdArgs);
1394     CmdArgs.push_back("-fallow-half-arguments-and-returns");
1395     break;
1396
1397   case llvm::Triple::mips:
1398   case llvm::Triple::mipsel:
1399   case llvm::Triple::mips64:
1400   case llvm::Triple::mips64el:
1401     AddMIPSTargetArgs(Args, CmdArgs);
1402     break;
1403
1404   case llvm::Triple::ppc:
1405   case llvm::Triple::ppc64:
1406   case llvm::Triple::ppc64le:
1407     AddPPCTargetArgs(Args, CmdArgs);
1408     break;
1409
1410   case llvm::Triple::riscv32:
1411   case llvm::Triple::riscv64:
1412     AddRISCVTargetArgs(Args, CmdArgs);
1413     break;
1414
1415   case llvm::Triple::sparc:
1416   case llvm::Triple::sparcel:
1417   case llvm::Triple::sparcv9:
1418     AddSparcTargetArgs(Args, CmdArgs);
1419     break;
1420
1421   case llvm::Triple::systemz:
1422     AddSystemZTargetArgs(Args, CmdArgs);
1423     break;
1424
1425   case llvm::Triple::x86:
1426   case llvm::Triple::x86_64:
1427     AddX86TargetArgs(Args, CmdArgs);
1428     break;
1429
1430   case llvm::Triple::lanai:
1431     AddLanaiTargetArgs(Args, CmdArgs);
1432     break;
1433
1434   case llvm::Triple::hexagon:
1435     AddHexagonTargetArgs(Args, CmdArgs);
1436     break;
1437
1438   case llvm::Triple::wasm32:
1439   case llvm::Triple::wasm64:
1440     AddWebAssemblyTargetArgs(Args, CmdArgs);
1441     break;
1442   }
1443 }
1444
1445 // Parse -mbranch-protection=<protection>[+<protection>]* where
1446 //   <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1447 // Returns a triple of (return address signing Scope, signing key, require
1448 // landing pads)
1449 static std::tuple<StringRef, StringRef, bool>
1450 ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1451                              const Arg *A) {
1452   StringRef Scope = "none";
1453   StringRef Key = "a_key";
1454   bool IndirectBranches = false;
1455
1456   StringRef Value = A->getValue();
1457   // This maps onto -mbranch-protection=<scope>+<key>
1458
1459   if (Value.equals("standard")) {
1460     Scope = "non-leaf";
1461     Key = "a_key";
1462     IndirectBranches = true;
1463
1464   } else if (!Value.equals("none")) {
1465     SmallVector<StringRef, 4> BranchProtection;
1466     StringRef(A->getValue()).split(BranchProtection, '+');
1467
1468     auto Protection = BranchProtection.begin();
1469     while (Protection != BranchProtection.end()) {
1470       if (Protection->equals("bti"))
1471         IndirectBranches = true;
1472       else if (Protection->equals("pac-ret")) {
1473         Scope = "non-leaf";
1474         while (++Protection != BranchProtection.end()) {
1475           // Inner loop as "leaf" and "b-key" options must only appear attached
1476           // to pac-ret.
1477           if (Protection->equals("leaf"))
1478             Scope = "all";
1479           else if (Protection->equals("b-key"))
1480             Key = "b_key";
1481           else
1482             break;
1483         }
1484         Protection--;
1485       } else
1486         D.Diag(diag::err_invalid_branch_protection)
1487             << *Protection << A->getAsString(Args);
1488       Protection++;
1489     }
1490   }
1491
1492   return std::make_tuple(Scope, Key, IndirectBranches);
1493 }
1494
1495 namespace {
1496 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1497                       ArgStringList &CmdArgs) {
1498   const char *ABIName = nullptr;
1499   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1500     ABIName = A->getValue();
1501   else if (Triple.isOSDarwin())
1502     ABIName = "darwinpcs";
1503   else
1504     ABIName = "aapcs";
1505
1506   CmdArgs.push_back("-target-abi");
1507   CmdArgs.push_back(ABIName);
1508 }
1509 }
1510
1511 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1512                                  ArgStringList &CmdArgs) const {
1513   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1514
1515   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1516       Args.hasArg(options::OPT_mkernel) ||
1517       Args.hasArg(options::OPT_fapple_kext))
1518     CmdArgs.push_back("-disable-red-zone");
1519
1520   if (!Args.hasFlag(options::OPT_mimplicit_float,
1521                     options::OPT_mno_implicit_float, true))
1522     CmdArgs.push_back("-no-implicit-float");
1523
1524   RenderAArch64ABI(Triple, Args, CmdArgs);
1525
1526   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1527                                options::OPT_mno_fix_cortex_a53_835769)) {
1528     CmdArgs.push_back("-mllvm");
1529     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1530       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1531     else
1532       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1533   } else if (Triple.isAndroid()) {
1534     // Enabled A53 errata (835769) workaround by default on android
1535     CmdArgs.push_back("-mllvm");
1536     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1537   }
1538
1539   // Forward the -mglobal-merge option for explicit control over the pass.
1540   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1541                                options::OPT_mno_global_merge)) {
1542     CmdArgs.push_back("-mllvm");
1543     if (A->getOption().matches(options::OPT_mno_global_merge))
1544       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1545     else
1546       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1547   }
1548
1549   // Enable/disable return address signing and indirect branch targets.
1550   if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1551                                options::OPT_mbranch_protection_EQ)) {
1552
1553     const Driver &D = getToolChain().getDriver();
1554
1555     StringRef Scope, Key;
1556     bool IndirectBranches;
1557
1558     if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1559       Scope = A->getValue();
1560       if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1561           !Scope.equals("all"))
1562         D.Diag(diag::err_invalid_branch_protection)
1563             << Scope << A->getAsString(Args);
1564       Key = "a_key";
1565       IndirectBranches = false;
1566     } else
1567       std::tie(Scope, Key, IndirectBranches) =
1568           ParseAArch64BranchProtection(D, Args, A);
1569
1570     CmdArgs.push_back(
1571         Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1572     CmdArgs.push_back(
1573         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1574     if (IndirectBranches)
1575       CmdArgs.push_back("-mbranch-target-enforce");
1576   }
1577 }
1578
1579 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1580                               ArgStringList &CmdArgs) const {
1581   const Driver &D = getToolChain().getDriver();
1582   StringRef CPUName;
1583   StringRef ABIName;
1584   const llvm::Triple &Triple = getToolChain().getTriple();
1585   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1586
1587   CmdArgs.push_back("-target-abi");
1588   CmdArgs.push_back(ABIName.data());
1589
1590   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1591   if (ABI == mips::FloatABI::Soft) {
1592     // Floating point operations and argument passing are soft.
1593     CmdArgs.push_back("-msoft-float");
1594     CmdArgs.push_back("-mfloat-abi");
1595     CmdArgs.push_back("soft");
1596   } else {
1597     // Floating point operations and argument passing are hard.
1598     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1599     CmdArgs.push_back("-mfloat-abi");
1600     CmdArgs.push_back("hard");
1601   }
1602
1603   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1604     if (A->getOption().matches(options::OPT_mxgot)) {
1605       CmdArgs.push_back("-mllvm");
1606       CmdArgs.push_back("-mxgot");
1607     }
1608   }
1609
1610   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1611                                options::OPT_mno_ldc1_sdc1)) {
1612     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1613       CmdArgs.push_back("-mllvm");
1614       CmdArgs.push_back("-mno-ldc1-sdc1");
1615     }
1616   }
1617
1618   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1619                                options::OPT_mno_check_zero_division)) {
1620     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1621       CmdArgs.push_back("-mllvm");
1622       CmdArgs.push_back("-mno-check-zero-division");
1623     }
1624   }
1625
1626   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1627     StringRef v = A->getValue();
1628     CmdArgs.push_back("-mllvm");
1629     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1630     A->claim();
1631   }
1632
1633   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1634   Arg *ABICalls =
1635       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1636
1637   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1638   // -mgpopt is the default for static, -fno-pic environments but these two
1639   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1640   // the only case where -mllvm -mgpopt is passed.
1641   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1642   //       passed explicitly when compiling something with -mabicalls
1643   //       (implictly) in affect. Currently the warning is in the backend.
1644   //
1645   // When the ABI in use is  N64, we also need to determine the PIC mode that
1646   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1647   bool NoABICalls =
1648       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1649
1650   llvm::Reloc::Model RelocationModel;
1651   unsigned PICLevel;
1652   bool IsPIE;
1653   std::tie(RelocationModel, PICLevel, IsPIE) =
1654       ParsePICArgs(getToolChain(), Args);
1655
1656   NoABICalls = NoABICalls ||
1657                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1658
1659   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1660   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1661   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1662     CmdArgs.push_back("-mllvm");
1663     CmdArgs.push_back("-mgpopt");
1664
1665     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1666                                       options::OPT_mno_local_sdata);
1667     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1668                                        options::OPT_mno_extern_sdata);
1669     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1670                                         options::OPT_mno_embedded_data);
1671     if (LocalSData) {
1672       CmdArgs.push_back("-mllvm");
1673       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1674         CmdArgs.push_back("-mlocal-sdata=1");
1675       } else {
1676         CmdArgs.push_back("-mlocal-sdata=0");
1677       }
1678       LocalSData->claim();
1679     }
1680
1681     if (ExternSData) {
1682       CmdArgs.push_back("-mllvm");
1683       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1684         CmdArgs.push_back("-mextern-sdata=1");
1685       } else {
1686         CmdArgs.push_back("-mextern-sdata=0");
1687       }
1688       ExternSData->claim();
1689     }
1690
1691     if (EmbeddedData) {
1692       CmdArgs.push_back("-mllvm");
1693       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1694         CmdArgs.push_back("-membedded-data=1");
1695       } else {
1696         CmdArgs.push_back("-membedded-data=0");
1697       }
1698       EmbeddedData->claim();
1699     }
1700
1701   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1702     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1703
1704   if (GPOpt)
1705     GPOpt->claim();
1706
1707   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1708     StringRef Val = StringRef(A->getValue());
1709     if (mips::hasCompactBranches(CPUName)) {
1710       if (Val == "never" || Val == "always" || Val == "optimal") {
1711         CmdArgs.push_back("-mllvm");
1712         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1713       } else
1714         D.Diag(diag::err_drv_unsupported_option_argument)
1715             << A->getOption().getName() << Val;
1716     } else
1717       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1718   }
1719 }
1720
1721 void Clang::AddPPCTargetArgs(const ArgList &Args,
1722                              ArgStringList &CmdArgs) const {
1723   // Select the ABI to use.
1724   const char *ABIName = nullptr;
1725   if (getToolChain().getTriple().isOSLinux())
1726     switch (getToolChain().getArch()) {
1727     case llvm::Triple::ppc64: {
1728       // When targeting a processor that supports QPX, or if QPX is
1729       // specifically enabled, default to using the ABI that supports QPX (so
1730       // long as it is not specifically disabled).
1731       bool HasQPX = false;
1732       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1733         HasQPX = A->getValue() == StringRef("a2q");
1734       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1735       if (HasQPX) {
1736         ABIName = "elfv1-qpx";
1737         break;
1738       }
1739
1740       ABIName = "elfv1";
1741       break;
1742     }
1743     case llvm::Triple::ppc64le:
1744       ABIName = "elfv2";
1745       break;
1746     default:
1747       break;
1748     }
1749
1750   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1751     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1752     // the option if given as we don't have backend support for any targets
1753     // that don't use the altivec abi.
1754     if (StringRef(A->getValue()) != "altivec")
1755       ABIName = A->getValue();
1756
1757   ppc::FloatABI FloatABI =
1758       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1759
1760   if (FloatABI == ppc::FloatABI::Soft) {
1761     // Floating point operations and argument passing are soft.
1762     CmdArgs.push_back("-msoft-float");
1763     CmdArgs.push_back("-mfloat-abi");
1764     CmdArgs.push_back("soft");
1765   } else {
1766     // Floating point operations and argument passing are hard.
1767     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1768     CmdArgs.push_back("-mfloat-abi");
1769     CmdArgs.push_back("hard");
1770   }
1771
1772   if (ABIName) {
1773     CmdArgs.push_back("-target-abi");
1774     CmdArgs.push_back(ABIName);
1775   }
1776 }
1777
1778 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1779                                ArgStringList &CmdArgs) const {
1780   // FIXME: currently defaults to the soft-float ABIs. Will need to be
1781   // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1782   const char *ABIName = nullptr;
1783   const llvm::Triple &Triple = getToolChain().getTriple();
1784   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1785     ABIName = A->getValue();
1786   else if (Triple.getArch() == llvm::Triple::riscv32)
1787     ABIName = "ilp32";
1788   else if (Triple.getArch() == llvm::Triple::riscv64)
1789     ABIName = "lp64";
1790   else
1791     llvm_unreachable("Unexpected triple!");
1792
1793   CmdArgs.push_back("-target-abi");
1794   CmdArgs.push_back(ABIName);
1795 }
1796
1797 void Clang::AddSparcTargetArgs(const ArgList &Args,
1798                                ArgStringList &CmdArgs) const {
1799   sparc::FloatABI FloatABI =
1800       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1801
1802   if (FloatABI == sparc::FloatABI::Soft) {
1803     // Floating point operations and argument passing are soft.
1804     CmdArgs.push_back("-msoft-float");
1805     CmdArgs.push_back("-mfloat-abi");
1806     CmdArgs.push_back("soft");
1807   } else {
1808     // Floating point operations and argument passing are hard.
1809     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1810     CmdArgs.push_back("-mfloat-abi");
1811     CmdArgs.push_back("hard");
1812   }
1813 }
1814
1815 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1816                                  ArgStringList &CmdArgs) const {
1817   if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1818     CmdArgs.push_back("-mbackchain");
1819 }
1820
1821 void Clang::AddX86TargetArgs(const ArgList &Args,
1822                              ArgStringList &CmdArgs) const {
1823   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1824       Args.hasArg(options::OPT_mkernel) ||
1825       Args.hasArg(options::OPT_fapple_kext))
1826     CmdArgs.push_back("-disable-red-zone");
1827
1828   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1829                     options::OPT_mno_tls_direct_seg_refs, true))
1830     CmdArgs.push_back("-mno-tls-direct-seg-refs");
1831
1832   // Default to avoid implicit floating-point for kernel/kext code, but allow
1833   // that to be overridden with -mno-soft-float.
1834   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1835                           Args.hasArg(options::OPT_fapple_kext));
1836   if (Arg *A = Args.getLastArg(
1837           options::OPT_msoft_float, options::OPT_mno_soft_float,
1838           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1839     const Option &O = A->getOption();
1840     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1841                        O.matches(options::OPT_msoft_float));
1842   }
1843   if (NoImplicitFloat)
1844     CmdArgs.push_back("-no-implicit-float");
1845
1846   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1847     StringRef Value = A->getValue();
1848     if (Value == "intel" || Value == "att") {
1849       CmdArgs.push_back("-mllvm");
1850       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1851     } else {
1852       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1853           << A->getOption().getName() << Value;
1854     }
1855   } else if (getToolChain().getDriver().IsCLMode()) {
1856     CmdArgs.push_back("-mllvm");
1857     CmdArgs.push_back("-x86-asm-syntax=intel");
1858   }
1859
1860   // Set flags to support MCU ABI.
1861   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1862     CmdArgs.push_back("-mfloat-abi");
1863     CmdArgs.push_back("soft");
1864     CmdArgs.push_back("-mstack-alignment=4");
1865   }
1866 }
1867
1868 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1869                                  ArgStringList &CmdArgs) const {
1870   CmdArgs.push_back("-mqdsp6-compat");
1871   CmdArgs.push_back("-Wreturn-type");
1872
1873   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1874     CmdArgs.push_back("-mllvm");
1875     CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1876                                          Twine(G.getValue())));
1877   }
1878
1879   if (!Args.hasArg(options::OPT_fno_short_enums))
1880     CmdArgs.push_back("-fshort-enums");
1881   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1882     CmdArgs.push_back("-mllvm");
1883     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1884   }
1885   CmdArgs.push_back("-mllvm");
1886   CmdArgs.push_back("-machine-sink-split=0");
1887 }
1888
1889 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1890                                ArgStringList &CmdArgs) const {
1891   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1892     StringRef CPUName = A->getValue();
1893
1894     CmdArgs.push_back("-target-cpu");
1895     CmdArgs.push_back(Args.MakeArgString(CPUName));
1896   }
1897   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1898     StringRef Value = A->getValue();
1899     // Only support mregparm=4 to support old usage. Report error for all other
1900     // cases.
1901     int Mregparm;
1902     if (Value.getAsInteger(10, Mregparm)) {
1903       if (Mregparm != 4) {
1904         getToolChain().getDriver().Diag(
1905             diag::err_drv_unsupported_option_argument)
1906             << A->getOption().getName() << Value;
1907       }
1908     }
1909   }
1910 }
1911
1912 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1913                                      ArgStringList &CmdArgs) const {
1914   // Default to "hidden" visibility.
1915   if (!Args.hasArg(options::OPT_fvisibility_EQ,
1916                    options::OPT_fvisibility_ms_compat)) {
1917     CmdArgs.push_back("-fvisibility");
1918     CmdArgs.push_back("hidden");
1919   }
1920 }
1921
1922 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1923                                     StringRef Target, const InputInfo &Output,
1924                                     const InputInfo &Input, const ArgList &Args) const {
1925   // If this is a dry run, do not create the compilation database file.
1926   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1927     return;
1928
1929   using llvm::yaml::escape;
1930   const Driver &D = getToolChain().getDriver();
1931
1932   if (!CompilationDatabase) {
1933     std::error_code EC;
1934     auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1935     if (EC) {
1936       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1937                                                        << EC.message();
1938       return;
1939     }
1940     CompilationDatabase = std::move(File);
1941   }
1942   auto &CDB = *CompilationDatabase;
1943   SmallString<128> Buf;
1944   if (llvm::sys::fs::current_path(Buf))
1945     Buf = ".";
1946   CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1947   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1948   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1949   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1950   Buf = "-x";
1951   Buf += types::getTypeName(Input.getType());
1952   CDB << ", \"" << escape(Buf) << "\"";
1953   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1954     Buf = "--sysroot=";
1955     Buf += D.SysRoot;
1956     CDB << ", \"" << escape(Buf) << "\"";
1957   }
1958   CDB << ", \"" << escape(Input.getFilename()) << "\"";
1959   for (auto &A: Args) {
1960     auto &O = A->getOption();
1961     // Skip language selection, which is positional.
1962     if (O.getID() == options::OPT_x)
1963       continue;
1964     // Skip writing dependency output and the compilation database itself.
1965     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1966       continue;
1967     // Skip inputs.
1968     if (O.getKind() == Option::InputClass)
1969       continue;
1970     // All other arguments are quoted and appended.
1971     ArgStringList ASL;
1972     A->render(Args, ASL);
1973     for (auto &it: ASL)
1974       CDB << ", \"" << escape(it) << "\"";
1975   }
1976   Buf = "--target=";
1977   Buf += Target;
1978   CDB << ", \"" << escape(Buf) << "\"]},\n";
1979 }
1980
1981 static void CollectArgsForIntegratedAssembler(Compilation &C,
1982                                               const ArgList &Args,
1983                                               ArgStringList &CmdArgs,
1984                                               const Driver &D) {
1985   if (UseRelaxAll(C, Args))
1986     CmdArgs.push_back("-mrelax-all");
1987
1988   // Only default to -mincremental-linker-compatible if we think we are
1989   // targeting the MSVC linker.
1990   bool DefaultIncrementalLinkerCompatible =
1991       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1992   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1993                    options::OPT_mno_incremental_linker_compatible,
1994                    DefaultIncrementalLinkerCompatible))
1995     CmdArgs.push_back("-mincremental-linker-compatible");
1996
1997   switch (C.getDefaultToolChain().getArch()) {
1998   case llvm::Triple::arm:
1999   case llvm::Triple::armeb:
2000   case llvm::Triple::thumb:
2001   case llvm::Triple::thumbeb:
2002     if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2003       StringRef Value = A->getValue();
2004       if (Value == "always" || Value == "never" || Value == "arm" ||
2005           Value == "thumb") {
2006         CmdArgs.push_back("-mllvm");
2007         CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2008       } else {
2009         D.Diag(diag::err_drv_unsupported_option_argument)
2010             << A->getOption().getName() << Value;
2011       }
2012     }
2013     break;
2014   default:
2015     break;
2016   }
2017
2018   // When passing -I arguments to the assembler we sometimes need to
2019   // unconditionally take the next argument.  For example, when parsing
2020   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2021   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2022   // arg after parsing the '-I' arg.
2023   bool TakeNextArg = false;
2024
2025   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2026   const char *MipsTargetFeature = nullptr;
2027   for (const Arg *A :
2028        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2029     A->claim();
2030
2031     for (StringRef Value : A->getValues()) {
2032       if (TakeNextArg) {
2033         CmdArgs.push_back(Value.data());
2034         TakeNextArg = false;
2035         continue;
2036       }
2037
2038       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2039           Value == "-mbig-obj")
2040         continue; // LLVM handles bigobj automatically
2041
2042       switch (C.getDefaultToolChain().getArch()) {
2043       default:
2044         break;
2045       case llvm::Triple::thumb:
2046       case llvm::Triple::thumbeb:
2047       case llvm::Triple::arm:
2048       case llvm::Triple::armeb:
2049         if (Value == "-mthumb")
2050           // -mthumb has already been processed in ComputeLLVMTriple()
2051           // recognize but skip over here.
2052           continue;
2053         break;
2054       case llvm::Triple::mips:
2055       case llvm::Triple::mipsel:
2056       case llvm::Triple::mips64:
2057       case llvm::Triple::mips64el:
2058         if (Value == "--trap") {
2059           CmdArgs.push_back("-target-feature");
2060           CmdArgs.push_back("+use-tcc-in-div");
2061           continue;
2062         }
2063         if (Value == "--break") {
2064           CmdArgs.push_back("-target-feature");
2065           CmdArgs.push_back("-use-tcc-in-div");
2066           continue;
2067         }
2068         if (Value.startswith("-msoft-float")) {
2069           CmdArgs.push_back("-target-feature");
2070           CmdArgs.push_back("+soft-float");
2071           continue;
2072         }
2073         if (Value.startswith("-mhard-float")) {
2074           CmdArgs.push_back("-target-feature");
2075           CmdArgs.push_back("-soft-float");
2076           continue;
2077         }
2078
2079         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2080                                 .Case("-mips1", "+mips1")
2081                                 .Case("-mips2", "+mips2")
2082                                 .Case("-mips3", "+mips3")
2083                                 .Case("-mips4", "+mips4")
2084                                 .Case("-mips5", "+mips5")
2085                                 .Case("-mips32", "+mips32")
2086                                 .Case("-mips32r2", "+mips32r2")
2087                                 .Case("-mips32r3", "+mips32r3")
2088                                 .Case("-mips32r5", "+mips32r5")
2089                                 .Case("-mips32r6", "+mips32r6")
2090                                 .Case("-mips64", "+mips64")
2091                                 .Case("-mips64r2", "+mips64r2")
2092                                 .Case("-mips64r3", "+mips64r3")
2093                                 .Case("-mips64r5", "+mips64r5")
2094                                 .Case("-mips64r6", "+mips64r6")
2095                                 .Default(nullptr);
2096         if (MipsTargetFeature)
2097           continue;
2098       }
2099
2100       if (Value == "-force_cpusubtype_ALL") {
2101         // Do nothing, this is the default and we don't support anything else.
2102       } else if (Value == "-L") {
2103         CmdArgs.push_back("-msave-temp-labels");
2104       } else if (Value == "--fatal-warnings") {
2105         CmdArgs.push_back("-massembler-fatal-warnings");
2106       } else if (Value == "--noexecstack") {
2107         CmdArgs.push_back("-mnoexecstack");
2108       } else if (Value.startswith("-compress-debug-sections") ||
2109                  Value.startswith("--compress-debug-sections") ||
2110                  Value == "-nocompress-debug-sections" ||
2111                  Value == "--nocompress-debug-sections") {
2112         CmdArgs.push_back(Value.data());
2113       } else if (Value == "-mrelax-relocations=yes" ||
2114                  Value == "--mrelax-relocations=yes") {
2115         UseRelaxRelocations = true;
2116       } else if (Value == "-mrelax-relocations=no" ||
2117                  Value == "--mrelax-relocations=no") {
2118         UseRelaxRelocations = false;
2119       } else if (Value.startswith("-I")) {
2120         CmdArgs.push_back(Value.data());
2121         // We need to consume the next argument if the current arg is a plain
2122         // -I. The next arg will be the include directory.
2123         if (Value == "-I")
2124           TakeNextArg = true;
2125       } else if (Value.startswith("-gdwarf-")) {
2126         // "-gdwarf-N" options are not cc1as options.
2127         unsigned DwarfVersion = DwarfVersionNum(Value);
2128         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2129           CmdArgs.push_back(Value.data());
2130         } else {
2131           RenderDebugEnablingArgs(Args, CmdArgs,
2132                                   codegenoptions::LimitedDebugInfo,
2133                                   DwarfVersion, llvm::DebuggerKind::Default);
2134         }
2135       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2136                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2137         // Do nothing, we'll validate it later.
2138       } else if (Value == "-defsym") {
2139           if (A->getNumValues() != 2) {
2140             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2141             break;
2142           }
2143           const char *S = A->getValue(1);
2144           auto Pair = StringRef(S).split('=');
2145           auto Sym = Pair.first;
2146           auto SVal = Pair.second;
2147
2148           if (Sym.empty() || SVal.empty()) {
2149             D.Diag(diag::err_drv_defsym_invalid_format) << S;
2150             break;
2151           }
2152           int64_t IVal;
2153           if (SVal.getAsInteger(0, IVal)) {
2154             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2155             break;
2156           }
2157           CmdArgs.push_back(Value.data());
2158           TakeNextArg = true;
2159       } else if (Value == "-fdebug-compilation-dir") {
2160         CmdArgs.push_back("-fdebug-compilation-dir");
2161         TakeNextArg = true;
2162       } else {
2163         D.Diag(diag::err_drv_unsupported_option_argument)
2164             << A->getOption().getName() << Value;
2165       }
2166     }
2167   }
2168   if (UseRelaxRelocations)
2169     CmdArgs.push_back("--mrelax-relocations");
2170   if (MipsTargetFeature != nullptr) {
2171     CmdArgs.push_back("-target-feature");
2172     CmdArgs.push_back(MipsTargetFeature);
2173   }
2174
2175   // forward -fembed-bitcode to assmebler
2176   if (C.getDriver().embedBitcodeEnabled() ||
2177       C.getDriver().embedBitcodeMarkerOnly())
2178     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2179 }
2180
2181 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2182                                        bool OFastEnabled, const ArgList &Args,
2183                                        ArgStringList &CmdArgs) {
2184   // Handle various floating point optimization flags, mapping them to the
2185   // appropriate LLVM code generation flags. This is complicated by several
2186   // "umbrella" flags, so we do this by stepping through the flags incrementally
2187   // adjusting what we think is enabled/disabled, then at the end setting the
2188   // LLVM flags based on the final state.
2189   bool HonorINFs = true;
2190   bool HonorNaNs = true;
2191   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2192   bool MathErrno = TC.IsMathErrnoDefault();
2193   bool AssociativeMath = false;
2194   bool ReciprocalMath = false;
2195   bool SignedZeros = true;
2196   bool TrappingMath = true;
2197   StringRef DenormalFPMath = "";
2198   StringRef FPContract = "";
2199
2200   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2201     CmdArgs.push_back("-mlimit-float-precision");
2202     CmdArgs.push_back(A->getValue());
2203   }
2204
2205   for (const Arg *A : Args) {
2206     switch (A->getOption().getID()) {
2207     // If this isn't an FP option skip the claim below
2208     default: continue;
2209
2210     // Options controlling individual features
2211     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2212     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2213     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2214     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2215     case options::OPT_fmath_errno:          MathErrno = true;         break;
2216     case options::OPT_fno_math_errno:       MathErrno = false;        break;
2217     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2218     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2219     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2220     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2221     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2222     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2223     case options::OPT_ftrapping_math:       TrappingMath = true;      break;
2224     case options::OPT_fno_trapping_math:    TrappingMath = false;     break;
2225
2226     case options::OPT_fdenormal_fp_math_EQ:
2227       DenormalFPMath = A->getValue();
2228       break;
2229
2230     // Validate and pass through -fp-contract option.
2231     case options::OPT_ffp_contract: {
2232       StringRef Val = A->getValue();
2233       if (Val == "fast" || Val == "on" || Val == "off")
2234         FPContract = Val;
2235       else
2236         D.Diag(diag::err_drv_unsupported_option_argument)
2237             << A->getOption().getName() << Val;
2238       break;
2239     }
2240
2241     case options::OPT_ffinite_math_only:
2242       HonorINFs = false;
2243       HonorNaNs = false;
2244       break;
2245     case options::OPT_fno_finite_math_only:
2246       HonorINFs = true;
2247       HonorNaNs = true;
2248       break;
2249
2250     case options::OPT_funsafe_math_optimizations:
2251       AssociativeMath = true;
2252       ReciprocalMath = true;
2253       SignedZeros = false;
2254       TrappingMath = false;
2255       break;
2256     case options::OPT_fno_unsafe_math_optimizations:
2257       AssociativeMath = false;
2258       ReciprocalMath = false;
2259       SignedZeros = true;
2260       TrappingMath = true;
2261       // -fno_unsafe_math_optimizations restores default denormal handling
2262       DenormalFPMath = "";
2263       break;
2264
2265     case options::OPT_Ofast:
2266       // If -Ofast is the optimization level, then -ffast-math should be enabled
2267       if (!OFastEnabled)
2268         continue;
2269       LLVM_FALLTHROUGH;
2270     case options::OPT_ffast_math:
2271       HonorINFs = false;
2272       HonorNaNs = false;
2273       MathErrno = false;
2274       AssociativeMath = true;
2275       ReciprocalMath = true;
2276       SignedZeros = false;
2277       TrappingMath = false;
2278       // If fast-math is set then set the fp-contract mode to fast.
2279       FPContract = "fast";
2280       break;
2281     case options::OPT_fno_fast_math:
2282       HonorINFs = true;
2283       HonorNaNs = true;
2284       // Turning on -ffast-math (with either flag) removes the need for
2285       // MathErrno. However, turning *off* -ffast-math merely restores the
2286       // toolchain default (which may be false).
2287       MathErrno = TC.IsMathErrnoDefault();
2288       AssociativeMath = false;
2289       ReciprocalMath = false;
2290       SignedZeros = true;
2291       TrappingMath = true;
2292       // -fno_fast_math restores default denormal and fpcontract handling
2293       DenormalFPMath = "";
2294       FPContract = "";
2295       break;
2296     }
2297
2298     // If we handled this option claim it
2299     A->claim();
2300   }
2301
2302   if (!HonorINFs)
2303     CmdArgs.push_back("-menable-no-infs");
2304
2305   if (!HonorNaNs)
2306     CmdArgs.push_back("-menable-no-nans");
2307
2308   if (MathErrno)
2309     CmdArgs.push_back("-fmath-errno");
2310
2311   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2312       !TrappingMath)
2313     CmdArgs.push_back("-menable-unsafe-fp-math");
2314
2315   if (!SignedZeros)
2316     CmdArgs.push_back("-fno-signed-zeros");
2317
2318   if (AssociativeMath && !SignedZeros && !TrappingMath)
2319     CmdArgs.push_back("-mreassociate");
2320
2321   if (ReciprocalMath)
2322     CmdArgs.push_back("-freciprocal-math");
2323
2324   if (!TrappingMath)
2325     CmdArgs.push_back("-fno-trapping-math");
2326
2327   if (!DenormalFPMath.empty())
2328     CmdArgs.push_back(
2329         Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2330
2331   if (!FPContract.empty())
2332     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2333
2334   ParseMRecip(D, Args, CmdArgs);
2335
2336   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2337   // individual features enabled by -ffast-math instead of the option itself as
2338   // that's consistent with gcc's behaviour.
2339   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2340       ReciprocalMath && !SignedZeros && !TrappingMath)
2341     CmdArgs.push_back("-ffast-math");
2342
2343   // Handle __FINITE_MATH_ONLY__ similarly.
2344   if (!HonorINFs && !HonorNaNs)
2345     CmdArgs.push_back("-ffinite-math-only");
2346
2347   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2348     CmdArgs.push_back("-mfpmath");
2349     CmdArgs.push_back(A->getValue());
2350   }
2351
2352   // Disable a codegen optimization for floating-point casts.
2353   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2354                    options::OPT_fstrict_float_cast_overflow, false))
2355     CmdArgs.push_back("-fno-strict-float-cast-overflow");
2356 }
2357
2358 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2359                                   const llvm::Triple &Triple,
2360                                   const InputInfo &Input) {
2361   // Enable region store model by default.
2362   CmdArgs.push_back("-analyzer-store=region");
2363
2364   // Treat blocks as analysis entry points.
2365   CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2366
2367   // Add default argument set.
2368   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2369     CmdArgs.push_back("-analyzer-checker=core");
2370     CmdArgs.push_back("-analyzer-checker=apiModeling");
2371
2372     if (!Triple.isWindowsMSVCEnvironment()) {
2373       CmdArgs.push_back("-analyzer-checker=unix");
2374     } else {
2375       // Enable "unix" checkers that also work on Windows.
2376       CmdArgs.push_back("-analyzer-checker=unix.API");
2377       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2378       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2379       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2380       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2381       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2382     }
2383
2384     // Disable some unix checkers for PS4.
2385     if (Triple.isPS4CPU()) {
2386       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2387       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2388     }
2389
2390     if (Triple.isOSDarwin())
2391       CmdArgs.push_back("-analyzer-checker=osx");
2392
2393     CmdArgs.push_back("-analyzer-checker=deadcode");
2394
2395     if (types::isCXX(Input.getType()))
2396       CmdArgs.push_back("-analyzer-checker=cplusplus");
2397
2398     if (!Triple.isPS4CPU()) {
2399       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2400       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2401       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2402       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2403       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2404       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2405     }
2406
2407     // Default nullability checks.
2408     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2409     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2410   }
2411
2412   // Set the output format. The default is plist, for (lame) historical reasons.
2413   CmdArgs.push_back("-analyzer-output");
2414   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2415     CmdArgs.push_back(A->getValue());
2416   else
2417     CmdArgs.push_back("plist");
2418
2419   // Disable the presentation of standard compiler warnings when using
2420   // --analyze.  We only want to show static analyzer diagnostics or frontend
2421   // errors.
2422   CmdArgs.push_back("-w");
2423
2424   // Add -Xanalyzer arguments when running as analyzer.
2425   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2426 }
2427
2428 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2429                              ArgStringList &CmdArgs, bool KernelOrKext) {
2430   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2431
2432   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2433   // doesn't even have a stack!
2434   if (EffectiveTriple.isNVPTX())
2435     return;
2436
2437   // -stack-protector=0 is default.
2438   unsigned StackProtectorLevel = 0;
2439   unsigned DefaultStackProtectorLevel =
2440       TC.GetDefaultStackProtectorLevel(KernelOrKext);
2441
2442   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2443                                options::OPT_fstack_protector_all,
2444                                options::OPT_fstack_protector_strong,
2445                                options::OPT_fstack_protector)) {
2446     if (A->getOption().matches(options::OPT_fstack_protector))
2447       StackProtectorLevel =
2448           std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2449     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2450       StackProtectorLevel = LangOptions::SSPStrong;
2451     else if (A->getOption().matches(options::OPT_fstack_protector_all))
2452       StackProtectorLevel = LangOptions::SSPReq;
2453   } else {
2454     StackProtectorLevel = DefaultStackProtectorLevel;
2455   }
2456
2457   if (StackProtectorLevel) {
2458     CmdArgs.push_back("-stack-protector");
2459     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2460   }
2461
2462   // --param ssp-buffer-size=
2463   for (const Arg *A : Args.filtered(options::OPT__param)) {
2464     StringRef Str(A->getValue());
2465     if (Str.startswith("ssp-buffer-size=")) {
2466       if (StackProtectorLevel) {
2467         CmdArgs.push_back("-stack-protector-buffer-size");
2468         // FIXME: Verify the argument is a valid integer.
2469         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2470       }
2471       A->claim();
2472     }
2473   }
2474 }
2475
2476 static void RenderTrivialAutoVarInitOptions(const Driver &D,
2477                                             const ToolChain &TC,
2478                                             const ArgList &Args,
2479                                             ArgStringList &CmdArgs) {
2480   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2481   StringRef TrivialAutoVarInit = "";
2482
2483   for (const Arg *A : Args) {
2484     switch (A->getOption().getID()) {
2485     default:
2486       continue;
2487     case options::OPT_ftrivial_auto_var_init: {
2488       A->claim();
2489       StringRef Val = A->getValue();
2490       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2491         TrivialAutoVarInit = Val;
2492       else
2493         D.Diag(diag::err_drv_unsupported_option_argument)
2494             << A->getOption().getName() << Val;
2495       break;
2496     }
2497     }
2498   }
2499
2500   if (TrivialAutoVarInit.empty())
2501     switch (DefaultTrivialAutoVarInit) {
2502     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2503       break;
2504     case LangOptions::TrivialAutoVarInitKind::Pattern:
2505       TrivialAutoVarInit = "pattern";
2506       break;
2507     case LangOptions::TrivialAutoVarInitKind::Zero:
2508       TrivialAutoVarInit = "zero";
2509       break;
2510     }
2511
2512   if (!TrivialAutoVarInit.empty()) {
2513     if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2514       D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2515     CmdArgs.push_back(
2516         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2517   }
2518 }
2519
2520 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2521   const unsigned ForwardedArguments[] = {
2522       options::OPT_cl_opt_disable,
2523       options::OPT_cl_strict_aliasing,
2524       options::OPT_cl_single_precision_constant,
2525       options::OPT_cl_finite_math_only,
2526       options::OPT_cl_kernel_arg_info,
2527       options::OPT_cl_unsafe_math_optimizations,
2528       options::OPT_cl_fast_relaxed_math,
2529       options::OPT_cl_mad_enable,
2530       options::OPT_cl_no_signed_zeros,
2531       options::OPT_cl_denorms_are_zero,
2532       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2533       options::OPT_cl_uniform_work_group_size
2534   };
2535
2536   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2537     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2538     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2539   }
2540
2541   for (const auto &Arg : ForwardedArguments)
2542     if (const auto *A = Args.getLastArg(Arg))
2543       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2544 }
2545
2546 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2547                                         ArgStringList &CmdArgs) {
2548   bool ARCMTEnabled = false;
2549   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2550     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2551                                        options::OPT_ccc_arcmt_modify,
2552                                        options::OPT_ccc_arcmt_migrate)) {
2553       ARCMTEnabled = true;
2554       switch (A->getOption().getID()) {
2555       default: llvm_unreachable("missed a case");
2556       case options::OPT_ccc_arcmt_check:
2557         CmdArgs.push_back("-arcmt-check");
2558         break;
2559       case options::OPT_ccc_arcmt_modify:
2560         CmdArgs.push_back("-arcmt-modify");
2561         break;
2562       case options::OPT_ccc_arcmt_migrate:
2563         CmdArgs.push_back("-arcmt-migrate");
2564         CmdArgs.push_back("-mt-migrate-directory");
2565         CmdArgs.push_back(A->getValue());
2566
2567         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2568         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2569         break;
2570       }
2571     }
2572   } else {
2573     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2574     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2575     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2576   }
2577
2578   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2579     if (ARCMTEnabled)
2580       D.Diag(diag::err_drv_argument_not_allowed_with)
2581           << A->getAsString(Args) << "-ccc-arcmt-migrate";
2582
2583     CmdArgs.push_back("-mt-migrate-directory");
2584     CmdArgs.push_back(A->getValue());
2585
2586     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2587                      options::OPT_objcmt_migrate_subscripting,
2588                      options::OPT_objcmt_migrate_property)) {
2589       // None specified, means enable them all.
2590       CmdArgs.push_back("-objcmt-migrate-literals");
2591       CmdArgs.push_back("-objcmt-migrate-subscripting");
2592       CmdArgs.push_back("-objcmt-migrate-property");
2593     } else {
2594       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2595       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2596       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2597     }
2598   } else {
2599     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2600     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2601     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2602     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2603     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2604     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2605     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2606     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2607     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2608     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2609     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2610     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2611     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2612     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2613     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2614     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2615   }
2616 }
2617
2618 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2619                                  const ArgList &Args, ArgStringList &CmdArgs) {
2620   // -fbuiltin is default unless -mkernel is used.
2621   bool UseBuiltins =
2622       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2623                    !Args.hasArg(options::OPT_mkernel));
2624   if (!UseBuiltins)
2625     CmdArgs.push_back("-fno-builtin");
2626
2627   // -ffreestanding implies -fno-builtin.
2628   if (Args.hasArg(options::OPT_ffreestanding))
2629     UseBuiltins = false;
2630
2631   // Process the -fno-builtin-* options.
2632   for (const auto &Arg : Args) {
2633     const Option &O = Arg->getOption();
2634     if (!O.matches(options::OPT_fno_builtin_))
2635       continue;
2636
2637     Arg->claim();
2638
2639     // If -fno-builtin is specified, then there's no need to pass the option to
2640     // the frontend.
2641     if (!UseBuiltins)
2642       continue;
2643
2644     StringRef FuncName = Arg->getValue();
2645     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2646   }
2647
2648   // le32-specific flags:
2649   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
2650   //                     by default.
2651   if (TC.getArch() == llvm::Triple::le32)
2652     CmdArgs.push_back("-fno-math-builtin");
2653 }
2654
2655 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2656   llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2657   llvm::sys::path::append(Result, "org.llvm.clang.");
2658   appendUserToPath(Result);
2659   llvm::sys::path::append(Result, "ModuleCache");
2660 }
2661
2662 static void RenderModulesOptions(Compilation &C, const Driver &D,
2663                                  const ArgList &Args, const InputInfo &Input,
2664                                  const InputInfo &Output,
2665                                  ArgStringList &CmdArgs, bool &HaveModules) {
2666   // -fmodules enables the use of precompiled modules (off by default).
2667   // Users can pass -fno-cxx-modules to turn off modules support for
2668   // C++/Objective-C++ programs.
2669   bool HaveClangModules = false;
2670   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2671     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2672                                      options::OPT_fno_cxx_modules, true);
2673     if (AllowedInCXX || !types::isCXX(Input.getType())) {
2674       CmdArgs.push_back("-fmodules");
2675       HaveClangModules = true;
2676     }
2677   }
2678
2679   HaveModules = HaveClangModules;
2680   if (Args.hasArg(options::OPT_fmodules_ts)) {
2681     CmdArgs.push_back("-fmodules-ts");
2682     HaveModules = true;
2683   }
2684
2685   // -fmodule-maps enables implicit reading of module map files. By default,
2686   // this is enabled if we are using Clang's flavor of precompiled modules.
2687   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2688                    options::OPT_fno_implicit_module_maps, HaveClangModules))
2689     CmdArgs.push_back("-fimplicit-module-maps");
2690
2691   // -fmodules-decluse checks that modules used are declared so (off by default)
2692   if (Args.hasFlag(options::OPT_fmodules_decluse,
2693                    options::OPT_fno_modules_decluse, false))
2694     CmdArgs.push_back("-fmodules-decluse");
2695
2696   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2697   // all #included headers are part of modules.
2698   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2699                    options::OPT_fno_modules_strict_decluse, false))
2700     CmdArgs.push_back("-fmodules-strict-decluse");
2701
2702   // -fno-implicit-modules turns off implicitly compiling modules on demand.
2703   bool ImplicitModules = false;
2704   if (!Args.hasFlag(options::OPT_fimplicit_modules,
2705                     options::OPT_fno_implicit_modules, HaveClangModules)) {
2706     if (HaveModules)
2707       CmdArgs.push_back("-fno-implicit-modules");
2708   } else if (HaveModules) {
2709     ImplicitModules = true;
2710     // -fmodule-cache-path specifies where our implicitly-built module files
2711     // should be written.
2712     SmallString<128> Path;
2713     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2714       Path = A->getValue();
2715
2716     if (C.isForDiagnostics()) {
2717       // When generating crash reports, we want to emit the modules along with
2718       // the reproduction sources, so we ignore any provided module path.
2719       Path = Output.getFilename();
2720       llvm::sys::path::replace_extension(Path, ".cache");
2721       llvm::sys::path::append(Path, "modules");
2722     } else if (Path.empty()) {
2723       // No module path was provided: use the default.
2724       Driver::getDefaultModuleCachePath(Path);
2725     }
2726
2727     const char Arg[] = "-fmodules-cache-path=";
2728     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2729     CmdArgs.push_back(Args.MakeArgString(Path));
2730   }
2731
2732   if (HaveModules) {
2733     // -fprebuilt-module-path specifies where to load the prebuilt module files.
2734     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2735       CmdArgs.push_back(Args.MakeArgString(
2736           std::string("-fprebuilt-module-path=") + A->getValue()));
2737       A->claim();
2738     }
2739   }
2740
2741   // -fmodule-name specifies the module that is currently being built (or
2742   // used for header checking by -fmodule-maps).
2743   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2744
2745   // -fmodule-map-file can be used to specify files containing module
2746   // definitions.
2747   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2748
2749   // -fbuiltin-module-map can be used to load the clang
2750   // builtin headers modulemap file.
2751   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2752     SmallString<128> BuiltinModuleMap(D.ResourceDir);
2753     llvm::sys::path::append(BuiltinModuleMap, "include");
2754     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2755     if (llvm::sys::fs::exists(BuiltinModuleMap))
2756       CmdArgs.push_back(
2757           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2758   }
2759
2760   // The -fmodule-file=<name>=<file> form specifies the mapping of module
2761   // names to precompiled module files (the module is loaded only if used).
2762   // The -fmodule-file=<file> form can be used to unconditionally load
2763   // precompiled module files (whether used or not).
2764   if (HaveModules)
2765     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2766   else
2767     Args.ClaimAllArgs(options::OPT_fmodule_file);
2768
2769   // When building modules and generating crashdumps, we need to dump a module
2770   // dependency VFS alongside the output.
2771   if (HaveClangModules && C.isForDiagnostics()) {
2772     SmallString<128> VFSDir(Output.getFilename());
2773     llvm::sys::path::replace_extension(VFSDir, ".cache");
2774     // Add the cache directory as a temp so the crash diagnostics pick it up.
2775     C.addTempFile(Args.MakeArgString(VFSDir));
2776
2777     llvm::sys::path::append(VFSDir, "vfs");
2778     CmdArgs.push_back("-module-dependency-dir");
2779     CmdArgs.push_back(Args.MakeArgString(VFSDir));
2780   }
2781
2782   if (HaveClangModules)
2783     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2784
2785   // Pass through all -fmodules-ignore-macro arguments.
2786   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2787   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2788   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2789
2790   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2791
2792   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2793     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2794       D.Diag(diag::err_drv_argument_not_allowed_with)
2795           << A->getAsString(Args) << "-fbuild-session-timestamp";
2796
2797     llvm::sys::fs::file_status Status;
2798     if (llvm::sys::fs::status(A->getValue(), Status))
2799       D.Diag(diag::err_drv_no_such_file) << A->getValue();
2800     CmdArgs.push_back(
2801         Args.MakeArgString("-fbuild-session-timestamp=" +
2802                            Twine((uint64_t)Status.getLastModificationTime()
2803                                      .time_since_epoch()
2804                                      .count())));
2805   }
2806
2807   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2808     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2809                          options::OPT_fbuild_session_file))
2810       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2811
2812     Args.AddLastArg(CmdArgs,
2813                     options::OPT_fmodules_validate_once_per_build_session);
2814   }
2815
2816   if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2817                    options::OPT_fno_modules_validate_system_headers,
2818                    ImplicitModules))
2819     CmdArgs.push_back("-fmodules-validate-system-headers");
2820
2821   Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2822 }
2823
2824 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2825                                    ArgStringList &CmdArgs) {
2826   // -fsigned-char is default.
2827   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2828                                      options::OPT_fno_signed_char,
2829                                      options::OPT_funsigned_char,
2830                                      options::OPT_fno_unsigned_char)) {
2831     if (A->getOption().matches(options::OPT_funsigned_char) ||
2832         A->getOption().matches(options::OPT_fno_signed_char)) {
2833       CmdArgs.push_back("-fno-signed-char");
2834     }
2835   } else if (!isSignedCharDefault(T)) {
2836     CmdArgs.push_back("-fno-signed-char");
2837   }
2838
2839   // The default depends on the language standard.
2840   if (const Arg *A =
2841           Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2842     A->render(Args, CmdArgs);
2843
2844   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2845                                      options::OPT_fno_short_wchar)) {
2846     if (A->getOption().matches(options::OPT_fshort_wchar)) {
2847       CmdArgs.push_back("-fwchar-type=short");
2848       CmdArgs.push_back("-fno-signed-wchar");
2849     } else {
2850       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2851       CmdArgs.push_back("-fwchar-type=int");
2852       if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2853                      T.isOSOpenBSD()))
2854         CmdArgs.push_back("-fno-signed-wchar");
2855       else
2856         CmdArgs.push_back("-fsigned-wchar");
2857     }
2858   }
2859 }
2860
2861 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2862                               const llvm::Triple &T, const ArgList &Args,
2863                               ObjCRuntime &Runtime, bool InferCovariantReturns,
2864                               const InputInfo &Input, ArgStringList &CmdArgs) {
2865   const llvm::Triple::ArchType Arch = TC.getArch();
2866
2867   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2868   // is the default. Except for deployment target of 10.5, next runtime is
2869   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2870   if (Runtime.isNonFragile()) {
2871     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2872                       options::OPT_fno_objc_legacy_dispatch,
2873                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2874       if (TC.UseObjCMixedDispatch())
2875         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2876       else
2877         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2878     }
2879   }
2880
2881   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2882   // to do Array/Dictionary subscripting by default.
2883   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2884       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2885     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2886
2887   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2888   // NOTE: This logic is duplicated in ToolChains.cpp.
2889   if (isObjCAutoRefCount(Args)) {
2890     TC.CheckObjCARC();
2891
2892     CmdArgs.push_back("-fobjc-arc");
2893
2894     // FIXME: It seems like this entire block, and several around it should be
2895     // wrapped in isObjC, but for now we just use it here as this is where it
2896     // was being used previously.
2897     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2898       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2899         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2900       else
2901         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2902     }
2903
2904     // Allow the user to enable full exceptions code emission.
2905     // We default off for Objective-C, on for Objective-C++.
2906     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2907                      options::OPT_fno_objc_arc_exceptions,
2908                      /*default=*/types::isCXX(Input.getType())))
2909       CmdArgs.push_back("-fobjc-arc-exceptions");
2910   }
2911
2912   // Silence warning for full exception code emission options when explicitly
2913   // set to use no ARC.
2914   if (Args.hasArg(options::OPT_fno_objc_arc)) {
2915     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2916     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2917   }
2918
2919   // Allow the user to control whether messages can be converted to runtime
2920   // functions.
2921   if (types::isObjC(Input.getType())) {
2922     auto *Arg = Args.getLastArg(
2923         options::OPT_fobjc_convert_messages_to_runtime_calls,
2924         options::OPT_fno_objc_convert_messages_to_runtime_calls);
2925     if (Arg &&
2926         Arg->getOption().matches(
2927             options::OPT_fno_objc_convert_messages_to_runtime_calls))
2928       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2929   }
2930
2931   // -fobjc-infer-related-result-type is the default, except in the Objective-C
2932   // rewriter.
2933   if (InferCovariantReturns)
2934     CmdArgs.push_back("-fno-objc-infer-related-result-type");
2935
2936   // Pass down -fobjc-weak or -fno-objc-weak if present.
2937   if (types::isObjC(Input.getType())) {
2938     auto WeakArg =
2939         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2940     if (!WeakArg) {
2941       // nothing to do
2942     } else if (!Runtime.allowsWeak()) {
2943       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2944         D.Diag(diag::err_objc_weak_unsupported);
2945     } else {
2946       WeakArg->render(Args, CmdArgs);
2947     }
2948   }
2949 }
2950
2951 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2952                                      ArgStringList &CmdArgs) {
2953   bool CaretDefault = true;
2954   bool ColumnDefault = true;
2955
2956   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2957                                      options::OPT__SLASH_diagnostics_column,
2958                                      options::OPT__SLASH_diagnostics_caret)) {
2959     switch (A->getOption().getID()) {
2960     case options::OPT__SLASH_diagnostics_caret:
2961       CaretDefault = true;
2962       ColumnDefault = true;
2963       break;
2964     case options::OPT__SLASH_diagnostics_column:
2965       CaretDefault = false;
2966       ColumnDefault = true;
2967       break;
2968     case options::OPT__SLASH_diagnostics_classic:
2969       CaretDefault = false;
2970       ColumnDefault = false;
2971       break;
2972     }
2973   }
2974
2975   // -fcaret-diagnostics is default.
2976   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2977                     options::OPT_fno_caret_diagnostics, CaretDefault))
2978     CmdArgs.push_back("-fno-caret-diagnostics");
2979
2980   // -fdiagnostics-fixit-info is default, only pass non-default.
2981   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2982                     options::OPT_fno_diagnostics_fixit_info))
2983     CmdArgs.push_back("-fno-diagnostics-fixit-info");
2984
2985   // Enable -fdiagnostics-show-option by default.
2986   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2987                    options::OPT_fno_diagnostics_show_option))
2988     CmdArgs.push_back("-fdiagnostics-show-option");
2989
2990   if (const Arg *A =
2991           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2992     CmdArgs.push_back("-fdiagnostics-show-category");
2993     CmdArgs.push_back(A->getValue());
2994   }
2995
2996   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2997                    options::OPT_fno_diagnostics_show_hotness, false))
2998     CmdArgs.push_back("-fdiagnostics-show-hotness");
2999
3000   if (const Arg *A =
3001           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3002     std::string Opt =
3003         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3004     CmdArgs.push_back(Args.MakeArgString(Opt));
3005   }
3006
3007   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3008     CmdArgs.push_back("-fdiagnostics-format");
3009     CmdArgs.push_back(A->getValue());
3010   }
3011
3012   if (const Arg *A = Args.getLastArg(
3013           options::OPT_fdiagnostics_show_note_include_stack,
3014           options::OPT_fno_diagnostics_show_note_include_stack)) {
3015     const Option &O = A->getOption();
3016     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3017       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3018     else
3019       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3020   }
3021
3022   // Color diagnostics are parsed by the driver directly from argv and later
3023   // re-parsed to construct this job; claim any possible color diagnostic here
3024   // to avoid warn_drv_unused_argument and diagnose bad
3025   // OPT_fdiagnostics_color_EQ values.
3026   for (const Arg *A : Args) {
3027     const Option &O = A->getOption();
3028     if (!O.matches(options::OPT_fcolor_diagnostics) &&
3029         !O.matches(options::OPT_fdiagnostics_color) &&
3030         !O.matches(options::OPT_fno_color_diagnostics) &&
3031         !O.matches(options::OPT_fno_diagnostics_color) &&
3032         !O.matches(options::OPT_fdiagnostics_color_EQ))
3033       continue;
3034
3035     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3036       StringRef Value(A->getValue());
3037       if (Value != "always" && Value != "never" && Value != "auto")
3038         D.Diag(diag::err_drv_clang_unsupported)
3039             << ("-fdiagnostics-color=" + Value).str();
3040     }
3041     A->claim();
3042   }
3043
3044   if (D.getDiags().getDiagnosticOptions().ShowColors)
3045     CmdArgs.push_back("-fcolor-diagnostics");
3046
3047   if (Args.hasArg(options::OPT_fansi_escape_codes))
3048     CmdArgs.push_back("-fansi-escape-codes");
3049
3050   if (!Args.hasFlag(options::OPT_fshow_source_location,
3051                     options::OPT_fno_show_source_location))
3052     CmdArgs.push_back("-fno-show-source-location");
3053
3054   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3055     CmdArgs.push_back("-fdiagnostics-absolute-paths");
3056
3057   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3058                     ColumnDefault))
3059     CmdArgs.push_back("-fno-show-column");
3060
3061   if (!Args.hasFlag(options::OPT_fspell_checking,
3062                     options::OPT_fno_spell_checking))
3063     CmdArgs.push_back("-fno-spell-checking");
3064 }
3065
3066 enum class DwarfFissionKind { None, Split, Single };
3067
3068 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3069                                             const ArgList &Args, Arg *&Arg) {
3070   Arg =
3071       Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3072   if (!Arg)
3073     return DwarfFissionKind::None;
3074
3075   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3076     return DwarfFissionKind::Split;
3077
3078   StringRef Value = Arg->getValue();
3079   if (Value == "split")
3080     return DwarfFissionKind::Split;
3081   if (Value == "single")
3082     return DwarfFissionKind::Single;
3083
3084   D.Diag(diag::err_drv_unsupported_option_argument)
3085       << Arg->getOption().getName() << Arg->getValue();
3086   return DwarfFissionKind::None;
3087 }
3088
3089 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3090                                const llvm::Triple &T, const ArgList &Args,
3091                                bool EmitCodeView, bool IsWindowsMSVC,
3092                                ArgStringList &CmdArgs,
3093                                codegenoptions::DebugInfoKind &DebugInfoKind,
3094                                DwarfFissionKind &DwarfFission) {
3095   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3096                    options::OPT_fno_debug_info_for_profiling, false) &&
3097       checkDebugInfoOption(
3098           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3099     CmdArgs.push_back("-fdebug-info-for-profiling");
3100
3101   // The 'g' groups options involve a somewhat intricate sequence of decisions
3102   // about what to pass from the driver to the frontend, but by the time they
3103   // reach cc1 they've been factored into three well-defined orthogonal choices:
3104   //  * what level of debug info to generate
3105   //  * what dwarf version to write
3106   //  * what debugger tuning to use
3107   // This avoids having to monkey around further in cc1 other than to disable
3108   // codeview if not running in a Windows environment. Perhaps even that
3109   // decision should be made in the driver as well though.
3110   unsigned DWARFVersion = 0;
3111   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3112
3113   bool SplitDWARFInlining =
3114       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3115                    options::OPT_fno_split_dwarf_inlining, true);
3116
3117   Args.ClaimAllArgs(options::OPT_g_Group);
3118
3119   Arg* SplitDWARFArg;
3120   DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3121
3122   if (DwarfFission != DwarfFissionKind::None &&
3123       !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3124     DwarfFission = DwarfFissionKind::None;
3125     SplitDWARFInlining = false;
3126   }
3127
3128   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3129     if (checkDebugInfoOption(A, Args, D, TC)) {
3130       // If the last option explicitly specified a debug-info level, use it.
3131       if (A->getOption().matches(options::OPT_gN_Group)) {
3132         DebugInfoKind = DebugLevelToInfoKind(*A);
3133         // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
3134         // But -gsplit-dwarf is not a g_group option, hence we have to check the
3135         // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
3136         // This gets a bit more complicated if you've disabled inline info in
3137         // the skeleton CUs (SplitDWARFInlining) - then there's value in
3138         // composing split-dwarf and line-tables-only, so let those compose
3139         // naturally in that case. And if you just turned off debug info,
3140         // (-gsplit-dwarf -g0) - do that.
3141         if (DwarfFission != DwarfFissionKind::None) {
3142           if (A->getIndex() > SplitDWARFArg->getIndex()) {
3143             if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3144                 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3145                 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3146                  SplitDWARFInlining))
3147               DwarfFission = DwarfFissionKind::None;
3148           } else if (SplitDWARFInlining)
3149             DebugInfoKind = codegenoptions::NoDebugInfo;
3150         }
3151       } else {
3152         // For any other 'g' option, use Limited.
3153         DebugInfoKind = codegenoptions::LimitedDebugInfo;
3154       }
3155     } else {
3156       DebugInfoKind = codegenoptions::LimitedDebugInfo;
3157     }
3158   }
3159
3160   // If a debugger tuning argument appeared, remember it.
3161   if (const Arg *A =
3162           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3163     if (checkDebugInfoOption(A, Args, D, TC)) {
3164       if (A->getOption().matches(options::OPT_glldb))
3165         DebuggerTuning = llvm::DebuggerKind::LLDB;
3166       else if (A->getOption().matches(options::OPT_gsce))
3167         DebuggerTuning = llvm::DebuggerKind::SCE;
3168       else
3169         DebuggerTuning = llvm::DebuggerKind::GDB;
3170     }
3171   }
3172
3173   // If a -gdwarf argument appeared, remember it.
3174   if (const Arg *A =
3175           Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3176                           options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3177     if (checkDebugInfoOption(A, Args, D, TC))
3178       DWARFVersion = DwarfVersionNum(A->getSpelling());
3179
3180   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3181     if (checkDebugInfoOption(A, Args, D, TC))
3182       EmitCodeView = true;
3183   }
3184
3185   // If the user asked for debug info but did not explicitly specify -gcodeview
3186   // or -gdwarf, ask the toolchain for the default format.
3187   if (!EmitCodeView && DWARFVersion == 0 &&
3188       DebugInfoKind != codegenoptions::NoDebugInfo) {
3189     switch (TC.getDefaultDebugFormat()) {
3190     case codegenoptions::DIF_CodeView:
3191       EmitCodeView = true;
3192       break;
3193     case codegenoptions::DIF_DWARF:
3194       DWARFVersion = TC.GetDefaultDwarfVersion();
3195       break;
3196     }
3197   }
3198
3199   // -gline-directives-only supported only for the DWARF debug info.
3200   if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3201     DebugInfoKind = codegenoptions::NoDebugInfo;
3202
3203   // We ignore flag -gstrict-dwarf for now.
3204   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3205   Args.ClaimAllArgs(options::OPT_g_flags_Group);
3206
3207   // Column info is included by default for everything except SCE and
3208   // CodeView. Clang doesn't track end columns, just starting columns, which,
3209   // in theory, is fine for CodeView (and PDB).  In practice, however, the
3210   // Microsoft debuggers don't handle missing end columns well, so it's better
3211   // not to include any column info.
3212   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3213     (void)checkDebugInfoOption(A, Args, D, TC);
3214   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3215                    /*Default=*/!EmitCodeView &&
3216                        DebuggerTuning != llvm::DebuggerKind::SCE))
3217     CmdArgs.push_back("-dwarf-column-info");
3218
3219   // FIXME: Move backend command line options to the module.
3220   // If -gline-tables-only or -gline-directives-only is the last option it wins.
3221   if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3222     if (checkDebugInfoOption(A, Args, D, TC)) {
3223       if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3224           DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3225         DebugInfoKind = codegenoptions::LimitedDebugInfo;
3226         CmdArgs.push_back("-dwarf-ext-refs");
3227         CmdArgs.push_back("-fmodule-format=obj");
3228       }
3229     }
3230
3231   // -gsplit-dwarf should turn on -g and enable the backend dwarf
3232   // splitting and extraction.
3233   // FIXME: Currently only works on Linux and Fuchsia.
3234   if (T.isOSLinux() || T.isOSFuchsia()) {
3235     if (!SplitDWARFInlining)
3236       CmdArgs.push_back("-fno-split-dwarf-inlining");
3237
3238     if (DwarfFission != DwarfFissionKind::None) {
3239       if (DebugInfoKind == codegenoptions::NoDebugInfo)
3240         DebugInfoKind = codegenoptions::LimitedDebugInfo;
3241
3242       if (DwarfFission == DwarfFissionKind::Single)
3243         CmdArgs.push_back("-enable-split-dwarf=single");
3244       else
3245         CmdArgs.push_back("-enable-split-dwarf");
3246     }
3247   }
3248
3249   // After we've dealt with all combinations of things that could
3250   // make DebugInfoKind be other than None or DebugLineTablesOnly,
3251   // figure out if we need to "upgrade" it to standalone debug info.
3252   // We parse these two '-f' options whether or not they will be used,
3253   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3254   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3255                                     options::OPT_fno_standalone_debug,
3256                                     TC.GetDefaultStandaloneDebug());
3257   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3258     (void)checkDebugInfoOption(A, Args, D, TC);
3259   if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3260     DebugInfoKind = codegenoptions::FullDebugInfo;
3261
3262   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3263                    false)) {
3264     // Source embedding is a vendor extension to DWARF v5. By now we have
3265     // checked if a DWARF version was stated explicitly, and have otherwise
3266     // fallen back to the target default, so if this is still not at least 5
3267     // we emit an error.
3268     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3269     if (DWARFVersion < 5)
3270       D.Diag(diag::err_drv_argument_only_allowed_with)
3271           << A->getAsString(Args) << "-gdwarf-5";
3272     else if (checkDebugInfoOption(A, Args, D, TC))
3273       CmdArgs.push_back("-gembed-source");
3274   }
3275
3276   if (EmitCodeView) {
3277     CmdArgs.push_back("-gcodeview");
3278
3279     // Emit codeview type hashes if requested.
3280     if (Args.hasFlag(options::OPT_gcodeview_ghash,
3281                      options::OPT_gno_codeview_ghash, false)) {
3282       CmdArgs.push_back("-gcodeview-ghash");
3283     }
3284   }
3285
3286   // Adjust the debug info kind for the given toolchain.
3287   TC.adjustDebugInfoKind(DebugInfoKind, Args);
3288
3289   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3290                           DebuggerTuning);
3291
3292   // -fdebug-macro turns on macro debug info generation.
3293   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3294                    false))
3295     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3296                              D, TC))
3297       CmdArgs.push_back("-debug-info-macro");
3298
3299   // -ggnu-pubnames turns on gnu style pubnames in the backend.
3300   const auto *PubnamesArg =
3301       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3302                       options::OPT_gpubnames, options::OPT_gno_pubnames);
3303   if (DwarfFission != DwarfFissionKind::None ||
3304       DebuggerTuning == llvm::DebuggerKind::LLDB ||
3305       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3306     if (!PubnamesArg ||
3307         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3308          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3309       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3310                                            options::OPT_gpubnames)
3311                             ? "-gpubnames"
3312                             : "-ggnu-pubnames");
3313
3314   if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3315                    options::OPT_fno_debug_ranges_base_address, false)) {
3316     CmdArgs.push_back("-fdebug-ranges-base-address");
3317   }
3318
3319   // -gdwarf-aranges turns on the emission of the aranges section in the
3320   // backend.
3321   // Always enabled for SCE tuning.
3322   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3323   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3324     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3325   if (NeedAranges) {
3326     CmdArgs.push_back("-mllvm");
3327     CmdArgs.push_back("-generate-arange-section");
3328   }
3329
3330   if (Args.hasFlag(options::OPT_fdebug_types_section,
3331                    options::OPT_fno_debug_types_section, false)) {
3332     if (!T.isOSBinFormatELF()) {
3333       D.Diag(diag::err_drv_unsupported_opt_for_target)
3334           << Args.getLastArg(options::OPT_fdebug_types_section)
3335                  ->getAsString(Args)
3336           << T.getTriple();
3337     } else if (checkDebugInfoOption(
3338                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3339                    TC)) {
3340       CmdArgs.push_back("-mllvm");
3341       CmdArgs.push_back("-generate-type-units");
3342     }
3343   }
3344
3345   // Decide how to render forward declarations of template instantiations.
3346   // SCE wants full descriptions, others just get them in the name.
3347   if (DebuggerTuning == llvm::DebuggerKind::SCE)
3348     CmdArgs.push_back("-debug-forward-template-params");
3349
3350   // Do we need to explicitly import anonymous namespaces into the parent
3351   // scope?
3352   if (DebuggerTuning == llvm::DebuggerKind::SCE)
3353     CmdArgs.push_back("-dwarf-explicit-import");
3354
3355   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3356 }
3357
3358 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3359                          const InputInfo &Output, const InputInfoList &Inputs,
3360                          const ArgList &Args, const char *LinkingOutput) const {
3361   const auto &TC = getToolChain();
3362   const llvm::Triple &RawTriple = TC.getTriple();
3363   const llvm::Triple &Triple = TC.getEffectiveTriple();
3364   const std::string &TripleStr = Triple.getTriple();
3365
3366   bool KernelOrKext =
3367       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3368   const Driver &D = TC.getDriver();
3369   ArgStringList CmdArgs;
3370
3371   // Check number of inputs for sanity. We need at least one input.
3372   assert(Inputs.size() >= 1 && "Must have at least one input.");
3373   // CUDA/HIP compilation may have multiple inputs (source file + results of
3374   // device-side compilations). OpenMP device jobs also take the host IR as a
3375   // second input. Module precompilation accepts a list of header files to
3376   // include as part of the module. All other jobs are expected to have exactly
3377   // one input.
3378   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3379   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3380   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3381   bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3382
3383   // A header module compilation doesn't have a main input file, so invent a
3384   // fake one as a placeholder.
3385   const char *ModuleName = [&]{
3386     auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3387     return ModuleNameArg ? ModuleNameArg->getValue() : "";
3388   }();
3389   InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3390
3391   const InputInfo &Input =
3392       IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3393
3394   InputInfoList ModuleHeaderInputs;
3395   const InputInfo *CudaDeviceInput = nullptr;
3396   const InputInfo *OpenMPDeviceInput = nullptr;
3397   for (const InputInfo &I : Inputs) {
3398     if (&I == &Input) {
3399       // This is the primary input.
3400     } else if (IsHeaderModulePrecompile &&
3401                types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3402       types::ID Expected = HeaderModuleInput.getType();
3403       if (I.getType() != Expected) {
3404         D.Diag(diag::err_drv_module_header_wrong_kind)
3405             << I.getFilename() << types::getTypeName(I.getType())
3406             << types::getTypeName(Expected);
3407       }
3408       ModuleHeaderInputs.push_back(I);
3409     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3410       CudaDeviceInput = &I;
3411     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3412       OpenMPDeviceInput = &I;
3413     } else {
3414       llvm_unreachable("unexpectedly given multiple inputs");
3415     }
3416   }
3417
3418   const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3419   bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3420   bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3421   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3422   bool IsIAMCU = RawTriple.isOSIAMCU();
3423
3424   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
3425   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3426   // Windows), we need to pass Windows-specific flags to cc1.
3427   if (IsCuda || IsHIP) {
3428     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3429     IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3430     IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3431   }
3432
3433   // C++ is not supported for IAMCU.
3434   if (IsIAMCU && types::isCXX(Input.getType()))
3435     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3436
3437   // Invoke ourselves in -cc1 mode.
3438   //
3439   // FIXME: Implement custom jobs for internal actions.
3440   CmdArgs.push_back("-cc1");
3441
3442   // Add the "effective" target triple.
3443   CmdArgs.push_back("-triple");
3444   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3445
3446   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3447     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3448     Args.ClaimAllArgs(options::OPT_MJ);
3449   }
3450
3451   if (IsCuda || IsHIP) {
3452     // We have to pass the triple of the host if compiling for a CUDA/HIP device
3453     // and vice-versa.
3454     std::string NormalizedTriple;
3455     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3456         JA.isDeviceOffloading(Action::OFK_HIP))
3457       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3458                              ->getTriple()
3459                              .normalize();
3460     else
3461       NormalizedTriple =
3462           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3463                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3464               ->getTriple()
3465               .normalize();
3466
3467     CmdArgs.push_back("-aux-triple");
3468     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3469   }
3470
3471   if (IsOpenMPDevice) {
3472     // We have to pass the triple of the host if compiling for an OpenMP device.
3473     std::string NormalizedTriple =
3474         C.getSingleOffloadToolChain<Action::OFK_Host>()
3475             ->getTriple()
3476             .normalize();
3477     CmdArgs.push_back("-aux-triple");
3478     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3479   }
3480
3481   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3482                                Triple.getArch() == llvm::Triple::thumb)) {
3483     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3484     unsigned Version;
3485     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3486     if (Version < 7)
3487       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3488                                                 << TripleStr;
3489   }
3490
3491   // Push all default warning arguments that are specific to
3492   // the given target.  These come before user provided warning options
3493   // are provided.
3494   TC.addClangWarningOptions(CmdArgs);
3495
3496   // Select the appropriate action.
3497   RewriteKind rewriteKind = RK_None;
3498
3499   if (isa<AnalyzeJobAction>(JA)) {
3500     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3501     CmdArgs.push_back("-analyze");
3502   } else if (isa<MigrateJobAction>(JA)) {
3503     CmdArgs.push_back("-migrate");
3504   } else if (isa<PreprocessJobAction>(JA)) {
3505     if (Output.getType() == types::TY_Dependencies)
3506       CmdArgs.push_back("-Eonly");
3507     else {
3508       CmdArgs.push_back("-E");
3509       if (Args.hasArg(options::OPT_rewrite_objc) &&
3510           !Args.hasArg(options::OPT_g_Group))
3511         CmdArgs.push_back("-P");
3512     }
3513   } else if (isa<AssembleJobAction>(JA)) {
3514     CmdArgs.push_back("-emit-obj");
3515
3516     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3517
3518     // Also ignore explicit -force_cpusubtype_ALL option.
3519     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3520   } else if (isa<PrecompileJobAction>(JA)) {
3521     if (JA.getType() == types::TY_Nothing)
3522       CmdArgs.push_back("-fsyntax-only");
3523     else if (JA.getType() == types::TY_ModuleFile)
3524       CmdArgs.push_back(IsHeaderModulePrecompile
3525                             ? "-emit-header-module"
3526                             : "-emit-module-interface");
3527     else
3528       CmdArgs.push_back("-emit-pch");
3529   } else if (isa<VerifyPCHJobAction>(JA)) {
3530     CmdArgs.push_back("-verify-pch");
3531   } else {
3532     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3533            "Invalid action for clang tool.");
3534     if (JA.getType() == types::TY_Nothing) {
3535       CmdArgs.push_back("-fsyntax-only");
3536     } else if (JA.getType() == types::TY_LLVM_IR ||
3537                JA.getType() == types::TY_LTO_IR) {
3538       CmdArgs.push_back("-emit-llvm");
3539     } else if (JA.getType() == types::TY_LLVM_BC ||
3540                JA.getType() == types::TY_LTO_BC) {
3541       CmdArgs.push_back("-emit-llvm-bc");
3542     } else if (JA.getType() == types::TY_PP_Asm) {
3543       CmdArgs.push_back("-S");
3544     } else if (JA.getType() == types::TY_AST) {
3545       CmdArgs.push_back("-emit-pch");
3546     } else if (JA.getType() == types::TY_ModuleFile) {
3547       CmdArgs.push_back("-module-file-info");
3548     } else if (JA.getType() == types::TY_RewrittenObjC) {
3549       CmdArgs.push_back("-rewrite-objc");
3550       rewriteKind = RK_NonFragile;
3551     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3552       CmdArgs.push_back("-rewrite-objc");
3553       rewriteKind = RK_Fragile;
3554     } else {
3555       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3556     }
3557
3558     // Preserve use-list order by default when emitting bitcode, so that
3559     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3560     // same result as running passes here.  For LTO, we don't need to preserve
3561     // the use-list order, since serialization to bitcode is part of the flow.
3562     if (JA.getType() == types::TY_LLVM_BC)
3563       CmdArgs.push_back("-emit-llvm-uselists");
3564
3565     // Device-side jobs do not support LTO.
3566     bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3567                                    JA.isDeviceOffloading(Action::OFK_Host));
3568
3569     if (D.isUsingLTO() && !isDeviceOffloadAction) {
3570       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3571
3572       // The Darwin and PS4 linkers currently use the legacy LTO API, which
3573       // does not support LTO unit features (CFI, whole program vtable opt)
3574       // under ThinLTO.
3575       if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3576           D.getLTOMode() == LTOK_Full)
3577         CmdArgs.push_back("-flto-unit");
3578     }
3579   }
3580
3581   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3582     if (!types::isLLVMIR(Input.getType()))
3583       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3584                                                        << "-x ir";
3585     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3586   }
3587
3588   if (Args.getLastArg(options::OPT_save_temps_EQ))
3589     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3590
3591   // Embed-bitcode option.
3592   // Only white-listed flags below are allowed to be embedded.
3593   if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3594       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3595     // Add flags implied by -fembed-bitcode.
3596     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3597     // Disable all llvm IR level optimizations.
3598     CmdArgs.push_back("-disable-llvm-passes");
3599
3600     // reject options that shouldn't be supported in bitcode
3601     // also reject kernel/kext
3602     static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3603         options::OPT_mkernel,
3604         options::OPT_fapple_kext,
3605         options::OPT_ffunction_sections,
3606         options::OPT_fno_function_sections,
3607         options::OPT_fdata_sections,
3608         options::OPT_fno_data_sections,
3609         options::OPT_funique_section_names,
3610         options::OPT_fno_unique_section_names,
3611         options::OPT_mrestrict_it,
3612         options::OPT_mno_restrict_it,
3613         options::OPT_mstackrealign,
3614         options::OPT_mno_stackrealign,
3615         options::OPT_mstack_alignment,
3616         options::OPT_mcmodel_EQ,
3617         options::OPT_mlong_calls,
3618         options::OPT_mno_long_calls,
3619         options::OPT_ggnu_pubnames,
3620         options::OPT_gdwarf_aranges,
3621         options::OPT_fdebug_types_section,
3622         options::OPT_fno_debug_types_section,
3623         options::OPT_fdwarf_directory_asm,
3624         options::OPT_fno_dwarf_directory_asm,
3625         options::OPT_mrelax_all,
3626         options::OPT_mno_relax_all,
3627         options::OPT_ftrap_function_EQ,
3628         options::OPT_ffixed_r9,
3629         options::OPT_mfix_cortex_a53_835769,
3630         options::OPT_mno_fix_cortex_a53_835769,
3631         options::OPT_ffixed_x18,
3632         options::OPT_mglobal_merge,
3633         options::OPT_mno_global_merge,
3634         options::OPT_mred_zone,
3635         options::OPT_mno_red_zone,
3636         options::OPT_Wa_COMMA,
3637         options::OPT_Xassembler,
3638         options::OPT_mllvm,
3639     };
3640     for (const auto &A : Args)
3641       if (std::find(std::begin(kBitcodeOptionBlacklist),
3642                     std::end(kBitcodeOptionBlacklist),
3643                     A->getOption().getID()) !=
3644           std::end(kBitcodeOptionBlacklist))
3645         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3646
3647     // Render the CodeGen options that need to be passed.
3648     if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3649                       options::OPT_fno_optimize_sibling_calls))
3650       CmdArgs.push_back("-mdisable-tail-calls");
3651
3652     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3653                                CmdArgs);
3654
3655     // Render ABI arguments
3656     switch (TC.getArch()) {
3657     default: break;
3658     case llvm::Triple::arm:
3659     case llvm::Triple::armeb:
3660     case llvm::Triple::thumbeb:
3661       RenderARMABI(Triple, Args, CmdArgs);
3662       break;
3663     case llvm::Triple::aarch64:
3664     case llvm::Triple::aarch64_be:
3665       RenderAArch64ABI(Triple, Args, CmdArgs);
3666       break;
3667     }
3668
3669     // Optimization level for CodeGen.
3670     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3671       if (A->getOption().matches(options::OPT_O4)) {
3672         CmdArgs.push_back("-O3");
3673         D.Diag(diag::warn_O4_is_O3);
3674       } else {
3675         A->render(Args, CmdArgs);
3676       }
3677     }
3678
3679     // Input/Output file.
3680     if (Output.getType() == types::TY_Dependencies) {
3681       // Handled with other dependency code.
3682     } else if (Output.isFilename()) {
3683       CmdArgs.push_back("-o");
3684       CmdArgs.push_back(Output.getFilename());
3685     } else {
3686       assert(Output.isNothing() && "Input output.");
3687     }
3688
3689     for (const auto &II : Inputs) {
3690       addDashXForInput(Args, II, CmdArgs);
3691       if (II.isFilename())
3692         CmdArgs.push_back(II.getFilename());
3693       else
3694         II.getInputArg().renderAsInput(Args, CmdArgs);
3695     }
3696
3697     C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3698                                             CmdArgs, Inputs));
3699     return;
3700   }
3701
3702   if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3703     CmdArgs.push_back("-fembed-bitcode=marker");
3704
3705   // We normally speed up the clang process a bit by skipping destructors at
3706   // exit, but when we're generating diagnostics we can rely on some of the
3707   // cleanup.
3708   if (!C.isForDiagnostics())
3709     CmdArgs.push_back("-disable-free");
3710
3711 #ifdef NDEBUG
3712   const bool IsAssertBuild = false;
3713 #else
3714   const bool IsAssertBuild = true;
3715 #endif
3716
3717   // Disable the verification pass in -asserts builds.
3718   if (!IsAssertBuild)
3719     CmdArgs.push_back("-disable-llvm-verifier");
3720
3721   // Discard value names in assert builds unless otherwise specified.
3722   if (Args.hasFlag(options::OPT_fdiscard_value_names,
3723                    options::OPT_fno_discard_value_names, !IsAssertBuild))
3724     CmdArgs.push_back("-discard-value-names");
3725
3726   // Set the main file name, so that debug info works even with
3727   // -save-temps.
3728   CmdArgs.push_back("-main-file-name");
3729   CmdArgs.push_back(getBaseInputName(Args, Input));
3730
3731   // Some flags which affect the language (via preprocessor
3732   // defines).
3733   if (Args.hasArg(options::OPT_static))
3734     CmdArgs.push_back("-static-define");
3735
3736   if (Args.hasArg(options::OPT_municode))
3737     CmdArgs.push_back("-DUNICODE");
3738
3739   if (isa<AnalyzeJobAction>(JA))
3740     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3741
3742   // Enable compatilibily mode to avoid analyzer-config related errors.
3743   // Since we can't access frontend flags through hasArg, let's manually iterate
3744   // through them.
3745   bool FoundAnalyzerConfig = false;
3746   for (auto Arg : Args.filtered(options::OPT_Xclang))
3747     if (StringRef(Arg->getValue()) == "-analyzer-config") {
3748       FoundAnalyzerConfig = true;
3749       break;
3750     }
3751   if (!FoundAnalyzerConfig)
3752     for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3753       if (StringRef(Arg->getValue()) == "-analyzer-config") {
3754         FoundAnalyzerConfig = true;
3755         break;
3756       }
3757   if (FoundAnalyzerConfig)
3758     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
3759
3760   CheckCodeGenerationOptions(D, Args);
3761
3762   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3763   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3764   if (FunctionAlignment) {
3765     CmdArgs.push_back("-function-alignment");
3766     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3767   }
3768
3769   llvm::Reloc::Model RelocationModel;
3770   unsigned PICLevel;
3771   bool IsPIE;
3772   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3773
3774   const char *RMName = RelocationModelName(RelocationModel);
3775
3776   if ((RelocationModel == llvm::Reloc::ROPI ||
3777        RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3778       types::isCXX(Input.getType()) &&
3779       !Args.hasArg(options::OPT_fallow_unsupported))
3780     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3781
3782   if (RMName) {
3783     CmdArgs.push_back("-mrelocation-model");
3784     CmdArgs.push_back(RMName);
3785   }
3786   if (PICLevel > 0) {
3787     CmdArgs.push_back("-pic-level");
3788     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3789     if (IsPIE)
3790       CmdArgs.push_back("-pic-is-pie");
3791   }
3792
3793   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3794     CmdArgs.push_back("-meabi");
3795     CmdArgs.push_back(A->getValue());
3796   }
3797
3798   CmdArgs.push_back("-mthread-model");
3799   if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3800     if (!TC.isThreadModelSupported(A->getValue()))
3801       D.Diag(diag::err_drv_invalid_thread_model_for_target)
3802           << A->getValue() << A->getAsString(Args);
3803     CmdArgs.push_back(A->getValue());
3804   }
3805   else
3806     CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3807
3808   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3809
3810   if (Args.hasFlag(options::OPT_fmerge_all_constants,
3811                    options::OPT_fno_merge_all_constants, false))
3812     CmdArgs.push_back("-fmerge-all-constants");
3813
3814   if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3815                    options::OPT_fdelete_null_pointer_checks, false))
3816     CmdArgs.push_back("-fno-delete-null-pointer-checks");
3817
3818   // LLVM Code Generator Options.
3819
3820   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3821       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3822     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3823                                       options::OPT_frewrite_map_file_EQ)) {
3824       StringRef Map = A->getValue();
3825       if (!llvm::sys::fs::exists(Map)) {
3826         D.Diag(diag::err_drv_no_such_file) << Map;
3827       } else {
3828         CmdArgs.push_back("-frewrite-map-file");
3829         CmdArgs.push_back(A->getValue());
3830         A->claim();
3831       }
3832     }
3833   }
3834
3835   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3836     StringRef v = A->getValue();
3837     CmdArgs.push_back("-mllvm");
3838     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3839     A->claim();
3840   }
3841
3842   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3843                     true))
3844     CmdArgs.push_back("-fno-jump-tables");
3845
3846   if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3847                    options::OPT_fno_profile_sample_accurate, false))
3848     CmdArgs.push_back("-fprofile-sample-accurate");
3849
3850   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3851                     options::OPT_fno_preserve_as_comments, true))
3852     CmdArgs.push_back("-fno-preserve-as-comments");
3853
3854   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3855     CmdArgs.push_back("-mregparm");
3856     CmdArgs.push_back(A->getValue());
3857   }
3858
3859   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3860                                options::OPT_freg_struct_return)) {
3861     if (TC.getArch() != llvm::Triple::x86) {
3862       D.Diag(diag::err_drv_unsupported_opt_for_target)
3863           << A->getSpelling() << RawTriple.str();
3864     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3865       CmdArgs.push_back("-fpcc-struct-return");
3866     } else {
3867       assert(A->getOption().matches(options::OPT_freg_struct_return));
3868       CmdArgs.push_back("-freg-struct-return");
3869     }
3870   }
3871
3872   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3873     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3874
3875   if (shouldUseFramePointer(Args, RawTriple))
3876     CmdArgs.push_back("-mdisable-fp-elim");
3877   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3878                     options::OPT_fno_zero_initialized_in_bss))
3879     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3880
3881   bool OFastEnabled = isOptimizationLevelFast(Args);
3882   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3883   // enabled.  This alias option is being used to simplify the hasFlag logic.
3884   OptSpecifier StrictAliasingAliasOption =
3885       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3886   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3887   // doesn't do any TBAA.
3888   bool TBAAOnByDefault = !D.IsCLMode();
3889   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3890                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3891     CmdArgs.push_back("-relaxed-aliasing");
3892   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3893                     options::OPT_fno_struct_path_tbaa))
3894     CmdArgs.push_back("-no-struct-path-tbaa");
3895   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3896                    false))
3897     CmdArgs.push_back("-fstrict-enums");
3898   if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3899                     true))
3900     CmdArgs.push_back("-fno-strict-return");
3901   if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3902                    options::OPT_fno_allow_editor_placeholders, false))
3903     CmdArgs.push_back("-fallow-editor-placeholders");
3904   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3905                    options::OPT_fno_strict_vtable_pointers,
3906                    false))
3907     CmdArgs.push_back("-fstrict-vtable-pointers");
3908   if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3909                    options::OPT_fno_force_emit_vtables,
3910                    false))
3911     CmdArgs.push_back("-fforce-emit-vtables");
3912   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3913                     options::OPT_fno_optimize_sibling_calls))
3914     CmdArgs.push_back("-mdisable-tail-calls");
3915   if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3916                    options::OPT_fescaping_block_tail_calls, false))
3917     CmdArgs.push_back("-fno-escaping-block-tail-calls");
3918
3919   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3920                   options::OPT_fno_fine_grained_bitfield_accesses);
3921
3922   // Handle segmented stacks.
3923   if (Args.hasArg(options::OPT_fsplit_stack))
3924     CmdArgs.push_back("-split-stacks");
3925
3926   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
3927
3928   // Decide whether to use verbose asm. Verbose assembly is the default on
3929   // toolchains which have the integrated assembler on by default.
3930   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
3931   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3932                    IsIntegratedAssemblerDefault) ||
3933       Args.hasArg(options::OPT_dA))
3934     CmdArgs.push_back("-masm-verbose");
3935
3936   if (!TC.useIntegratedAs())
3937     CmdArgs.push_back("-no-integrated-as");
3938
3939   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3940     CmdArgs.push_back("-mdebug-pass");
3941     CmdArgs.push_back("Structure");
3942   }
3943   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3944     CmdArgs.push_back("-mdebug-pass");
3945     CmdArgs.push_back("Arguments");
3946   }
3947
3948   // Enable -mconstructor-aliases except on darwin, where we have to work around
3949   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3950   // aliases aren't supported.
3951   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
3952     CmdArgs.push_back("-mconstructor-aliases");
3953
3954   // Darwin's kernel doesn't support guard variables; just die if we
3955   // try to use them.
3956   if (KernelOrKext && RawTriple.isOSDarwin())
3957     CmdArgs.push_back("-fforbid-guard-variables");
3958
3959   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3960                    false)) {
3961     CmdArgs.push_back("-mms-bitfields");
3962   }
3963
3964   if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3965                    options::OPT_mno_pie_copy_relocations,
3966                    false)) {
3967     CmdArgs.push_back("-mpie-copy-relocations");
3968   }
3969
3970   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3971     CmdArgs.push_back("-fno-plt");
3972   }
3973
3974   // -fhosted is default.
3975   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3976   // use Freestanding.
3977   bool Freestanding =
3978       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3979       KernelOrKext;
3980   if (Freestanding)
3981     CmdArgs.push_back("-ffreestanding");
3982
3983   // This is a coarse approximation of what llvm-gcc actually does, both
3984   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3985   // complicated ways.
3986   bool AsynchronousUnwindTables =
3987       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3988                    options::OPT_fno_asynchronous_unwind_tables,
3989                    (TC.IsUnwindTablesDefault(Args) ||
3990                     TC.getSanitizerArgs().needsUnwindTables()) &&
3991                        !Freestanding);
3992   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3993                    AsynchronousUnwindTables))
3994     CmdArgs.push_back("-munwind-tables");
3995
3996   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3997
3998   // FIXME: Handle -mtune=.
3999   (void)Args.hasArg(options::OPT_mtune_EQ);
4000
4001   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4002     CmdArgs.push_back("-mcode-model");
4003     CmdArgs.push_back(A->getValue());
4004   }
4005
4006   // Add the target cpu
4007   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4008   if (!CPU.empty()) {
4009     CmdArgs.push_back("-target-cpu");
4010     CmdArgs.push_back(Args.MakeArgString(CPU));
4011   }
4012
4013   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4014
4015   // These two are potentially updated by AddClangCLArgs.
4016   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4017   bool EmitCodeView = false;
4018
4019   // Add clang-cl arguments.
4020   types::ID InputType = Input.getType();
4021   if (D.IsCLMode())
4022     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4023
4024   DwarfFissionKind DwarfFission;
4025   RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
4026                      CmdArgs, DebugInfoKind, DwarfFission);
4027
4028   // Add the split debug info name to the command lines here so we
4029   // can propagate it to the backend.
4030   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4031                     (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
4032                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4033                      isa<BackendJobAction>(JA));
4034   const char *SplitDWARFOut;
4035   if (SplitDWARF) {
4036     CmdArgs.push_back("-split-dwarf-file");
4037     SplitDWARFOut = SplitDebugName(Args, Output);
4038     CmdArgs.push_back(SplitDWARFOut);
4039   }
4040
4041   // Pass the linker version in use.
4042   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4043     CmdArgs.push_back("-target-linker-version");
4044     CmdArgs.push_back(A->getValue());
4045   }
4046
4047   if (!shouldUseLeafFramePointer(Args, RawTriple))
4048     CmdArgs.push_back("-momit-leaf-frame-pointer");
4049
4050   // Explicitly error on some things we know we don't support and can't just
4051   // ignore.
4052   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4053     Arg *Unsupported;
4054     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
4055         TC.getArch() == llvm::Triple::x86) {
4056       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4057           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4058         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4059             << Unsupported->getOption().getName();
4060     }
4061     // The faltivec option has been superseded by the maltivec option.
4062     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4063       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4064           << Unsupported->getOption().getName()
4065           << "please use -maltivec and include altivec.h explicitly";
4066     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4067       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4068           << Unsupported->getOption().getName() << "please use -mno-altivec";
4069   }
4070
4071   Args.AddAllArgs(CmdArgs, options::OPT_v);
4072   Args.AddLastArg(CmdArgs, options::OPT_H);
4073   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4074     CmdArgs.push_back("-header-include-file");
4075     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4076                                                : "-");
4077   }
4078   Args.AddLastArg(CmdArgs, options::OPT_P);
4079   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4080
4081   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4082     CmdArgs.push_back("-diagnostic-log-file");
4083     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4084                                                  : "-");
4085   }
4086
4087   bool UseSeparateSections = isUseSeparateSections(Triple);
4088
4089   if (Args.hasFlag(options::OPT_ffunction_sections,
4090                    options::OPT_fno_function_sections, UseSeparateSections)) {
4091     CmdArgs.push_back("-ffunction-sections");
4092   }
4093
4094   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4095                    UseSeparateSections)) {
4096     CmdArgs.push_back("-fdata-sections");
4097   }
4098
4099   if (!Args.hasFlag(options::OPT_funique_section_names,
4100                     options::OPT_fno_unique_section_names, true))
4101     CmdArgs.push_back("-fno-unique-section-names");
4102
4103   if (auto *A = Args.getLastArg(
4104       options::OPT_finstrument_functions,
4105       options::OPT_finstrument_functions_after_inlining,
4106       options::OPT_finstrument_function_entry_bare))
4107     A->render(Args, CmdArgs);
4108
4109   // NVPTX doesn't support PGO or coverage. There's no runtime support for
4110   // sampling, overhead of call arc collection is way too high and there's no
4111   // way to collect the output.
4112   if (!Triple.isNVPTX())
4113     addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4114
4115   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4116     ABICompatArg->render(Args, CmdArgs);
4117
4118   // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4119   if (RawTriple.isPS4CPU() &&
4120       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4121     PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4122     PS4cpu::addSanitizerArgs(TC, CmdArgs);
4123   }
4124
4125   // Pass options for controlling the default header search paths.
4126   if (Args.hasArg(options::OPT_nostdinc)) {
4127     CmdArgs.push_back("-nostdsysteminc");
4128     CmdArgs.push_back("-nobuiltininc");
4129   } else {
4130     if (Args.hasArg(options::OPT_nostdlibinc))
4131       CmdArgs.push_back("-nostdsysteminc");
4132     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4133     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4134   }
4135
4136   // Pass the path to compiler resource files.
4137   CmdArgs.push_back("-resource-dir");
4138   CmdArgs.push_back(D.ResourceDir.c_str());
4139
4140   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4141
4142   RenderARCMigrateToolOptions(D, Args, CmdArgs);
4143
4144   // Add preprocessing options like -I, -D, etc. if we are using the
4145   // preprocessor.
4146   //
4147   // FIXME: Support -fpreprocessed
4148   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4149     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4150
4151   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4152   // that "The compiler can only warn and ignore the option if not recognized".
4153   // When building with ccache, it will pass -D options to clang even on
4154   // preprocessed inputs and configure concludes that -fPIC is not supported.
4155   Args.ClaimAllArgs(options::OPT_D);
4156
4157   // Manually translate -O4 to -O3; let clang reject others.
4158   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4159     if (A->getOption().matches(options::OPT_O4)) {
4160       CmdArgs.push_back("-O3");
4161       D.Diag(diag::warn_O4_is_O3);
4162     } else {
4163       A->render(Args, CmdArgs);
4164     }
4165   }
4166
4167   // Warn about ignored options to clang.
4168   for (const Arg *A :
4169        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4170     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4171     A->claim();
4172   }
4173
4174   for (const Arg *A :
4175        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4176     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4177     A->claim();
4178   }
4179
4180   claimNoWarnArgs(Args);
4181
4182   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4183
4184   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4185   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4186     CmdArgs.push_back("-pedantic");
4187   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4188   Args.AddLastArg(CmdArgs, options::OPT_w);
4189
4190   // Fixed point flags
4191   if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4192                    /*Default=*/false))
4193     Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4194
4195   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4196   // (-ansi is equivalent to -std=c89 or -std=c++98).
4197   //
4198   // If a std is supplied, only add -trigraphs if it follows the
4199   // option.
4200   bool ImplyVCPPCXXVer = false;
4201   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4202     if (Std->getOption().matches(options::OPT_ansi))
4203       if (types::isCXX(InputType))
4204         CmdArgs.push_back("-std=c++98");
4205       else
4206         CmdArgs.push_back("-std=c89");
4207     else
4208       Std->render(Args, CmdArgs);
4209
4210     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4211     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4212                                  options::OPT_ftrigraphs,
4213                                  options::OPT_fno_trigraphs))
4214       if (A != Std)
4215         A->render(Args, CmdArgs);
4216   } else {
4217     // Honor -std-default.
4218     //
4219     // FIXME: Clang doesn't correctly handle -std= when the input language
4220     // doesn't match. For the time being just ignore this for C++ inputs;
4221     // eventually we want to do all the standard defaulting here instead of
4222     // splitting it between the driver and clang -cc1.
4223     if (!types::isCXX(InputType))
4224       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4225                                 /*Joined=*/true);
4226     else if (IsWindowsMSVC)
4227       ImplyVCPPCXXVer = true;
4228
4229     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4230                     options::OPT_fno_trigraphs);
4231   }
4232
4233   // GCC's behavior for -Wwrite-strings is a bit strange:
4234   //  * In C, this "warning flag" changes the types of string literals from
4235   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4236   //    for the discarded qualifier.
4237   //  * In C++, this is just a normal warning flag.
4238   //
4239   // Implementing this warning correctly in C is hard, so we follow GCC's
4240   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4241   // a non-const char* in C, rather than using this crude hack.
4242   if (!types::isCXX(InputType)) {
4243     // FIXME: This should behave just like a warning flag, and thus should also
4244     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4245     Arg *WriteStrings =
4246         Args.getLastArg(options::OPT_Wwrite_strings,
4247                         options::OPT_Wno_write_strings, options::OPT_w);
4248     if (WriteStrings &&
4249         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4250       CmdArgs.push_back("-fconst-strings");
4251   }
4252
4253   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4254   // during C++ compilation, which it is by default. GCC keeps this define even
4255   // in the presence of '-w', match this behavior bug-for-bug.
4256   if (types::isCXX(InputType) &&
4257       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4258                    true)) {
4259     CmdArgs.push_back("-fdeprecated-macro");
4260   }
4261
4262   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4263   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4264     if (Asm->getOption().matches(options::OPT_fasm))
4265       CmdArgs.push_back("-fgnu-keywords");
4266     else
4267       CmdArgs.push_back("-fno-gnu-keywords");
4268   }
4269
4270   if (ShouldDisableDwarfDirectory(Args, TC))
4271     CmdArgs.push_back("-fno-dwarf-directory-asm");
4272
4273   if (ShouldDisableAutolink(Args, TC))
4274     CmdArgs.push_back("-fno-autolink");
4275
4276   // Add in -fdebug-compilation-dir if necessary.
4277   addDebugCompDirArg(Args, CmdArgs);
4278
4279   addDebugPrefixMapArg(D, Args, CmdArgs);
4280
4281   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4282                                options::OPT_ftemplate_depth_EQ)) {
4283     CmdArgs.push_back("-ftemplate-depth");
4284     CmdArgs.push_back(A->getValue());
4285   }
4286
4287   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4288     CmdArgs.push_back("-foperator-arrow-depth");
4289     CmdArgs.push_back(A->getValue());
4290   }
4291
4292   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4293     CmdArgs.push_back("-fconstexpr-depth");
4294     CmdArgs.push_back(A->getValue());
4295   }
4296
4297   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4298     CmdArgs.push_back("-fconstexpr-steps");
4299     CmdArgs.push_back(A->getValue());
4300   }
4301
4302   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4303     CmdArgs.push_back("-fbracket-depth");
4304     CmdArgs.push_back(A->getValue());
4305   }
4306
4307   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4308                                options::OPT_Wlarge_by_value_copy_def)) {
4309     if (A->getNumValues()) {
4310       StringRef bytes = A->getValue();
4311       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4312     } else
4313       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4314   }
4315
4316   if (Args.hasArg(options::OPT_relocatable_pch))
4317     CmdArgs.push_back("-relocatable-pch");
4318
4319   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4320     static const char *kCFABIs[] = {
4321       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4322     };
4323
4324     if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4325       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4326     else
4327       A->render(Args, CmdArgs);
4328   }
4329
4330   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4331     CmdArgs.push_back("-fconstant-string-class");
4332     CmdArgs.push_back(A->getValue());
4333   }
4334
4335   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4336     CmdArgs.push_back("-ftabstop");
4337     CmdArgs.push_back(A->getValue());
4338   }
4339
4340   if (Args.hasFlag(options::OPT_fstack_size_section,
4341                    options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4342     CmdArgs.push_back("-fstack-size-section");
4343
4344   CmdArgs.push_back("-ferror-limit");
4345   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4346     CmdArgs.push_back(A->getValue());
4347   else
4348     CmdArgs.push_back("19");
4349
4350   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4351     CmdArgs.push_back("-fmacro-backtrace-limit");
4352     CmdArgs.push_back(A->getValue());
4353   }
4354
4355   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4356     CmdArgs.push_back("-ftemplate-backtrace-limit");
4357     CmdArgs.push_back(A->getValue());
4358   }
4359
4360   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4361     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4362     CmdArgs.push_back(A->getValue());
4363   }
4364
4365   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4366     CmdArgs.push_back("-fspell-checking-limit");
4367     CmdArgs.push_back(A->getValue());
4368   }
4369
4370   // Pass -fmessage-length=.
4371   CmdArgs.push_back("-fmessage-length");
4372   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4373     CmdArgs.push_back(A->getValue());
4374   } else {
4375     // If -fmessage-length=N was not specified, determine whether this is a
4376     // terminal and, if so, implicitly define -fmessage-length appropriately.
4377     unsigned N = llvm::sys::Process::StandardErrColumns();
4378     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4379   }
4380
4381   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4382   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4383                                      options::OPT_fvisibility_ms_compat)) {
4384     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4385       CmdArgs.push_back("-fvisibility");
4386       CmdArgs.push_back(A->getValue());
4387     } else {
4388       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4389       CmdArgs.push_back("-fvisibility");
4390       CmdArgs.push_back("hidden");
4391       CmdArgs.push_back("-ftype-visibility");
4392       CmdArgs.push_back("default");
4393     }
4394   }
4395
4396   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4397   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
4398
4399   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4400
4401   // Forward -f (flag) options which we can pass directly.
4402   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4403   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4404   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4405   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4406   Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4407                   options::OPT_fno_emulated_tls);
4408   Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4409
4410   // AltiVec-like language extensions aren't relevant for assembling.
4411   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4412     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4413
4414   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4415   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4416
4417   // Forward flags for OpenMP. We don't do this if the current action is an
4418   // device offloading action other than OpenMP.
4419   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4420                    options::OPT_fno_openmp, false) &&
4421       (JA.isDeviceOffloading(Action::OFK_None) ||
4422        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4423     switch (D.getOpenMPRuntime(Args)) {
4424     case Driver::OMPRT_OMP:
4425     case Driver::OMPRT_IOMP5:
4426       // Clang can generate useful OpenMP code for these two runtime libraries.
4427       CmdArgs.push_back("-fopenmp");
4428
4429       // If no option regarding the use of TLS in OpenMP codegeneration is
4430       // given, decide a default based on the target. Otherwise rely on the
4431       // options and pass the right information to the frontend.
4432       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4433                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4434         CmdArgs.push_back("-fnoopenmp-use-tls");
4435       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4436                       options::OPT_fno_openmp_simd);
4437       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4438       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4439       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
4440       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4441                        options::OPT_fno_openmp_optimistic_collapse,
4442                        /*Default=*/false))
4443         CmdArgs.push_back("-fopenmp-optimistic-collapse");
4444
4445       // When in OpenMP offloading mode with NVPTX target, forward
4446       // cuda-mode flag
4447       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4448                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4449         CmdArgs.push_back("-fopenmp-cuda-mode");
4450
4451       // When in OpenMP offloading mode with NVPTX target, check if full runtime
4452       // is required.
4453       if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4454                        options::OPT_fno_openmp_cuda_force_full_runtime,
4455                        /*Default=*/false))
4456         CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4457       break;
4458     default:
4459       // By default, if Clang doesn't know how to generate useful OpenMP code
4460       // for a specific runtime library, we just don't pass the '-fopenmp' flag
4461       // down to the actual compilation.
4462       // FIXME: It would be better to have a mode which *only* omits IR
4463       // generation based on the OpenMP support so that we get consistent
4464       // semantic analysis, etc.
4465       break;
4466     }
4467   } else {
4468     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4469                     options::OPT_fno_openmp_simd);
4470     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4471   }
4472
4473   const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4474   Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4475
4476   const XRayArgs &XRay = TC.getXRayArgs();
4477   XRay.addArgs(TC, Args, CmdArgs, InputType);
4478
4479   if (TC.SupportsProfiling())
4480     Args.AddLastArg(CmdArgs, options::OPT_pg);
4481
4482   if (TC.SupportsProfiling())
4483     Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4484
4485   // -flax-vector-conversions is default.
4486   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4487                     options::OPT_fno_lax_vector_conversions))
4488     CmdArgs.push_back("-fno-lax-vector-conversions");
4489
4490   if (Args.getLastArg(options::OPT_fapple_kext) ||
4491       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4492     CmdArgs.push_back("-fapple-kext");
4493
4494   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4495   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4496   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4497   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4498   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4499
4500   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4501     CmdArgs.push_back("-ftrapv-handler");
4502     CmdArgs.push_back(A->getValue());
4503   }
4504
4505   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4506
4507   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4508   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4509   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4510     if (A->getOption().matches(options::OPT_fwrapv))
4511       CmdArgs.push_back("-fwrapv");
4512   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4513                                       options::OPT_fno_strict_overflow)) {
4514     if (A->getOption().matches(options::OPT_fno_strict_overflow))
4515       CmdArgs.push_back("-fwrapv");
4516   }
4517
4518   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4519                                options::OPT_fno_reroll_loops))
4520     if (A->getOption().matches(options::OPT_freroll_loops))
4521       CmdArgs.push_back("-freroll-loops");
4522
4523   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4524   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4525                   options::OPT_fno_unroll_loops);
4526
4527   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4528
4529   if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4530                    false))
4531     CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
4532
4533   RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4534   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
4535
4536   // Translate -mstackrealign
4537   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4538                    false))
4539     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4540
4541   if (Args.hasArg(options::OPT_mstack_alignment)) {
4542     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4543     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4544   }
4545
4546   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4547     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4548
4549     if (!Size.empty())
4550       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4551     else
4552       CmdArgs.push_back("-mstack-probe-size=0");
4553   }
4554
4555   if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4556                     options::OPT_mno_stack_arg_probe, true))
4557     CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4558
4559   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4560                                options::OPT_mno_restrict_it)) {
4561     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4562       CmdArgs.push_back("-mllvm");
4563       CmdArgs.push_back("-arm-restrict-it");
4564     } else {
4565       CmdArgs.push_back("-mllvm");
4566       CmdArgs.push_back("-arm-no-restrict-it");
4567     }
4568   } else if (Triple.isOSWindows() &&
4569              (Triple.getArch() == llvm::Triple::arm ||
4570               Triple.getArch() == llvm::Triple::thumb)) {
4571     // Windows on ARM expects restricted IT blocks
4572     CmdArgs.push_back("-mllvm");
4573     CmdArgs.push_back("-arm-restrict-it");
4574   }
4575
4576   // Forward -cl options to -cc1
4577   RenderOpenCLOptions(Args, CmdArgs);
4578
4579   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4580     CmdArgs.push_back(
4581         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4582   }
4583
4584   // Forward -f options with positive and negative forms; we translate
4585   // these by hand.
4586   if (Arg *A = getLastProfileSampleUseArg(Args)) {
4587     StringRef fname = A->getValue();
4588     if (!llvm::sys::fs::exists(fname))
4589       D.Diag(diag::err_drv_no_such_file) << fname;
4590     else
4591       A->render(Args, CmdArgs);
4592   }
4593   Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4594
4595   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4596
4597   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4598                     options::OPT_fno_assume_sane_operator_new))
4599     CmdArgs.push_back("-fno-assume-sane-operator-new");
4600
4601   // -fblocks=0 is default.
4602   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4603                    TC.IsBlocksDefault()) ||
4604       (Args.hasArg(options::OPT_fgnu_runtime) &&
4605        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4606        !Args.hasArg(options::OPT_fno_blocks))) {
4607     CmdArgs.push_back("-fblocks");
4608
4609     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4610       CmdArgs.push_back("-fblocks-runtime-optional");
4611   }
4612
4613   // -fencode-extended-block-signature=1 is default.
4614   if (TC.IsEncodeExtendedBlockSignatureDefault())
4615     CmdArgs.push_back("-fencode-extended-block-signature");
4616
4617   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4618                    false) &&
4619       types::isCXX(InputType)) {
4620     CmdArgs.push_back("-fcoroutines-ts");
4621   }
4622
4623   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4624                   options::OPT_fno_double_square_bracket_attributes);
4625
4626   bool HaveModules = false;
4627   RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4628
4629   // -faccess-control is default.
4630   if (Args.hasFlag(options::OPT_fno_access_control,
4631                    options::OPT_faccess_control, false))
4632     CmdArgs.push_back("-fno-access-control");
4633
4634   // -felide-constructors is the default.
4635   if (Args.hasFlag(options::OPT_fno_elide_constructors,
4636                    options::OPT_felide_constructors, false))
4637     CmdArgs.push_back("-fno-elide-constructors");
4638
4639   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4640
4641   if (KernelOrKext || (types::isCXX(InputType) &&
4642                        (RTTIMode == ToolChain::RM_Disabled)))
4643     CmdArgs.push_back("-fno-rtti");
4644
4645   // -fshort-enums=0 is default for all architectures except Hexagon.
4646   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4647                    TC.getArch() == llvm::Triple::hexagon))
4648     CmdArgs.push_back("-fshort-enums");
4649
4650   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4651
4652   // -fuse-cxa-atexit is default.
4653   if (!Args.hasFlag(
4654           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4655           !RawTriple.isOSWindows() &&
4656               RawTriple.getOS() != llvm::Triple::Solaris &&
4657               TC.getArch() != llvm::Triple::xcore &&
4658               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4659                RawTriple.hasEnvironment())) ||
4660       KernelOrKext)
4661     CmdArgs.push_back("-fno-use-cxa-atexit");
4662
4663   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4664                    options::OPT_fno_register_global_dtors_with_atexit,
4665                    RawTriple.isOSDarwin() && !KernelOrKext))
4666     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4667
4668   // -fms-extensions=0 is default.
4669   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4670                    IsWindowsMSVC))
4671     CmdArgs.push_back("-fms-extensions");
4672
4673   // -fno-use-line-directives is default.
4674   if (Args.hasFlag(options::OPT_fuse_line_directives,
4675                    options::OPT_fno_use_line_directives, false))
4676     CmdArgs.push_back("-fuse-line-directives");
4677
4678   // -fms-compatibility=0 is default.
4679   if (Args.hasFlag(options::OPT_fms_compatibility,
4680                    options::OPT_fno_ms_compatibility,
4681                    (IsWindowsMSVC &&
4682                     Args.hasFlag(options::OPT_fms_extensions,
4683                                  options::OPT_fno_ms_extensions, true))))
4684     CmdArgs.push_back("-fms-compatibility");
4685
4686   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4687   if (!MSVT.empty())
4688     CmdArgs.push_back(
4689         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4690
4691   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4692   if (ImplyVCPPCXXVer) {
4693     StringRef LanguageStandard;
4694     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4695       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4696                              .Case("c++14", "-std=c++14")
4697                              .Case("c++17", "-std=c++17")
4698                              .Case("c++latest", "-std=c++2a")
4699                              .Default("");
4700       if (LanguageStandard.empty())
4701         D.Diag(clang::diag::warn_drv_unused_argument)
4702             << StdArg->getAsString(Args);
4703     }
4704
4705     if (LanguageStandard.empty()) {
4706       if (IsMSVC2015Compatible)
4707         LanguageStandard = "-std=c++14";
4708       else
4709         LanguageStandard = "-std=c++11";
4710     }
4711
4712     CmdArgs.push_back(LanguageStandard.data());
4713   }
4714
4715   // -fno-borland-extensions is default.
4716   if (Args.hasFlag(options::OPT_fborland_extensions,
4717                    options::OPT_fno_borland_extensions, false))
4718     CmdArgs.push_back("-fborland-extensions");
4719
4720   // -fno-declspec is default, except for PS4.
4721   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4722                    RawTriple.isPS4()))
4723     CmdArgs.push_back("-fdeclspec");
4724   else if (Args.hasArg(options::OPT_fno_declspec))
4725     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4726
4727   // -fthreadsafe-static is default, except for MSVC compatibility versions less
4728   // than 19.
4729   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4730                     options::OPT_fno_threadsafe_statics,
4731                     !IsWindowsMSVC || IsMSVC2015Compatible))
4732     CmdArgs.push_back("-fno-threadsafe-statics");
4733
4734   // -fno-delayed-template-parsing is default, except when targeting MSVC.
4735   // Many old Windows SDK versions require this to parse.
4736   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4737   // compiler. We should be able to disable this by default at some point.
4738   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4739                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4740     CmdArgs.push_back("-fdelayed-template-parsing");
4741
4742   // -fgnu-keywords default varies depending on language; only pass if
4743   // specified.
4744   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4745                                options::OPT_fno_gnu_keywords))
4746     A->render(Args, CmdArgs);
4747
4748   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4749                    false))
4750     CmdArgs.push_back("-fgnu89-inline");
4751
4752   if (Args.hasArg(options::OPT_fno_inline))
4753     CmdArgs.push_back("-fno-inline");
4754
4755   if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4756                                        options::OPT_finline_hint_functions,
4757                                        options::OPT_fno_inline_functions))
4758     InlineArg->render(Args, CmdArgs);
4759
4760   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4761                   options::OPT_fno_experimental_new_pass_manager);
4762
4763   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4764   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4765                     Input, CmdArgs);
4766
4767   if (Args.hasFlag(options::OPT_fapplication_extension,
4768                    options::OPT_fno_application_extension, false))
4769     CmdArgs.push_back("-fapplication-extension");
4770
4771   // Handle GCC-style exception args.
4772   if (!C.getDriver().IsCLMode())
4773     addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4774
4775   // Handle exception personalities
4776   Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4777                            options::OPT_fseh_exceptions,
4778                            options::OPT_fdwarf_exceptions);
4779   if (A) {
4780     const Option &Opt = A->getOption();
4781     if (Opt.matches(options::OPT_fsjlj_exceptions))
4782       CmdArgs.push_back("-fsjlj-exceptions");
4783     if (Opt.matches(options::OPT_fseh_exceptions))
4784       CmdArgs.push_back("-fseh-exceptions");
4785     if (Opt.matches(options::OPT_fdwarf_exceptions))
4786       CmdArgs.push_back("-fdwarf-exceptions");
4787   } else {
4788     switch (TC.GetExceptionModel(Args)) {
4789     default:
4790       break;
4791     case llvm::ExceptionHandling::DwarfCFI:
4792       CmdArgs.push_back("-fdwarf-exceptions");
4793       break;
4794     case llvm::ExceptionHandling::SjLj:
4795       CmdArgs.push_back("-fsjlj-exceptions");
4796       break;
4797     case llvm::ExceptionHandling::WinEH:
4798       CmdArgs.push_back("-fseh-exceptions");
4799       break;
4800     }
4801   }
4802
4803   // C++ "sane" operator new.
4804   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4805                     options::OPT_fno_assume_sane_operator_new))
4806     CmdArgs.push_back("-fno-assume-sane-operator-new");
4807
4808   // -frelaxed-template-template-args is off by default, as it is a severe
4809   // breaking change until a corresponding change to template partial ordering
4810   // is provided.
4811   if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4812                    options::OPT_fno_relaxed_template_template_args, false))
4813     CmdArgs.push_back("-frelaxed-template-template-args");
4814
4815   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4816   // most platforms.
4817   if (Args.hasFlag(options::OPT_fsized_deallocation,
4818                    options::OPT_fno_sized_deallocation, false))
4819     CmdArgs.push_back("-fsized-deallocation");
4820
4821   // -faligned-allocation is on by default in C++17 onwards and otherwise off
4822   // by default.
4823   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4824                                options::OPT_fno_aligned_allocation,
4825                                options::OPT_faligned_new_EQ)) {
4826     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4827       CmdArgs.push_back("-fno-aligned-allocation");
4828     else
4829       CmdArgs.push_back("-faligned-allocation");
4830   }
4831
4832   // The default new alignment can be specified using a dedicated option or via
4833   // a GCC-compatible option that also turns on aligned allocation.
4834   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4835                                options::OPT_faligned_new_EQ))
4836     CmdArgs.push_back(
4837         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4838
4839   // -fconstant-cfstrings is default, and may be subject to argument translation
4840   // on Darwin.
4841   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4842                     options::OPT_fno_constant_cfstrings) ||
4843       !Args.hasFlag(options::OPT_mconstant_cfstrings,
4844                     options::OPT_mno_constant_cfstrings))
4845     CmdArgs.push_back("-fno-constant-cfstrings");
4846
4847   // -fno-pascal-strings is default, only pass non-default.
4848   if (Args.hasFlag(options::OPT_fpascal_strings,
4849                    options::OPT_fno_pascal_strings, false))
4850     CmdArgs.push_back("-fpascal-strings");
4851
4852   // Honor -fpack-struct= and -fpack-struct, if given. Note that
4853   // -fno-pack-struct doesn't apply to -fpack-struct=.
4854   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4855     std::string PackStructStr = "-fpack-struct=";
4856     PackStructStr += A->getValue();
4857     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4858   } else if (Args.hasFlag(options::OPT_fpack_struct,
4859                           options::OPT_fno_pack_struct, false)) {
4860     CmdArgs.push_back("-fpack-struct=1");
4861   }
4862
4863   // Handle -fmax-type-align=N and -fno-type-align
4864   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4865   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4866     if (!SkipMaxTypeAlign) {
4867       std::string MaxTypeAlignStr = "-fmax-type-align=";
4868       MaxTypeAlignStr += A->getValue();
4869       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4870     }
4871   } else if (RawTriple.isOSDarwin()) {
4872     if (!SkipMaxTypeAlign) {
4873       std::string MaxTypeAlignStr = "-fmax-type-align=16";
4874       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4875     }
4876   }
4877
4878   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4879     CmdArgs.push_back("-Qn");
4880
4881   // -fcommon is the default unless compiling kernel code or the target says so
4882   bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4883   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4884                     !NoCommonDefault))
4885     CmdArgs.push_back("-fno-common");
4886
4887   // -fsigned-bitfields is default, and clang doesn't yet support
4888   // -funsigned-bitfields.
4889   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4890                     options::OPT_funsigned_bitfields))
4891     D.Diag(diag::warn_drv_clang_unsupported)
4892         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4893
4894   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4895   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4896     D.Diag(diag::err_drv_clang_unsupported)
4897         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4898
4899   // -finput_charset=UTF-8 is default. Reject others
4900   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4901     StringRef value = inputCharset->getValue();
4902     if (!value.equals_lower("utf-8"))
4903       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4904                                           << value;
4905   }
4906
4907   // -fexec_charset=UTF-8 is default. Reject others
4908   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4909     StringRef value = execCharset->getValue();
4910     if (!value.equals_lower("utf-8"))
4911       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4912                                           << value;
4913   }
4914
4915   RenderDiagnosticsOptions(D, Args, CmdArgs);
4916
4917   // -fno-asm-blocks is default.
4918   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4919                    false))
4920     CmdArgs.push_back("-fasm-blocks");
4921
4922   // -fgnu-inline-asm is default.
4923   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4924                     options::OPT_fno_gnu_inline_asm, true))
4925     CmdArgs.push_back("-fno-gnu-inline-asm");
4926
4927   // Enable vectorization per default according to the optimization level
4928   // selected. For optimization levels that want vectorization we use the alias
4929   // option to simplify the hasFlag logic.
4930   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4931   OptSpecifier VectorizeAliasOption =
4932       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4933   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4934                    options::OPT_fno_vectorize, EnableVec))
4935     CmdArgs.push_back("-vectorize-loops");
4936
4937   // -fslp-vectorize is enabled based on the optimization level selected.
4938   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4939   OptSpecifier SLPVectAliasOption =
4940       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4941   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4942                    options::OPT_fno_slp_vectorize, EnableSLPVec))
4943     CmdArgs.push_back("-vectorize-slp");
4944
4945   ParseMPreferVectorWidth(D, Args, CmdArgs);
4946
4947   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4948     A->render(Args, CmdArgs);
4949
4950   if (Arg *A = Args.getLastArg(
4951           options::OPT_fsanitize_undefined_strip_path_components_EQ))
4952     A->render(Args, CmdArgs);
4953
4954   // -fdollars-in-identifiers default varies depending on platform and
4955   // language; only pass if specified.
4956   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4957                                options::OPT_fno_dollars_in_identifiers)) {
4958     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4959       CmdArgs.push_back("-fdollars-in-identifiers");
4960     else
4961       CmdArgs.push_back("-fno-dollars-in-identifiers");
4962   }
4963
4964   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4965   // practical purposes.
4966   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4967                                options::OPT_fno_unit_at_a_time)) {
4968     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4969       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4970   }
4971
4972   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4973                    options::OPT_fno_apple_pragma_pack, false))
4974     CmdArgs.push_back("-fapple-pragma-pack");
4975
4976   if (Args.hasFlag(options::OPT_fsave_optimization_record,
4977                    options::OPT_foptimization_record_file_EQ,
4978                    options::OPT_fno_save_optimization_record, false)) {
4979     CmdArgs.push_back("-opt-record-file");
4980
4981     const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4982     if (A) {
4983       CmdArgs.push_back(A->getValue());
4984     } else {
4985       SmallString<128> F;
4986
4987       if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4988         if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4989           F = FinalOutput->getValue();
4990       }
4991
4992       if (F.empty()) {
4993         // Use the input filename.
4994         F = llvm::sys::path::stem(Input.getBaseInput());
4995
4996         // If we're compiling for an offload architecture (i.e. a CUDA device),
4997         // we need to make the file name for the device compilation different
4998         // from the host compilation.
4999         if (!JA.isDeviceOffloading(Action::OFK_None) &&
5000             !JA.isDeviceOffloading(Action::OFK_Host)) {
5001           llvm::sys::path::replace_extension(F, "");
5002           F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5003                                                    Triple.normalize());
5004           F += "-";
5005           F += JA.getOffloadingArch();
5006         }
5007       }
5008
5009       llvm::sys::path::replace_extension(F, "opt.yaml");
5010       CmdArgs.push_back(Args.MakeArgString(F));
5011     }
5012   }
5013
5014   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5015                                      options::OPT_fno_rewrite_imports, false);
5016   if (RewriteImports)
5017     CmdArgs.push_back("-frewrite-imports");
5018
5019   // Enable rewrite includes if the user's asked for it or if we're generating
5020   // diagnostics.
5021   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5022   // nice to enable this when doing a crashdump for modules as well.
5023   if (Args.hasFlag(options::OPT_frewrite_includes,
5024                    options::OPT_fno_rewrite_includes, false) ||
5025       (C.isForDiagnostics() && !HaveModules))
5026     CmdArgs.push_back("-frewrite-includes");
5027
5028   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5029   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5030                                options::OPT_traditional_cpp)) {
5031     if (isa<PreprocessJobAction>(JA))
5032       CmdArgs.push_back("-traditional-cpp");
5033     else
5034       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5035   }
5036
5037   Args.AddLastArg(CmdArgs, options::OPT_dM);
5038   Args.AddLastArg(CmdArgs, options::OPT_dD);
5039
5040   // Handle serialized diagnostics.
5041   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5042     CmdArgs.push_back("-serialize-diagnostic-file");
5043     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5044   }
5045
5046   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5047     CmdArgs.push_back("-fretain-comments-from-system-headers");
5048
5049   // Forward -fcomment-block-commands to -cc1.
5050   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5051   // Forward -fparse-all-comments to -cc1.
5052   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5053
5054   // Turn -fplugin=name.so into -load name.so
5055   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5056     CmdArgs.push_back("-load");
5057     CmdArgs.push_back(A->getValue());
5058     A->claim();
5059   }
5060
5061   // Setup statistics file output.
5062   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5063   if (!StatsFile.empty())
5064     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
5065
5066   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5067   // parser.
5068   // -finclude-default-header flag is for preprocessor,
5069   // do not pass it to other cc1 commands when save-temps is enabled
5070   if (C.getDriver().isSaveTempsEnabled() &&
5071       !isa<PreprocessJobAction>(JA)) {
5072     for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5073       Arg->claim();
5074       if (StringRef(Arg->getValue()) != "-finclude-default-header")
5075         CmdArgs.push_back(Arg->getValue());
5076     }
5077   }
5078   else {
5079     Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5080   }
5081   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5082     A->claim();
5083
5084     // We translate this by hand to the -cc1 argument, since nightly test uses
5085     // it and developers have been trained to spell it with -mllvm. Both
5086     // spellings are now deprecated and should be removed.
5087     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5088       CmdArgs.push_back("-disable-llvm-optzns");
5089     } else {
5090       A->render(Args, CmdArgs);
5091     }
5092   }
5093
5094   // With -save-temps, we want to save the unoptimized bitcode output from the
5095   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5096   // by the frontend.
5097   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5098   // has slightly different breakdown between stages.
5099   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5100   // pristine IR generated by the frontend. Ideally, a new compile action should
5101   // be added so both IR can be captured.
5102   if (C.getDriver().isSaveTempsEnabled() &&
5103       !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5104       isa<CompileJobAction>(JA))
5105     CmdArgs.push_back("-disable-llvm-passes");
5106
5107   if (Output.getType() == types::TY_Dependencies) {
5108     // Handled with other dependency code.
5109   } else if (Output.isFilename()) {
5110     CmdArgs.push_back("-o");
5111     CmdArgs.push_back(Output.getFilename());
5112   } else {
5113     assert(Output.isNothing() && "Invalid output.");
5114   }
5115
5116   addDashXForInput(Args, Input, CmdArgs);
5117
5118   ArrayRef<InputInfo> FrontendInputs = Input;
5119   if (IsHeaderModulePrecompile)
5120     FrontendInputs = ModuleHeaderInputs;
5121   else if (Input.isNothing())
5122     FrontendInputs = {};
5123
5124   for (const InputInfo &Input : FrontendInputs) {
5125     if (Input.isFilename())
5126       CmdArgs.push_back(Input.getFilename());
5127     else
5128       Input.getInputArg().renderAsInput(Args, CmdArgs);
5129   }
5130
5131   Args.AddAllArgs(CmdArgs, options::OPT_undef);
5132
5133   const char *Exec = D.getClangProgramPath();
5134
5135   // Optionally embed the -cc1 level arguments into the debug info or a
5136   // section, for build analysis.
5137   // Also record command line arguments into the debug info if
5138   // -grecord-gcc-switches options is set on.
5139   // By default, -gno-record-gcc-switches is set on and no recording.
5140   auto GRecordSwitches =
5141       Args.hasFlag(options::OPT_grecord_command_line,
5142                    options::OPT_gno_record_command_line, false);
5143   auto FRecordSwitches =
5144       Args.hasFlag(options::OPT_frecord_command_line,
5145                    options::OPT_fno_record_command_line, false);
5146   if (FRecordSwitches && !Triple.isOSBinFormatELF())
5147     D.Diag(diag::err_drv_unsupported_opt_for_target)
5148         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5149         << TripleStr;
5150   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
5151     ArgStringList OriginalArgs;
5152     for (const auto &Arg : Args)
5153       Arg->render(Args, OriginalArgs);
5154
5155     SmallString<256> Flags;
5156     Flags += Exec;
5157     for (const char *OriginalArg : OriginalArgs) {
5158       SmallString<128> EscapedArg;
5159       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5160       Flags += " ";
5161       Flags += EscapedArg;
5162     }
5163     auto FlagsArgString = Args.MakeArgString(Flags);
5164     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5165       CmdArgs.push_back("-dwarf-debug-flags");
5166       CmdArgs.push_back(FlagsArgString);
5167     }
5168     if (FRecordSwitches) {
5169       CmdArgs.push_back("-record-command-line");
5170       CmdArgs.push_back(FlagsArgString);
5171     }
5172   }
5173
5174   // Host-side cuda compilation receives all device-side outputs in a single
5175   // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5176   if ((IsCuda || IsHIP) && CudaDeviceInput) {
5177       CmdArgs.push_back("-fcuda-include-gpubinary");
5178       CmdArgs.push_back(CudaDeviceInput->getFilename());
5179       if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5180         CmdArgs.push_back("-fgpu-rdc");
5181   }
5182
5183   if (IsCuda) {
5184     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5185                      options::OPT_fno_cuda_short_ptr, false))
5186       CmdArgs.push_back("-fcuda-short-ptr");
5187   }
5188
5189   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5190   // to specify the result of the compile phase on the host, so the meaningful
5191   // device declarations can be identified. Also, -fopenmp-is-device is passed
5192   // along to tell the frontend that it is generating code for a device, so that
5193   // only the relevant declarations are emitted.
5194   if (IsOpenMPDevice) {
5195     CmdArgs.push_back("-fopenmp-is-device");
5196     if (OpenMPDeviceInput) {
5197       CmdArgs.push_back("-fopenmp-host-ir-file-path");
5198       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
5199     }
5200   }
5201
5202   // For all the host OpenMP offloading compile jobs we need to pass the targets
5203   // information using -fopenmp-targets= option.
5204   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
5205     SmallString<128> TargetInfo("-fopenmp-targets=");
5206
5207     Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5208     assert(Tgts && Tgts->getNumValues() &&
5209            "OpenMP offloading has to have targets specified.");
5210     for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5211       if (i)
5212         TargetInfo += ',';
5213       // We need to get the string from the triple because it may be not exactly
5214       // the same as the one we get directly from the arguments.
5215       llvm::Triple T(Tgts->getValue(i));
5216       TargetInfo += T.getTriple();
5217     }
5218     CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5219   }
5220
5221   bool WholeProgramVTables =
5222       Args.hasFlag(options::OPT_fwhole_program_vtables,
5223                    options::OPT_fno_whole_program_vtables, false);
5224   if (WholeProgramVTables) {
5225     if (!D.isUsingLTO())
5226       D.Diag(diag::err_drv_argument_only_allowed_with)
5227           << "-fwhole-program-vtables"
5228           << "-flto";
5229     CmdArgs.push_back("-fwhole-program-vtables");
5230   }
5231
5232   bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5233   bool SplitLTOUnit =
5234       Args.hasFlag(options::OPT_fsplit_lto_unit,
5235                    options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5236   if (RequiresSplitLTOUnit && !SplitLTOUnit)
5237     D.Diag(diag::err_drv_argument_not_allowed_with)
5238         << "-fno-split-lto-unit"
5239         << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5240   if (SplitLTOUnit)
5241     CmdArgs.push_back("-fsplit-lto-unit");
5242
5243   if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5244                                options::OPT_fno_experimental_isel)) {
5245     CmdArgs.push_back("-mllvm");
5246     if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5247       CmdArgs.push_back("-global-isel=1");
5248
5249       // GISel is on by default on AArch64 -O0, so don't bother adding
5250       // the fallback remarks for it. Other combinations will add a warning of
5251       // some kind.
5252       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5253       bool IsOptLevelSupported = false;
5254
5255       Arg *A = Args.getLastArg(options::OPT_O_Group);
5256       if (Triple.getArch() == llvm::Triple::aarch64) {
5257         if (!A || A->getOption().matches(options::OPT_O0))
5258           IsOptLevelSupported = true;
5259       }
5260       if (!IsArchSupported || !IsOptLevelSupported) {
5261         CmdArgs.push_back("-mllvm");
5262         CmdArgs.push_back("-global-isel-abort=2");
5263
5264         if (!IsArchSupported)
5265           D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5266         else
5267           D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5268       }
5269     } else {
5270       CmdArgs.push_back("-global-isel=0");
5271     }
5272   }
5273
5274   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5275                                options::OPT_fno_force_enable_int128)) {
5276     if (A->getOption().matches(options::OPT_fforce_enable_int128))
5277       CmdArgs.push_back("-fforce-enable-int128");
5278   }
5279
5280   if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5281                    options::OPT_fno_complete_member_pointers, false))
5282     CmdArgs.push_back("-fcomplete-member-pointers");
5283
5284   if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5285                     options::OPT_fno_cxx_static_destructors, true))
5286     CmdArgs.push_back("-fno-c++-static-destructors");
5287
5288   if (Arg *A = Args.getLastArg(options::OPT_moutline,
5289                                options::OPT_mno_outline)) {
5290     if (A->getOption().matches(options::OPT_moutline)) {
5291       // We only support -moutline in AArch64 right now. If we're not compiling
5292       // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5293       // proper mllvm flags.
5294       if (Triple.getArch() != llvm::Triple::aarch64) {
5295         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5296       } else {
5297           CmdArgs.push_back("-mllvm");
5298           CmdArgs.push_back("-enable-machine-outliner");
5299       }
5300     } else {
5301       // Disable all outlining behaviour.
5302       CmdArgs.push_back("-mllvm");
5303       CmdArgs.push_back("-enable-machine-outliner=never");
5304     }
5305   }
5306
5307   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5308                    (TC.getTriple().isOSBinFormatELF() ||
5309                     TC.getTriple().isOSBinFormatCOFF()) &&
5310                       !TC.getTriple().isPS4() &&
5311                       !TC.getTriple().isOSNetBSD() &&
5312                       !Distro(D.getVFS()).IsGentoo() &&
5313                       !TC.getTriple().isAndroid() &&
5314                        TC.useIntegratedAs()))
5315     CmdArgs.push_back("-faddrsig");
5316
5317   // Finally add the compile command to the compilation.
5318   if (Args.hasArg(options::OPT__SLASH_fallback) &&
5319       Output.getType() == types::TY_Object &&
5320       (InputType == types::TY_C || InputType == types::TY_CXX)) {
5321     auto CLCommand =
5322         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5323     C.addCommand(llvm::make_unique<FallbackCommand>(
5324         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5325   } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5326              isa<PrecompileJobAction>(JA)) {
5327     // In /fallback builds, run the main compilation even if the pch generation
5328     // fails, so that the main compilation's fallback to cl.exe runs.
5329     C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5330                                                         CmdArgs, Inputs));
5331   } else {
5332     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5333   }
5334
5335   // Make the compile command echo its inputs for /showFilenames.
5336   if (Output.getType() == types::TY_Object &&
5337       Args.hasFlag(options::OPT__SLASH_showFilenames,
5338                    options::OPT__SLASH_showFilenames_, false)) {
5339     C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5340   }
5341
5342   if (Arg *A = Args.getLastArg(options::OPT_pg))
5343     if (!shouldUseFramePointer(Args, Triple))
5344       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5345                                                       << A->getAsString(Args);
5346
5347   // Claim some arguments which clang supports automatically.
5348
5349   // -fpch-preprocess is used with gcc to add a special marker in the output to
5350   // include the PCH file.
5351   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5352
5353   // Claim some arguments which clang doesn't support, but we don't
5354   // care to warn the user about.
5355   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5356   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5357
5358   // Disable warnings for clang -E -emit-llvm foo.c
5359   Args.ClaimAllArgs(options::OPT_emit_llvm);
5360 }
5361
5362 Clang::Clang(const ToolChain &TC)
5363     // CAUTION! The first constructor argument ("clang") is not arbitrary,
5364     // as it is for other tools. Some operations on a Tool actually test
5365     // whether that tool is Clang based on the Tool's Name as a string.
5366     : Tool("clang", "clang frontend", TC, RF_Full) {}
5367
5368 Clang::~Clang() {}
5369
5370 /// Add options related to the Objective-C runtime/ABI.
5371 ///
5372 /// Returns true if the runtime is non-fragile.
5373 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5374                                       ArgStringList &cmdArgs,
5375                                       RewriteKind rewriteKind) const {
5376   // Look for the controlling runtime option.
5377   Arg *runtimeArg =
5378       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5379                       options::OPT_fobjc_runtime_EQ);
5380
5381   // Just forward -fobjc-runtime= to the frontend.  This supercedes
5382   // options about fragility.
5383   if (runtimeArg &&
5384       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5385     ObjCRuntime runtime;
5386     StringRef value = runtimeArg->getValue();
5387     if (runtime.tryParse(value)) {
5388       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5389           << value;
5390     }
5391     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5392         (runtime.getVersion() >= VersionTuple(2, 0)))
5393       if (!getToolChain().getTriple().isOSBinFormatELF() &&
5394           !getToolChain().getTriple().isOSBinFormatCOFF()) {
5395         getToolChain().getDriver().Diag(
5396             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5397           << runtime.getVersion().getMajor();
5398       }
5399
5400     runtimeArg->render(args, cmdArgs);
5401     return runtime;
5402   }
5403
5404   // Otherwise, we'll need the ABI "version".  Version numbers are
5405   // slightly confusing for historical reasons:
5406   //   1 - Traditional "fragile" ABI
5407   //   2 - Non-fragile ABI, version 1
5408   //   3 - Non-fragile ABI, version 2
5409   unsigned objcABIVersion = 1;
5410   // If -fobjc-abi-version= is present, use that to set the version.
5411   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5412     StringRef value = abiArg->getValue();
5413     if (value == "1")
5414       objcABIVersion = 1;
5415     else if (value == "2")
5416       objcABIVersion = 2;
5417     else if (value == "3")
5418       objcABIVersion = 3;
5419     else
5420       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5421   } else {
5422     // Otherwise, determine if we are using the non-fragile ABI.
5423     bool nonFragileABIIsDefault =
5424         (rewriteKind == RK_NonFragile ||
5425          (rewriteKind == RK_None &&
5426           getToolChain().IsObjCNonFragileABIDefault()));
5427     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5428                      options::OPT_fno_objc_nonfragile_abi,
5429                      nonFragileABIIsDefault)) {
5430 // Determine the non-fragile ABI version to use.
5431 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5432       unsigned nonFragileABIVersion = 1;
5433 #else
5434       unsigned nonFragileABIVersion = 2;
5435 #endif
5436
5437       if (Arg *abiArg =
5438               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5439         StringRef value = abiArg->getValue();
5440         if (value == "1")
5441           nonFragileABIVersion = 1;
5442         else if (value == "2")
5443           nonFragileABIVersion = 2;
5444         else
5445           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5446               << value;
5447       }
5448
5449       objcABIVersion = 1 + nonFragileABIVersion;
5450     } else {
5451       objcABIVersion = 1;
5452     }
5453   }
5454
5455   // We don't actually care about the ABI version other than whether
5456   // it's non-fragile.
5457   bool isNonFragile = objcABIVersion != 1;
5458
5459   // If we have no runtime argument, ask the toolchain for its default runtime.
5460   // However, the rewriter only really supports the Mac runtime, so assume that.
5461   ObjCRuntime runtime;
5462   if (!runtimeArg) {
5463     switch (rewriteKind) {
5464     case RK_None:
5465       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5466       break;
5467     case RK_Fragile:
5468       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5469       break;
5470     case RK_NonFragile:
5471       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5472       break;
5473     }
5474
5475     // -fnext-runtime
5476   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5477     // On Darwin, make this use the default behavior for the toolchain.
5478     if (getToolChain().getTriple().isOSDarwin()) {
5479       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5480
5481       // Otherwise, build for a generic macosx port.
5482     } else {
5483       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5484     }
5485
5486     // -fgnu-runtime
5487   } else {
5488     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5489     // Legacy behaviour is to target the gnustep runtime if we are in
5490     // non-fragile mode or the GCC runtime in fragile mode.
5491     if (isNonFragile)
5492       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5493     else
5494       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5495   }
5496
5497   cmdArgs.push_back(
5498       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5499   return runtime;
5500 }
5501
5502 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5503   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5504   I += HaveDash;
5505   return !HaveDash;
5506 }
5507
5508 namespace {
5509 struct EHFlags {
5510   bool Synch = false;
5511   bool Asynch = false;
5512   bool NoUnwindC = false;
5513 };
5514 } // end anonymous namespace
5515
5516 /// /EH controls whether to run destructor cleanups when exceptions are
5517 /// thrown.  There are three modifiers:
5518 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5519 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5520 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5521 /// - c: Assume that extern "C" functions are implicitly nounwind.
5522 /// The default is /EHs-c-, meaning cleanups are disabled.
5523 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5524   EHFlags EH;
5525
5526   std::vector<std::string> EHArgs =
5527       Args.getAllArgValues(options::OPT__SLASH_EH);
5528   for (auto EHVal : EHArgs) {
5529     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5530       switch (EHVal[I]) {
5531       case 'a':
5532         EH.Asynch = maybeConsumeDash(EHVal, I);
5533         if (EH.Asynch)
5534           EH.Synch = false;
5535         continue;
5536       case 'c':
5537         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5538         continue;
5539       case 's':
5540         EH.Synch = maybeConsumeDash(EHVal, I);
5541         if (EH.Synch)
5542           EH.Asynch = false;
5543         continue;
5544       default:
5545         break;
5546       }
5547       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5548       break;
5549     }
5550   }
5551   // The /GX, /GX- flags are only processed if there are not /EH flags.
5552   // The default is that /GX is not specified.
5553   if (EHArgs.empty() &&
5554       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5555                    /*default=*/false)) {
5556     EH.Synch = true;
5557     EH.NoUnwindC = true;
5558   }
5559
5560   return EH;
5561 }
5562
5563 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5564                            ArgStringList &CmdArgs,
5565                            codegenoptions::DebugInfoKind *DebugInfoKind,
5566                            bool *EmitCodeView) const {
5567   unsigned RTOptionID = options::OPT__SLASH_MT;
5568
5569   if (Args.hasArg(options::OPT__SLASH_LDd))
5570     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5571     // but defining _DEBUG is sticky.
5572     RTOptionID = options::OPT__SLASH_MTd;
5573
5574   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5575     RTOptionID = A->getOption().getID();
5576
5577   StringRef FlagForCRT;
5578   switch (RTOptionID) {
5579   case options::OPT__SLASH_MD:
5580     if (Args.hasArg(options::OPT__SLASH_LDd))
5581       CmdArgs.push_back("-D_DEBUG");
5582     CmdArgs.push_back("-D_MT");
5583     CmdArgs.push_back("-D_DLL");
5584     FlagForCRT = "--dependent-lib=msvcrt";
5585     break;
5586   case options::OPT__SLASH_MDd:
5587     CmdArgs.push_back("-D_DEBUG");
5588     CmdArgs.push_back("-D_MT");
5589     CmdArgs.push_back("-D_DLL");
5590     FlagForCRT = "--dependent-lib=msvcrtd";
5591     break;
5592   case options::OPT__SLASH_MT:
5593     if (Args.hasArg(options::OPT__SLASH_LDd))
5594       CmdArgs.push_back("-D_DEBUG");
5595     CmdArgs.push_back("-D_MT");
5596     CmdArgs.push_back("-flto-visibility-public-std");
5597     FlagForCRT = "--dependent-lib=libcmt";
5598     break;
5599   case options::OPT__SLASH_MTd:
5600     CmdArgs.push_back("-D_DEBUG");
5601     CmdArgs.push_back("-D_MT");
5602     CmdArgs.push_back("-flto-visibility-public-std");
5603     FlagForCRT = "--dependent-lib=libcmtd";
5604     break;
5605   default:
5606     llvm_unreachable("Unexpected option ID.");
5607   }
5608
5609   if (Args.hasArg(options::OPT__SLASH_Zl)) {
5610     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5611   } else {
5612     CmdArgs.push_back(FlagForCRT.data());
5613
5614     // This provides POSIX compatibility (maps 'open' to '_open'), which most
5615     // users want.  The /Za flag to cl.exe turns this off, but it's not
5616     // implemented in clang.
5617     CmdArgs.push_back("--dependent-lib=oldnames");
5618   }
5619
5620   if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5621     A->render(Args, CmdArgs);
5622
5623   // This controls whether or not we emit RTTI data for polymorphic types.
5624   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5625                    /*default=*/false))
5626     CmdArgs.push_back("-fno-rtti-data");
5627
5628   // This controls whether or not we emit stack-protector instrumentation.
5629   // In MSVC, Buffer Security Check (/GS) is on by default.
5630   if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5631                    /*default=*/true)) {
5632     CmdArgs.push_back("-stack-protector");
5633     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5634   }
5635
5636   // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5637   if (Arg *DebugInfoArg =
5638           Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5639                           options::OPT_gline_tables_only)) {
5640     *EmitCodeView = true;
5641     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5642       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5643     else
5644       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5645   } else {
5646     *EmitCodeView = false;
5647   }
5648
5649   const Driver &D = getToolChain().getDriver();
5650   EHFlags EH = parseClangCLEHFlags(D, Args);
5651   if (EH.Synch || EH.Asynch) {
5652     if (types::isCXX(InputType))
5653       CmdArgs.push_back("-fcxx-exceptions");
5654     CmdArgs.push_back("-fexceptions");
5655   }
5656   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5657     CmdArgs.push_back("-fexternc-nounwind");
5658
5659   // /EP should expand to -E -P.
5660   if (Args.hasArg(options::OPT__SLASH_EP)) {
5661     CmdArgs.push_back("-E");
5662     CmdArgs.push_back("-P");
5663   }
5664
5665   unsigned VolatileOptionID;
5666   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5667       getToolChain().getArch() == llvm::Triple::x86)
5668     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5669   else
5670     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5671
5672   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5673     VolatileOptionID = A->getOption().getID();
5674
5675   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5676     CmdArgs.push_back("-fms-volatile");
5677
5678  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5679                   options::OPT__SLASH_Zc_dllexportInlines,
5680                   false)) {
5681    if (Args.hasArg(options::OPT__SLASH_fallback)) {
5682      D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5683    } else {
5684     CmdArgs.push_back("-fno-dllexport-inlines");
5685    }
5686  }
5687
5688   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5689   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5690   if (MostGeneralArg && BestCaseArg)
5691     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5692         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5693
5694   if (MostGeneralArg) {
5695     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5696     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5697     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5698
5699     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5700     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5701     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5702       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5703           << FirstConflict->getAsString(Args)
5704           << SecondConflict->getAsString(Args);
5705
5706     if (SingleArg)
5707       CmdArgs.push_back("-fms-memptr-rep=single");
5708     else if (MultipleArg)
5709       CmdArgs.push_back("-fms-memptr-rep=multiple");
5710     else
5711       CmdArgs.push_back("-fms-memptr-rep=virtual");
5712   }
5713
5714   // Parse the default calling convention options.
5715   if (Arg *CCArg =
5716           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5717                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5718                           options::OPT__SLASH_Gregcall)) {
5719     unsigned DCCOptId = CCArg->getOption().getID();
5720     const char *DCCFlag = nullptr;
5721     bool ArchSupported = true;
5722     llvm::Triple::ArchType Arch = getToolChain().getArch();
5723     switch (DCCOptId) {
5724     case options::OPT__SLASH_Gd:
5725       DCCFlag = "-fdefault-calling-conv=cdecl";
5726       break;
5727     case options::OPT__SLASH_Gr:
5728       ArchSupported = Arch == llvm::Triple::x86;
5729       DCCFlag = "-fdefault-calling-conv=fastcall";
5730       break;
5731     case options::OPT__SLASH_Gz:
5732       ArchSupported = Arch == llvm::Triple::x86;
5733       DCCFlag = "-fdefault-calling-conv=stdcall";
5734       break;
5735     case options::OPT__SLASH_Gv:
5736       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5737       DCCFlag = "-fdefault-calling-conv=vectorcall";
5738       break;
5739     case options::OPT__SLASH_Gregcall:
5740       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5741       DCCFlag = "-fdefault-calling-conv=regcall";
5742       break;
5743     }
5744
5745     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5746     if (ArchSupported && DCCFlag)
5747       CmdArgs.push_back(DCCFlag);
5748   }
5749
5750   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5751     A->render(Args, CmdArgs);
5752
5753   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5754     CmdArgs.push_back("-fdiagnostics-format");
5755     if (Args.hasArg(options::OPT__SLASH_fallback))
5756       CmdArgs.push_back("msvc-fallback");
5757     else
5758       CmdArgs.push_back("msvc");
5759   }
5760
5761   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5762     SmallVector<StringRef, 1> SplitArgs;
5763     StringRef(A->getValue()).split(SplitArgs, ",");
5764     bool Instrument = false;
5765     bool NoChecks = false;
5766     for (StringRef Arg : SplitArgs) {
5767       if (Arg.equals_lower("cf"))
5768         Instrument = true;
5769       else if (Arg.equals_lower("cf-"))
5770         Instrument = false;
5771       else if (Arg.equals_lower("nochecks"))
5772         NoChecks = true;
5773       else if (Arg.equals_lower("nochecks-"))
5774         NoChecks = false;
5775       else
5776         D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5777     }
5778     // Currently there's no support emitting CFG instrumentation; the flag only
5779     // emits the table of address-taken functions.
5780     if (Instrument || NoChecks)
5781       CmdArgs.push_back("-cfguard");
5782   }
5783 }
5784
5785 visualstudio::Compiler *Clang::getCLFallback() const {
5786   if (!CLFallback)
5787     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5788   return CLFallback.get();
5789 }
5790
5791
5792 const char *Clang::getBaseInputName(const ArgList &Args,
5793                                     const InputInfo &Input) {
5794   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5795 }
5796
5797 const char *Clang::getBaseInputStem(const ArgList &Args,
5798                                     const InputInfoList &Inputs) {
5799   const char *Str = getBaseInputName(Args, Inputs[0]);
5800
5801   if (const char *End = strrchr(Str, '.'))
5802     return Args.MakeArgString(std::string(Str, End));
5803
5804   return Str;
5805 }
5806
5807 const char *Clang::getDependencyFileName(const ArgList &Args,
5808                                          const InputInfoList &Inputs) {
5809   // FIXME: Think about this more.
5810   std::string Res;
5811
5812   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5813     std::string Str(OutputOpt->getValue());
5814     Res = Str.substr(0, Str.rfind('.'));
5815   } else {
5816     Res = getBaseInputStem(Args, Inputs);
5817   }
5818   return Args.MakeArgString(Res + ".d");
5819 }
5820
5821 // Begin ClangAs
5822
5823 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5824                                 ArgStringList &CmdArgs) const {
5825   StringRef CPUName;
5826   StringRef ABIName;
5827   const llvm::Triple &Triple = getToolChain().getTriple();
5828   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5829
5830   CmdArgs.push_back("-target-abi");
5831   CmdArgs.push_back(ABIName.data());
5832 }
5833
5834 void ClangAs::AddX86TargetArgs(const ArgList &Args,
5835                                ArgStringList &CmdArgs) const {
5836   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5837     StringRef Value = A->getValue();
5838     if (Value == "intel" || Value == "att") {
5839       CmdArgs.push_back("-mllvm");
5840       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5841     } else {
5842       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5843           << A->getOption().getName() << Value;
5844     }
5845   }
5846 }
5847
5848 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5849                            const InputInfo &Output, const InputInfoList &Inputs,
5850                            const ArgList &Args,
5851                            const char *LinkingOutput) const {
5852   ArgStringList CmdArgs;
5853
5854   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5855   const InputInfo &Input = Inputs[0];
5856
5857   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5858   const std::string &TripleStr = Triple.getTriple();
5859   const auto &D = getToolChain().getDriver();
5860
5861   // Don't warn about "clang -w -c foo.s"
5862   Args.ClaimAllArgs(options::OPT_w);
5863   // and "clang -emit-llvm -c foo.s"
5864   Args.ClaimAllArgs(options::OPT_emit_llvm);
5865
5866   claimNoWarnArgs(Args);
5867
5868   // Invoke ourselves in -cc1as mode.
5869   //
5870   // FIXME: Implement custom jobs for internal actions.
5871   CmdArgs.push_back("-cc1as");
5872
5873   // Add the "effective" target triple.
5874   CmdArgs.push_back("-triple");
5875   CmdArgs.push_back(Args.MakeArgString(TripleStr));
5876
5877   // Set the output mode, we currently only expect to be used as a real
5878   // assembler.
5879   CmdArgs.push_back("-filetype");
5880   CmdArgs.push_back("obj");
5881
5882   // Set the main file name, so that debug info works even with
5883   // -save-temps or preprocessed assembly.
5884   CmdArgs.push_back("-main-file-name");
5885   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5886
5887   // Add the target cpu
5888   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5889   if (!CPU.empty()) {
5890     CmdArgs.push_back("-target-cpu");
5891     CmdArgs.push_back(Args.MakeArgString(CPU));
5892   }
5893
5894   // Add the target features
5895   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5896
5897   // Ignore explicit -force_cpusubtype_ALL option.
5898   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5899
5900   // Pass along any -I options so we get proper .include search paths.
5901   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5902
5903   // Determine the original source input.
5904   const Action *SourceAction = &JA;
5905   while (SourceAction->getKind() != Action::InputClass) {
5906     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5907     SourceAction = SourceAction->getInputs()[0];
5908   }
5909
5910   // Forward -g and handle debug info related flags, assuming we are dealing
5911   // with an actual assembly file.
5912   bool WantDebug = false;
5913   unsigned DwarfVersion = 0;
5914   Args.ClaimAllArgs(options::OPT_g_Group);
5915   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5916     WantDebug = !A->getOption().matches(options::OPT_g0) &&
5917                 !A->getOption().matches(options::OPT_ggdb0);
5918     if (WantDebug)
5919       DwarfVersion = DwarfVersionNum(A->getSpelling());
5920   }
5921   if (DwarfVersion == 0)
5922     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5923
5924   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5925
5926   if (SourceAction->getType() == types::TY_Asm ||
5927       SourceAction->getType() == types::TY_PP_Asm) {
5928     // You might think that it would be ok to set DebugInfoKind outside of
5929     // the guard for source type, however there is a test which asserts
5930     // that some assembler invocation receives no -debug-info-kind,
5931     // and it's not clear whether that test is just overly restrictive.
5932     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5933                                : codegenoptions::NoDebugInfo);
5934     // Add the -fdebug-compilation-dir flag if needed.
5935     addDebugCompDirArg(Args, CmdArgs);
5936
5937     addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5938
5939     // Set the AT_producer to the clang version when using the integrated
5940     // assembler on assembly source files.
5941     CmdArgs.push_back("-dwarf-debug-producer");
5942     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5943
5944     // And pass along -I options
5945     Args.AddAllArgs(CmdArgs, options::OPT_I);
5946   }
5947   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5948                           llvm::DebuggerKind::Default);
5949   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
5950
5951
5952   // Handle -fPIC et al -- the relocation-model affects the assembler
5953   // for some targets.
5954   llvm::Reloc::Model RelocationModel;
5955   unsigned PICLevel;
5956   bool IsPIE;
5957   std::tie(RelocationModel, PICLevel, IsPIE) =
5958       ParsePICArgs(getToolChain(), Args);
5959
5960   const char *RMName = RelocationModelName(RelocationModel);
5961   if (RMName) {
5962     CmdArgs.push_back("-mrelocation-model");
5963     CmdArgs.push_back(RMName);
5964   }
5965
5966   // Optionally embed the -cc1as level arguments into the debug info, for build
5967   // analysis.
5968   if (getToolChain().UseDwarfDebugFlags()) {
5969     ArgStringList OriginalArgs;
5970     for (const auto &Arg : Args)
5971       Arg->render(Args, OriginalArgs);
5972
5973     SmallString<256> Flags;
5974     const char *Exec = getToolChain().getDriver().getClangProgramPath();
5975     Flags += Exec;
5976     for (const char *OriginalArg : OriginalArgs) {
5977       SmallString<128> EscapedArg;
5978       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5979       Flags += " ";
5980       Flags += EscapedArg;
5981     }
5982     CmdArgs.push_back("-dwarf-debug-flags");
5983     CmdArgs.push_back(Args.MakeArgString(Flags));
5984   }
5985
5986   // FIXME: Add -static support, once we have it.
5987
5988   // Add target specific flags.
5989   switch (getToolChain().getArch()) {
5990   default:
5991     break;
5992
5993   case llvm::Triple::mips:
5994   case llvm::Triple::mipsel:
5995   case llvm::Triple::mips64:
5996   case llvm::Triple::mips64el:
5997     AddMIPSTargetArgs(Args, CmdArgs);
5998     break;
5999
6000   case llvm::Triple::x86:
6001   case llvm::Triple::x86_64:
6002     AddX86TargetArgs(Args, CmdArgs);
6003     break;
6004
6005   case llvm::Triple::arm:
6006   case llvm::Triple::armeb:
6007   case llvm::Triple::thumb:
6008   case llvm::Triple::thumbeb:
6009     // This isn't in AddARMTargetArgs because we want to do this for assembly
6010     // only, not C/C++.
6011     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6012                      options::OPT_mno_default_build_attributes, true)) {
6013         CmdArgs.push_back("-mllvm");
6014         CmdArgs.push_back("-arm-add-build-attributes");
6015     }
6016     break;
6017   }
6018
6019   // Consume all the warning flags. Usually this would be handled more
6020   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6021   // doesn't handle that so rather than warning about unused flags that are
6022   // actually used, we'll lie by omission instead.
6023   // FIXME: Stop lying and consume only the appropriate driver flags
6024   Args.ClaimAllArgs(options::OPT_W_Group);
6025
6026   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6027                                     getToolChain().getDriver());
6028
6029   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6030
6031   assert(Output.isFilename() && "Unexpected lipo output.");
6032   CmdArgs.push_back("-o");
6033   CmdArgs.push_back(Output.getFilename());
6034
6035   const llvm::Triple &T = getToolChain().getTriple();
6036   Arg *A;
6037   if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) &&
6038       (T.isOSLinux() || T.isOSFuchsia())) {
6039     CmdArgs.push_back("-split-dwarf-file");
6040     CmdArgs.push_back(SplitDebugName(Args, Output));
6041   }
6042
6043   assert(Input.isFilename() && "Invalid input.");
6044   CmdArgs.push_back(Input.getFilename());
6045
6046   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6047   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6048 }
6049
6050 // Begin OffloadBundler
6051
6052 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6053                                   const InputInfo &Output,
6054                                   const InputInfoList &Inputs,
6055                                   const llvm::opt::ArgList &TCArgs,
6056                                   const char *LinkingOutput) const {
6057   // The version with only one output is expected to refer to a bundling job.
6058   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6059
6060   // The bundling command looks like this:
6061   // clang-offload-bundler -type=bc
6062   //   -targets=host-triple,openmp-triple1,openmp-triple2
6063   //   -outputs=input_file
6064   //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6065
6066   ArgStringList CmdArgs;
6067
6068   // Get the type.
6069   CmdArgs.push_back(TCArgs.MakeArgString(
6070       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6071
6072   assert(JA.getInputs().size() == Inputs.size() &&
6073          "Not have inputs for all dependence actions??");
6074
6075   // Get the targets.
6076   SmallString<128> Triples;
6077   Triples += "-targets=";
6078   for (unsigned I = 0; I < Inputs.size(); ++I) {
6079     if (I)
6080       Triples += ',';
6081
6082     // Find ToolChain for this input.
6083     Action::OffloadKind CurKind = Action::OFK_Host;
6084     const ToolChain *CurTC = &getToolChain();
6085     const Action *CurDep = JA.getInputs()[I];
6086
6087     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
6088       CurTC = nullptr;
6089       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
6090         assert(CurTC == nullptr && "Expected one dependence!");
6091         CurKind = A->getOffloadingDeviceKind();
6092         CurTC = TC;
6093       });
6094     }
6095     Triples += Action::GetOffloadKindName(CurKind);
6096     Triples += '-';
6097     Triples += CurTC->getTriple().normalize();
6098     if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6099       Triples += '-';
6100       Triples += CurDep->getOffloadingArch();
6101     }
6102   }
6103   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6104
6105   // Get bundled file command.
6106   CmdArgs.push_back(
6107       TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6108
6109   // Get unbundled files command.
6110   SmallString<128> UB;
6111   UB += "-inputs=";
6112   for (unsigned I = 0; I < Inputs.size(); ++I) {
6113     if (I)
6114       UB += ',';
6115
6116     // Find ToolChain for this input.
6117     const ToolChain *CurTC = &getToolChain();
6118     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6119       CurTC = nullptr;
6120       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6121         assert(CurTC == nullptr && "Expected one dependence!");
6122         CurTC = TC;
6123       });
6124     }
6125     UB += CurTC->getInputFilename(Inputs[I]);
6126   }
6127   CmdArgs.push_back(TCArgs.MakeArgString(UB));
6128
6129   // All the inputs are encoded as commands.
6130   C.addCommand(llvm::make_unique<Command>(
6131       JA, *this,
6132       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6133       CmdArgs, None));
6134 }
6135
6136 void OffloadBundler::ConstructJobMultipleOutputs(
6137     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6138     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6139     const char *LinkingOutput) const {
6140   // The version with multiple outputs is expected to refer to a unbundling job.
6141   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6142
6143   // The unbundling command looks like this:
6144   // clang-offload-bundler -type=bc
6145   //   -targets=host-triple,openmp-triple1,openmp-triple2
6146   //   -inputs=input_file
6147   //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6148   //   -unbundle
6149
6150   ArgStringList CmdArgs;
6151
6152   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6153   InputInfo Input = Inputs.front();
6154
6155   // Get the type.
6156   CmdArgs.push_back(TCArgs.MakeArgString(
6157       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6158
6159   // Get the targets.
6160   SmallString<128> Triples;
6161   Triples += "-targets=";
6162   auto DepInfo = UA.getDependentActionsInfo();
6163   for (unsigned I = 0; I < DepInfo.size(); ++I) {
6164     if (I)
6165       Triples += ',';
6166
6167     auto &Dep = DepInfo[I];
6168     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6169     Triples += '-';
6170     Triples += Dep.DependentToolChain->getTriple().normalize();
6171     if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6172         !Dep.DependentBoundArch.empty()) {
6173       Triples += '-';
6174       Triples += Dep.DependentBoundArch;
6175     }
6176   }
6177
6178   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6179
6180   // Get bundled file command.
6181   CmdArgs.push_back(
6182       TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6183
6184   // Get unbundled files command.
6185   SmallString<128> UB;
6186   UB += "-outputs=";
6187   for (unsigned I = 0; I < Outputs.size(); ++I) {
6188     if (I)
6189       UB += ',';
6190     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
6191   }
6192   CmdArgs.push_back(TCArgs.MakeArgString(UB));
6193   CmdArgs.push_back("-unbundle");
6194
6195   // All the inputs are encoded as commands.
6196   C.addCommand(llvm::make_unique<Command>(
6197       JA, *this,
6198       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6199       CmdArgs, None));
6200 }