1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Clang.h"
10 #include "AMDGPU.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/M68k.h"
14 #include "Arch/Mips.h"
15 #include "Arch/PPC.h"
16 #include "Arch/RISCV.h"
17 #include "Arch/Sparc.h"
18 #include "Arch/SystemZ.h"
19 #include "Arch/VE.h"
20 #include "Arch/X86.h"
21 #include "CommonArgs.h"
22 #include "Hexagon.h"
23 #include "InputInfo.h"
24 #include "MSP430.h"
25 #include "PS4CPU.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/CodeGenOptions.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/ObjCRuntime.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Driver/Distro.h"
32 #include "clang/Driver/DriverDiagnostic.h"
33 #include "clang/Driver/Options.h"
34 #include "clang/Driver/SanitizerArgs.h"
35 #include "clang/Driver/XRayArgs.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Config/llvm-config.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Support/CodeGen.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Compression.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/TargetParser.h"
47 #include "llvm/Support/YAMLParser.h"
48 
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
53 
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)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 
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)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.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)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.
QuoteTarget(StringRef Target,SmallVectorImpl<char> & Res)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
forAllAssociatedToolChains(Compilation & C,const JobAction & JA,const ToolChain & RegularToolChain,llvm::function_ref<void (const ToolChain &)> Work)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.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)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.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)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".
ParseMPreferVectorWidth(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)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 
getWebAssemblyTargetFeatures(const ArgList & Args,std::vector<StringRef> & Features)305 static void getWebAssemblyTargetFeatures(const ArgList &Args,
306                                          std::vector<StringRef> &Features) {
307   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308 }
309 
getTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool ForAS,bool IsAux=false)310 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
311                               const ArgList &Args, ArgStringList &CmdArgs,
312                               bool ForAS, bool IsAux = false) {
313   std::vector<StringRef> Features;
314   switch (Triple.getArch()) {
315   default:
316     break;
317   case llvm::Triple::mips:
318   case llvm::Triple::mipsel:
319   case llvm::Triple::mips64:
320   case llvm::Triple::mips64el:
321     mips::getMIPSTargetFeatures(D, Triple, Args, Features);
322     break;
323 
324   case llvm::Triple::arm:
325   case llvm::Triple::armeb:
326   case llvm::Triple::thumb:
327   case llvm::Triple::thumbeb:
328     arm::getARMTargetFeatures(D, Triple, Args, CmdArgs, Features, ForAS);
329     break;
330 
331   case llvm::Triple::ppc:
332   case llvm::Triple::ppcle:
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, Triple, Args, Features);
340     break;
341   case llvm::Triple::systemz:
342     systemz::getSystemZTargetFeatures(D, Args, Features);
343     break;
344   case llvm::Triple::aarch64:
345   case llvm::Triple::aarch64_32:
346   case llvm::Triple::aarch64_be:
347     aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
348     break;
349   case llvm::Triple::x86:
350   case llvm::Triple::x86_64:
351     x86::getX86TargetFeatures(D, Triple, Args, Features);
352     break;
353   case llvm::Triple::hexagon:
354     hexagon::getHexagonTargetFeatures(D, Args, Features);
355     break;
356   case llvm::Triple::wasm32:
357   case llvm::Triple::wasm64:
358     getWebAssemblyTargetFeatures(Args, Features);
359     break;
360   case llvm::Triple::sparc:
361   case llvm::Triple::sparcel:
362   case llvm::Triple::sparcv9:
363     sparc::getSparcTargetFeatures(D, Args, Features);
364     break;
365   case llvm::Triple::r600:
366   case llvm::Triple::amdgcn:
367     amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
368     break;
369   case llvm::Triple::m68k:
370     m68k::getM68kTargetFeatures(D, Triple, Args, Features);
371     break;
372   case llvm::Triple::msp430:
373     msp430::getMSP430TargetFeatures(D, Args, Features);
374     break;
375   case llvm::Triple::ve:
376     ve::getVETargetFeatures(D, Args, Features);
377     break;
378   }
379 
380   for (auto Feature : unifyTargetFeatures(Features)) {
381     CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
382     CmdArgs.push_back(Feature.data());
383   }
384 }
385 
386 static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)387 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
388                                           const llvm::Triple &Triple) {
389   // We use the zero-cost exception tables for Objective-C if the non-fragile
390   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
391   // later.
392   if (runtime.isNonFragile())
393     return true;
394 
395   if (!Triple.isMacOSX())
396     return false;
397 
398   return (!Triple.isMacOSXVersionLT(10, 5) &&
399           (Triple.getArch() == llvm::Triple::x86_64 ||
400            Triple.getArch() == llvm::Triple::arm));
401 }
402 
403 /// Adds exception related arguments to the driver command arguments. There's a
404 /// master flag, -fexceptions and also language specific flags to enable/disable
405 /// C++ and Objective-C exceptions. This makes it possible to for example
406 /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)407 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
408                              const ToolChain &TC, bool KernelOrKext,
409                              const ObjCRuntime &objcRuntime,
410                              ArgStringList &CmdArgs) {
411   const llvm::Triple &Triple = TC.getTriple();
412 
413   if (KernelOrKext) {
414     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
415     // arguments now to avoid warnings about unused arguments.
416     Args.ClaimAllArgs(options::OPT_fexceptions);
417     Args.ClaimAllArgs(options::OPT_fno_exceptions);
418     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
419     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
420     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
421     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
422     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
423     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
424     return false;
425   }
426 
427   // See if the user explicitly enabled exceptions.
428   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
429                          false);
430 
431   bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
432                           options::OPT_fno_async_exceptions, false);
433   if (EHa) {
434     CmdArgs.push_back("-fasync-exceptions");
435     EH = true;
436   }
437 
438   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
439   // is not necessarily sensible, but follows GCC.
440   if (types::isObjC(InputType) &&
441       Args.hasFlag(options::OPT_fobjc_exceptions,
442                    options::OPT_fno_objc_exceptions, true)) {
443     CmdArgs.push_back("-fobjc-exceptions");
444 
445     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
446   }
447 
448   if (types::isCXX(InputType)) {
449     // Disable C++ EH by default on XCore and PS4.
450     bool CXXExceptionsEnabled =
451         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
452     Arg *ExceptionArg = Args.getLastArg(
453         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
454         options::OPT_fexceptions, options::OPT_fno_exceptions);
455     if (ExceptionArg)
456       CXXExceptionsEnabled =
457           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
458           ExceptionArg->getOption().matches(options::OPT_fexceptions);
459 
460     if (CXXExceptionsEnabled) {
461       CmdArgs.push_back("-fcxx-exceptions");
462 
463       EH = true;
464     }
465   }
466 
467   // OPT_fignore_exceptions means exception could still be thrown,
468   // but no clean up or catch would happen in current module.
469   // So we do not set EH to false.
470   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
471 
472   if (EH)
473     CmdArgs.push_back("-fexceptions");
474   return EH;
475 }
476 
ShouldEnableAutolink(const ArgList & Args,const ToolChain & TC,const JobAction & JA)477 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
478                                  const JobAction &JA) {
479   bool Default = true;
480   if (TC.getTriple().isOSDarwin()) {
481     // The native darwin assembler doesn't support the linker_option directives,
482     // so we disable them if we think the .s file will be passed to it.
483     Default = TC.useIntegratedAs();
484   }
485   // The linker_option directives are intended for host compilation.
486   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
487       JA.isDeviceOffloading(Action::OFK_HIP))
488     Default = false;
489   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
490                       Default);
491 }
492 
ShouldDisableDwarfDirectory(const ArgList & Args,const ToolChain & TC)493 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
494                                         const ToolChain &TC) {
495   bool UseDwarfDirectory =
496       Args.hasFlag(options::OPT_fdwarf_directory_asm,
497                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
498   return !UseDwarfDirectory;
499 }
500 
501 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
502 // to the corresponding DebugInfoKind.
DebugLevelToInfoKind(const Arg & A)503 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
504   assert(A.getOption().matches(options::OPT_gN_Group) &&
505          "Not a -g option that specifies a debug-info level");
506   if (A.getOption().matches(options::OPT_g0) ||
507       A.getOption().matches(options::OPT_ggdb0))
508     return codegenoptions::NoDebugInfo;
509   if (A.getOption().matches(options::OPT_gline_tables_only) ||
510       A.getOption().matches(options::OPT_ggdb1))
511     return codegenoptions::DebugLineTablesOnly;
512   if (A.getOption().matches(options::OPT_gline_directives_only))
513     return codegenoptions::DebugDirectivesOnly;
514   return codegenoptions::LimitedDebugInfo;
515 }
516 
mustUseNonLeafFramePointerForTarget(const llvm::Triple & Triple)517 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
518   switch (Triple.getArch()){
519   default:
520     return false;
521   case llvm::Triple::arm:
522   case llvm::Triple::thumb:
523     // ARM Darwin targets require a frame pointer to be always present to aid
524     // offline debugging via backtraces.
525     return Triple.isOSDarwin();
526   }
527 }
528 
useFramePointerForTargetByDefault(const ArgList & Args,const llvm::Triple & Triple)529 static bool useFramePointerForTargetByDefault(const ArgList &Args,
530                                               const llvm::Triple &Triple) {
531   if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
532     return true;
533 
534   switch (Triple.getArch()) {
535   case llvm::Triple::xcore:
536   case llvm::Triple::wasm32:
537   case llvm::Triple::wasm64:
538   case llvm::Triple::msp430:
539     // XCore never wants frame pointers, regardless of OS.
540     // WebAssembly never wants frame pointers.
541     return false;
542   case llvm::Triple::ppc:
543   case llvm::Triple::ppcle:
544   case llvm::Triple::ppc64:
545   case llvm::Triple::ppc64le:
546   case llvm::Triple::riscv32:
547   case llvm::Triple::riscv64:
548   case llvm::Triple::amdgcn:
549   case llvm::Triple::r600:
550     return !areOptimizationsEnabled(Args);
551   default:
552     break;
553   }
554 
555   if (Triple.isOSNetBSD()) {
556     return !areOptimizationsEnabled(Args);
557   }
558 
559   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
560       Triple.isOSHurd()) {
561     switch (Triple.getArch()) {
562     // Don't use a frame pointer on linux if optimizing for certain targets.
563     case llvm::Triple::arm:
564     case llvm::Triple::armeb:
565     case llvm::Triple::thumb:
566     case llvm::Triple::thumbeb:
567       if (Triple.isAndroid())
568         return true;
569       LLVM_FALLTHROUGH;
570     case llvm::Triple::mips64:
571     case llvm::Triple::mips64el:
572     case llvm::Triple::mips:
573     case llvm::Triple::mipsel:
574     case llvm::Triple::systemz:
575     case llvm::Triple::x86:
576     case llvm::Triple::x86_64:
577       return !areOptimizationsEnabled(Args);
578     default:
579       return true;
580     }
581   }
582 
583   if (Triple.isOSWindows()) {
584     switch (Triple.getArch()) {
585     case llvm::Triple::x86:
586       return !areOptimizationsEnabled(Args);
587     case llvm::Triple::x86_64:
588       return Triple.isOSBinFormatMachO();
589     case llvm::Triple::arm:
590     case llvm::Triple::thumb:
591       // Windows on ARM builds with FPO disabled to aid fast stack walking
592       return true;
593     default:
594       // All other supported Windows ISAs use xdata unwind information, so frame
595       // pointers are not generally useful.
596       return false;
597     }
598   }
599 
600   return true;
601 }
602 
603 static CodeGenOptions::FramePointerKind
getFramePointerKind(const ArgList & Args,const llvm::Triple & Triple)604 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
605   // We have 4 states:
606   //
607   //  00) leaf retained, non-leaf retained
608   //  01) leaf retained, non-leaf omitted (this is invalid)
609   //  10) leaf omitted, non-leaf retained
610   //      (what -momit-leaf-frame-pointer was designed for)
611   //  11) leaf omitted, non-leaf omitted
612   //
613   //  "omit" options taking precedence over "no-omit" options is the only way
614   //  to make 3 valid states representable
615   Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
616                            options::OPT_fno_omit_frame_pointer);
617   bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
618   bool NoOmitFP =
619       A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
620   bool OmitLeafFP = Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
621                                  options::OPT_mno_omit_leaf_frame_pointer,
622                                  Triple.isAArch64() || Triple.isPS4CPU());
623   if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
624       (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
625     if (OmitLeafFP)
626       return CodeGenOptions::FramePointerKind::NonLeaf;
627     return CodeGenOptions::FramePointerKind::All;
628   }
629   return CodeGenOptions::FramePointerKind::None;
630 }
631 
632 /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs,const llvm::vfs::FileSystem & VFS)633 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
634                                const llvm::vfs::FileSystem &VFS) {
635   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
636                                options::OPT_fdebug_compilation_dir_EQ)) {
637     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
638       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
639                                            A->getValue()));
640     else
641       A->render(Args, CmdArgs);
642   } else if (llvm::ErrorOr<std::string> CWD =
643                  VFS.getCurrentWorkingDirectory()) {
644     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
645   }
646 }
647 
648 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
addDebugPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)649 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
650   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
651                                     options::OPT_fdebug_prefix_map_EQ)) {
652     StringRef Map = A->getValue();
653     if (Map.find('=') == StringRef::npos)
654       D.Diag(diag::err_drv_invalid_argument_to_option)
655           << Map << A->getOption().getName();
656     else
657       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
658     A->claim();
659   }
660 }
661 
662 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
addMacroPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)663 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
664                                  ArgStringList &CmdArgs) {
665   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
666                                     options::OPT_fmacro_prefix_map_EQ)) {
667     StringRef Map = A->getValue();
668     if (Map.find('=') == StringRef::npos)
669       D.Diag(diag::err_drv_invalid_argument_to_option)
670           << Map << A->getOption().getName();
671     else
672       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
673     A->claim();
674   }
675 }
676 
677 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
addCoveragePrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)678 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
679                                    ArgStringList &CmdArgs) {
680   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
681                                     options::OPT_fcoverage_prefix_map_EQ)) {
682     StringRef Map = A->getValue();
683     if (Map.find('=') == StringRef::npos)
684       D.Diag(diag::err_drv_invalid_argument_to_option)
685           << Map << A->getOption().getName();
686     else
687       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
688     A->claim();
689   }
690 }
691 
692 /// Vectorize at all optimization levels greater than 1 except for -Oz.
693 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
694 /// enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)695 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
696   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
697     if (A->getOption().matches(options::OPT_O4) ||
698         A->getOption().matches(options::OPT_Ofast))
699       return true;
700 
701     if (A->getOption().matches(options::OPT_O0))
702       return false;
703 
704     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
705 
706     // Vectorize -Os.
707     StringRef S(A->getValue());
708     if (S == "s")
709       return true;
710 
711     // Don't vectorize -Oz, unless it's the slp vectorizer.
712     if (S == "z")
713       return isSlpVec;
714 
715     unsigned OptLevel = 0;
716     if (S.getAsInteger(10, OptLevel))
717       return false;
718 
719     return OptLevel > 1;
720   }
721 
722   return false;
723 }
724 
725 /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)726 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
727                              ArgStringList &CmdArgs) {
728   // When using -verify-pch, we don't want to provide the type
729   // 'precompiled-header' if it was inferred from the file extension
730   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
731     return;
732 
733   CmdArgs.push_back("-x");
734   if (Args.hasArg(options::OPT_rewrite_objc))
735     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
736   else {
737     // Map the driver type to the frontend type. This is mostly an identity
738     // mapping, except that the distinction between module interface units
739     // and other source files does not exist at the frontend layer.
740     const char *ClangType;
741     switch (Input.getType()) {
742     case types::TY_CXXModule:
743       ClangType = "c++";
744       break;
745     case types::TY_PP_CXXModule:
746       ClangType = "c++-cpp-output";
747       break;
748     default:
749       ClangType = types::getTypeName(Input.getType());
750       break;
751     }
752     CmdArgs.push_back(ClangType);
753   }
754 }
755 
addPGOAndCoverageFlags(const ToolChain & TC,Compilation & C,const Driver & D,const InputInfo & Output,const ArgList & Args,ArgStringList & CmdArgs)756 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
757                                    const Driver &D, const InputInfo &Output,
758                                    const ArgList &Args,
759                                    ArgStringList &CmdArgs) {
760 
761   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
762                                          options::OPT_fprofile_generate_EQ,
763                                          options::OPT_fno_profile_generate);
764   if (PGOGenerateArg &&
765       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
766     PGOGenerateArg = nullptr;
767 
768   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
769                                            options::OPT_fcs_profile_generate_EQ,
770                                            options::OPT_fno_profile_generate);
771   if (CSPGOGenerateArg &&
772       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
773     CSPGOGenerateArg = nullptr;
774 
775   auto *ProfileGenerateArg = Args.getLastArg(
776       options::OPT_fprofile_instr_generate,
777       options::OPT_fprofile_instr_generate_EQ,
778       options::OPT_fno_profile_instr_generate);
779   if (ProfileGenerateArg &&
780       ProfileGenerateArg->getOption().matches(
781           options::OPT_fno_profile_instr_generate))
782     ProfileGenerateArg = nullptr;
783 
784   if (PGOGenerateArg && ProfileGenerateArg)
785     D.Diag(diag::err_drv_argument_not_allowed_with)
786         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
787 
788   auto *ProfileUseArg = getLastProfileUseArg(Args);
789 
790   if (PGOGenerateArg && ProfileUseArg)
791     D.Diag(diag::err_drv_argument_not_allowed_with)
792         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
793 
794   if (ProfileGenerateArg && ProfileUseArg)
795     D.Diag(diag::err_drv_argument_not_allowed_with)
796         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
797 
798   if (CSPGOGenerateArg && PGOGenerateArg) {
799     D.Diag(diag::err_drv_argument_not_allowed_with)
800         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
801     PGOGenerateArg = nullptr;
802   }
803 
804   if (ProfileGenerateArg) {
805     if (ProfileGenerateArg->getOption().matches(
806             options::OPT_fprofile_instr_generate_EQ))
807       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
808                                            ProfileGenerateArg->getValue()));
809     // The default is to use Clang Instrumentation.
810     CmdArgs.push_back("-fprofile-instrument=clang");
811     if (TC.getTriple().isWindowsMSVCEnvironment()) {
812       // Add dependent lib for clang_rt.profile
813       CmdArgs.push_back(Args.MakeArgString(
814           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
815     }
816   }
817 
818   Arg *PGOGenArg = nullptr;
819   if (PGOGenerateArg) {
820     assert(!CSPGOGenerateArg);
821     PGOGenArg = PGOGenerateArg;
822     CmdArgs.push_back("-fprofile-instrument=llvm");
823   }
824   if (CSPGOGenerateArg) {
825     assert(!PGOGenerateArg);
826     PGOGenArg = CSPGOGenerateArg;
827     CmdArgs.push_back("-fprofile-instrument=csllvm");
828   }
829   if (PGOGenArg) {
830     if (TC.getTriple().isWindowsMSVCEnvironment()) {
831       // Add dependent lib for clang_rt.profile
832       CmdArgs.push_back(Args.MakeArgString(
833           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
834     }
835     if (PGOGenArg->getOption().matches(
836             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
837                            : options::OPT_fcs_profile_generate_EQ)) {
838       SmallString<128> Path(PGOGenArg->getValue());
839       llvm::sys::path::append(Path, "default_%m.profraw");
840       CmdArgs.push_back(
841           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
842     }
843   }
844 
845   if (ProfileUseArg) {
846     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
847       CmdArgs.push_back(Args.MakeArgString(
848           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
849     else if ((ProfileUseArg->getOption().matches(
850                   options::OPT_fprofile_use_EQ) ||
851               ProfileUseArg->getOption().matches(
852                   options::OPT_fprofile_instr_use))) {
853       SmallString<128> Path(
854           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
855       if (Path.empty() || llvm::sys::fs::is_directory(Path))
856         llvm::sys::path::append(Path, "default.profdata");
857       CmdArgs.push_back(
858           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
859     }
860   }
861 
862   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
863                                    options::OPT_fno_test_coverage, false) ||
864                       Args.hasArg(options::OPT_coverage);
865   bool EmitCovData = TC.needsGCovInstrumentation(Args);
866   if (EmitCovNotes)
867     CmdArgs.push_back("-ftest-coverage");
868   if (EmitCovData)
869     CmdArgs.push_back("-fprofile-arcs");
870 
871   if (Args.hasFlag(options::OPT_fcoverage_mapping,
872                    options::OPT_fno_coverage_mapping, false)) {
873     if (!ProfileGenerateArg)
874       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
875           << "-fcoverage-mapping"
876           << "-fprofile-instr-generate";
877 
878     CmdArgs.push_back("-fcoverage-mapping");
879   }
880 
881   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
882                                options::OPT_fcoverage_compilation_dir_EQ)) {
883     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
884       CmdArgs.push_back(Args.MakeArgString(
885           Twine("-fcoverage-compilation-dir=") + A->getValue()));
886     else
887       A->render(Args, CmdArgs);
888   } else if (llvm::ErrorOr<std::string> CWD =
889                  D.getVFS().getCurrentWorkingDirectory()) {
890     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
891   }
892 
893   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
894     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
895     if (!Args.hasArg(options::OPT_coverage))
896       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
897           << "-fprofile-exclude-files="
898           << "--coverage";
899 
900     StringRef v = Arg->getValue();
901     CmdArgs.push_back(
902         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
903   }
904 
905   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
906     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
907     if (!Args.hasArg(options::OPT_coverage))
908       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
909           << "-fprofile-filter-files="
910           << "--coverage";
911 
912     StringRef v = Arg->getValue();
913     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
914   }
915 
916   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
917     StringRef Val = A->getValue();
918     if (Val == "atomic" || Val == "prefer-atomic")
919       CmdArgs.push_back("-fprofile-update=atomic");
920     else if (Val != "single")
921       D.Diag(diag::err_drv_unsupported_option_argument)
922           << A->getOption().getName() << Val;
923   } else if (TC.getSanitizerArgs().needsTsanRt()) {
924     CmdArgs.push_back("-fprofile-update=atomic");
925   }
926 
927   // Leave -fprofile-dir= an unused argument unless .gcda emission is
928   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
929   // the flag used. There is no -fno-profile-dir, so the user has no
930   // targeted way to suppress the warning.
931   Arg *FProfileDir = nullptr;
932   if (Args.hasArg(options::OPT_fprofile_arcs) ||
933       Args.hasArg(options::OPT_coverage))
934     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
935 
936   // Put the .gcno and .gcda files (if needed) next to the object file or
937   // bitcode file in the case of LTO.
938   // FIXME: There should be a simpler way to find the object file for this
939   // input, and this code probably does the wrong thing for commands that
940   // compile and link all at once.
941   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
942       (EmitCovNotes || EmitCovData) && Output.isFilename()) {
943     SmallString<128> OutputFilename;
944     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
945       OutputFilename = FinalOutput->getValue();
946     else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
947       OutputFilename = FinalOutput->getValue();
948     else
949       OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
950     SmallString<128> CoverageFilename = OutputFilename;
951     if (llvm::sys::path::is_relative(CoverageFilename))
952       (void)D.getVFS().makeAbsolute(CoverageFilename);
953     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
954 
955     CmdArgs.push_back("-coverage-notes-file");
956     CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
957 
958     if (EmitCovData) {
959       if (FProfileDir) {
960         CoverageFilename = FProfileDir->getValue();
961         llvm::sys::path::append(CoverageFilename, OutputFilename);
962       }
963       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
964       CmdArgs.push_back("-coverage-data-file");
965       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
966     }
967   }
968 }
969 
970 /// Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)971 static bool ContainsCompileAction(const Action *A) {
972   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
973     return true;
974 
975   for (const auto &AI : A->inputs())
976     if (ContainsCompileAction(AI))
977       return true;
978 
979   return false;
980 }
981 
982 /// Check if -relax-all should be passed to the internal assembler.
983 /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)984 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
985   bool RelaxDefault = true;
986 
987   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
988     RelaxDefault = A->getOption().matches(options::OPT_O0);
989 
990   if (RelaxDefault) {
991     RelaxDefault = false;
992     for (const auto &Act : C.getActions()) {
993       if (ContainsCompileAction(Act)) {
994         RelaxDefault = true;
995         break;
996       }
997     }
998   }
999 
1000   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1001                       RelaxDefault);
1002 }
1003 
1004 // Extract the integer N from a string spelled "-dwarf-N", returning 0
1005 // on mismatch. The StringRef input (rather than an Arg) allows
1006 // for use by the "-Xassembler" option parser.
DwarfVersionNum(StringRef ArgValue)1007 static unsigned DwarfVersionNum(StringRef ArgValue) {
1008   return llvm::StringSwitch<unsigned>(ArgValue)
1009       .Case("-gdwarf-2", 2)
1010       .Case("-gdwarf-3", 3)
1011       .Case("-gdwarf-4", 4)
1012       .Case("-gdwarf-5", 5)
1013       .Default(0);
1014 }
1015 
1016 // Find a DWARF format version option.
1017 // This function is a complementary for DwarfVersionNum().
getDwarfNArg(const ArgList & Args)1018 static const Arg *getDwarfNArg(const ArgList &Args) {
1019   return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
1020                          options::OPT_gdwarf_4, options::OPT_gdwarf_5,
1021                          options::OPT_gdwarf);
1022 }
1023 
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)1024 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
1025                                     codegenoptions::DebugInfoKind DebugInfoKind,
1026                                     unsigned DwarfVersion,
1027                                     llvm::DebuggerKind DebuggerTuning) {
1028   switch (DebugInfoKind) {
1029   case codegenoptions::DebugDirectivesOnly:
1030     CmdArgs.push_back("-debug-info-kind=line-directives-only");
1031     break;
1032   case codegenoptions::DebugLineTablesOnly:
1033     CmdArgs.push_back("-debug-info-kind=line-tables-only");
1034     break;
1035   case codegenoptions::DebugInfoConstructor:
1036     CmdArgs.push_back("-debug-info-kind=constructor");
1037     break;
1038   case codegenoptions::LimitedDebugInfo:
1039     CmdArgs.push_back("-debug-info-kind=limited");
1040     break;
1041   case codegenoptions::FullDebugInfo:
1042     CmdArgs.push_back("-debug-info-kind=standalone");
1043     break;
1044   case codegenoptions::UnusedTypeInfo:
1045     CmdArgs.push_back("-debug-info-kind=unused-types");
1046     break;
1047   default:
1048     break;
1049   }
1050   if (DwarfVersion > 0)
1051     CmdArgs.push_back(
1052         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
1053   switch (DebuggerTuning) {
1054   case llvm::DebuggerKind::GDB:
1055     CmdArgs.push_back("-debugger-tuning=gdb");
1056     break;
1057   case llvm::DebuggerKind::LLDB:
1058     CmdArgs.push_back("-debugger-tuning=lldb");
1059     break;
1060   case llvm::DebuggerKind::SCE:
1061     CmdArgs.push_back("-debugger-tuning=sce");
1062     break;
1063   case llvm::DebuggerKind::DBX:
1064     CmdArgs.push_back("-debugger-tuning=dbx");
1065     break;
1066   default:
1067     break;
1068   }
1069 }
1070 
checkDebugInfoOption(const Arg * A,const ArgList & Args,const Driver & D,const ToolChain & TC)1071 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1072                                  const Driver &D, const ToolChain &TC) {
1073   assert(A && "Expected non-nullptr argument.");
1074   if (TC.supportsDebugInfoOption(A))
1075     return true;
1076   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1077       << A->getAsString(Args) << TC.getTripleString();
1078   return false;
1079 }
1080 
RenderDebugInfoCompressionArgs(const ArgList & Args,ArgStringList & CmdArgs,const Driver & D,const ToolChain & TC)1081 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1082                                            ArgStringList &CmdArgs,
1083                                            const Driver &D,
1084                                            const ToolChain &TC) {
1085   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1086   if (!A)
1087     return;
1088   if (checkDebugInfoOption(A, Args, D, TC)) {
1089     StringRef Value = A->getValue();
1090     if (Value == "none") {
1091       CmdArgs.push_back("--compress-debug-sections=none");
1092     } else if (Value == "zlib" || Value == "zlib-gnu") {
1093       if (llvm::zlib::isAvailable()) {
1094         CmdArgs.push_back(
1095             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1096       } else {
1097         D.Diag(diag::warn_debug_compression_unavailable);
1098       }
1099     } else {
1100       D.Diag(diag::err_drv_unsupported_option_argument)
1101           << A->getOption().getName() << Value;
1102     }
1103   }
1104 }
1105 
RelocationModelName(llvm::Reloc::Model Model)1106 static const char *RelocationModelName(llvm::Reloc::Model Model) {
1107   switch (Model) {
1108   case llvm::Reloc::Static:
1109     return "static";
1110   case llvm::Reloc::PIC_:
1111     return "pic";
1112   case llvm::Reloc::DynamicNoPIC:
1113     return "dynamic-no-pic";
1114   case llvm::Reloc::ROPI:
1115     return "ropi";
1116   case llvm::Reloc::RWPI:
1117     return "rwpi";
1118   case llvm::Reloc::ROPI_RWPI:
1119     return "ropi-rwpi";
1120   }
1121   llvm_unreachable("Unknown Reloc::Model kind");
1122 }
handleAMDGPUCodeObjectVersionOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)1123 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1124                                                  const ArgList &Args,
1125                                                  ArgStringList &CmdArgs) {
1126   // If no version was requested by the user, use the default value from the
1127   // back end. This is consistent with the value returned from
1128   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1129   // requiring the corresponding llvm to have the AMDGPU target enabled,
1130   // provided the user (e.g. front end tests) can use the default.
1131   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1132     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1133     CmdArgs.insert(CmdArgs.begin() + 1,
1134                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1135                                       Twine(CodeObjVer)));
1136     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1137   }
1138 }
1139 
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const1140 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1141                                     const Driver &D, const ArgList &Args,
1142                                     ArgStringList &CmdArgs,
1143                                     const InputInfo &Output,
1144                                     const InputInfoList &Inputs) const {
1145   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1146 
1147   CheckPreprocessingOptions(D, Args);
1148 
1149   Args.AddLastArg(CmdArgs, options::OPT_C);
1150   Args.AddLastArg(CmdArgs, options::OPT_CC);
1151 
1152   // Handle dependency file generation.
1153   Arg *ArgM = Args.getLastArg(options::OPT_MM);
1154   if (!ArgM)
1155     ArgM = Args.getLastArg(options::OPT_M);
1156   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1157   if (!ArgMD)
1158     ArgMD = Args.getLastArg(options::OPT_MD);
1159 
1160   // -M and -MM imply -w.
1161   if (ArgM)
1162     CmdArgs.push_back("-w");
1163   else
1164     ArgM = ArgMD;
1165 
1166   if (ArgM) {
1167     // Determine the output location.
1168     const char *DepFile;
1169     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1170       DepFile = MF->getValue();
1171       C.addFailureResultFile(DepFile, &JA);
1172     } else if (Output.getType() == types::TY_Dependencies) {
1173       DepFile = Output.getFilename();
1174     } else if (!ArgMD) {
1175       DepFile = "-";
1176     } else {
1177       DepFile = getDependencyFileName(Args, Inputs);
1178       C.addFailureResultFile(DepFile, &JA);
1179     }
1180     CmdArgs.push_back("-dependency-file");
1181     CmdArgs.push_back(DepFile);
1182 
1183     bool HasTarget = false;
1184     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1185       HasTarget = true;
1186       A->claim();
1187       if (A->getOption().matches(options::OPT_MT)) {
1188         A->render(Args, CmdArgs);
1189       } else {
1190         CmdArgs.push_back("-MT");
1191         SmallString<128> Quoted;
1192         QuoteTarget(A->getValue(), Quoted);
1193         CmdArgs.push_back(Args.MakeArgString(Quoted));
1194       }
1195     }
1196 
1197     // Add a default target if one wasn't specified.
1198     if (!HasTarget) {
1199       const char *DepTarget;
1200 
1201       // If user provided -o, that is the dependency target, except
1202       // when we are only generating a dependency file.
1203       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1204       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1205         DepTarget = OutputOpt->getValue();
1206       } else {
1207         // Otherwise derive from the base input.
1208         //
1209         // FIXME: This should use the computed output file location.
1210         SmallString<128> P(Inputs[0].getBaseInput());
1211         llvm::sys::path::replace_extension(P, "o");
1212         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1213       }
1214 
1215       CmdArgs.push_back("-MT");
1216       SmallString<128> Quoted;
1217       QuoteTarget(DepTarget, Quoted);
1218       CmdArgs.push_back(Args.MakeArgString(Quoted));
1219     }
1220 
1221     if (ArgM->getOption().matches(options::OPT_M) ||
1222         ArgM->getOption().matches(options::OPT_MD))
1223       CmdArgs.push_back("-sys-header-deps");
1224     if ((isa<PrecompileJobAction>(JA) &&
1225          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1226         Args.hasArg(options::OPT_fmodule_file_deps))
1227       CmdArgs.push_back("-module-file-deps");
1228   }
1229 
1230   if (Args.hasArg(options::OPT_MG)) {
1231     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1232         ArgM->getOption().matches(options::OPT_MMD))
1233       D.Diag(diag::err_drv_mg_requires_m_or_mm);
1234     CmdArgs.push_back("-MG");
1235   }
1236 
1237   Args.AddLastArg(CmdArgs, options::OPT_MP);
1238   Args.AddLastArg(CmdArgs, options::OPT_MV);
1239 
1240   // Add offload include arguments specific for CUDA/HIP.  This must happen
1241   // before we -I or -include anything else, because we must pick up the
1242   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1243   // from e.g. /usr/local/include.
1244   if (JA.isOffloading(Action::OFK_Cuda))
1245     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1246   if (JA.isOffloading(Action::OFK_HIP))
1247     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1248 
1249   // If we are offloading to a target via OpenMP we need to include the
1250   // openmp_wrappers folder which contains alternative system headers.
1251   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1252       getToolChain().getTriple().isNVPTX()){
1253     if (!Args.hasArg(options::OPT_nobuiltininc)) {
1254       // Add openmp_wrappers/* to our system include path.  This lets us wrap
1255       // standard library headers.
1256       SmallString<128> P(D.ResourceDir);
1257       llvm::sys::path::append(P, "include");
1258       llvm::sys::path::append(P, "openmp_wrappers");
1259       CmdArgs.push_back("-internal-isystem");
1260       CmdArgs.push_back(Args.MakeArgString(P));
1261     }
1262 
1263     CmdArgs.push_back("-include");
1264     CmdArgs.push_back("__clang_openmp_device_functions.h");
1265   }
1266 
1267   // Add -i* options, and automatically translate to
1268   // -include-pch/-include-pth for transparent PCH support. It's
1269   // wonky, but we include looking for .gch so we can support seamless
1270   // replacement into a build system already set up to be generating
1271   // .gch files.
1272 
1273   if (getToolChain().getDriver().IsCLMode()) {
1274     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1275     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1276     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1277         JA.getKind() <= Action::AssembleJobClass) {
1278       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1279       // -fpch-instantiate-templates is the default when creating
1280       // precomp using /Yc
1281       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1282                        options::OPT_fno_pch_instantiate_templates, true))
1283         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1284     }
1285     if (YcArg || YuArg) {
1286       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1287       if (!isa<PrecompileJobAction>(JA)) {
1288         CmdArgs.push_back("-include-pch");
1289         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1290             C, !ThroughHeader.empty()
1291                    ? ThroughHeader
1292                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1293       }
1294 
1295       if (ThroughHeader.empty()) {
1296         CmdArgs.push_back(Args.MakeArgString(
1297             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1298       } else {
1299         CmdArgs.push_back(
1300             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1301       }
1302     }
1303   }
1304 
1305   bool RenderedImplicitInclude = false;
1306   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1307     if (A->getOption().matches(options::OPT_include)) {
1308       // Handling of gcc-style gch precompiled headers.
1309       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1310       RenderedImplicitInclude = true;
1311 
1312       bool FoundPCH = false;
1313       SmallString<128> P(A->getValue());
1314       // We want the files to have a name like foo.h.pch. Add a dummy extension
1315       // so that replace_extension does the right thing.
1316       P += ".dummy";
1317       llvm::sys::path::replace_extension(P, "pch");
1318       if (llvm::sys::fs::exists(P))
1319         FoundPCH = true;
1320 
1321       if (!FoundPCH) {
1322         llvm::sys::path::replace_extension(P, "gch");
1323         if (llvm::sys::fs::exists(P)) {
1324           FoundPCH = true;
1325         }
1326       }
1327 
1328       if (FoundPCH) {
1329         if (IsFirstImplicitInclude) {
1330           A->claim();
1331           CmdArgs.push_back("-include-pch");
1332           CmdArgs.push_back(Args.MakeArgString(P));
1333           continue;
1334         } else {
1335           // Ignore the PCH if not first on command line and emit warning.
1336           D.Diag(diag::warn_drv_pch_not_first_include) << P
1337                                                        << A->getAsString(Args);
1338         }
1339       }
1340     } else if (A->getOption().matches(options::OPT_isystem_after)) {
1341       // Handling of paths which must come late.  These entries are handled by
1342       // the toolchain itself after the resource dir is inserted in the right
1343       // search order.
1344       // Do not claim the argument so that the use of the argument does not
1345       // silently go unnoticed on toolchains which do not honour the option.
1346       continue;
1347     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1348       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1349       continue;
1350     }
1351 
1352     // Not translated, render as usual.
1353     A->claim();
1354     A->render(Args, CmdArgs);
1355   }
1356 
1357   Args.AddAllArgs(CmdArgs,
1358                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1359                    options::OPT_F, options::OPT_index_header_map});
1360 
1361   // Add -Wp, and -Xpreprocessor if using the preprocessor.
1362 
1363   // FIXME: There is a very unfortunate problem here, some troubled
1364   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1365   // really support that we would have to parse and then translate
1366   // those options. :(
1367   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1368                        options::OPT_Xpreprocessor);
1369 
1370   // -I- is a deprecated GCC feature, reject it.
1371   if (Arg *A = Args.getLastArg(options::OPT_I_))
1372     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1373 
1374   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1375   // -isysroot to the CC1 invocation.
1376   StringRef sysroot = C.getSysRoot();
1377   if (sysroot != "") {
1378     if (!Args.hasArg(options::OPT_isysroot)) {
1379       CmdArgs.push_back("-isysroot");
1380       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1381     }
1382   }
1383 
1384   // Parse additional include paths from environment variables.
1385   // FIXME: We should probably sink the logic for handling these from the
1386   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1387   // CPATH - included following the user specified includes (but prior to
1388   // builtin and standard includes).
1389   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1390   // C_INCLUDE_PATH - system includes enabled when compiling C.
1391   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1392   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1393   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1394   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1395   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1396   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1397   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1398 
1399   // While adding the include arguments, we also attempt to retrieve the
1400   // arguments of related offloading toolchains or arguments that are specific
1401   // of an offloading programming model.
1402 
1403   // Add C++ include arguments, if needed.
1404   if (types::isCXX(Inputs[0].getType())) {
1405     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1406     forAllAssociatedToolChains(
1407         C, JA, getToolChain(),
1408         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1409           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1410                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1411         });
1412   }
1413 
1414   // Add system include arguments for all targets but IAMCU.
1415   if (!IsIAMCU)
1416     forAllAssociatedToolChains(C, JA, getToolChain(),
1417                                [&Args, &CmdArgs](const ToolChain &TC) {
1418                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1419                                });
1420   else {
1421     // For IAMCU add special include arguments.
1422     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1423   }
1424 
1425   addMacroPrefixMapArg(D, Args, CmdArgs);
1426   addCoveragePrefixMapArg(D, Args, CmdArgs);
1427 }
1428 
1429 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)1430 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1431   switch (Triple.getArch()) {
1432   default:
1433     return true;
1434 
1435   case llvm::Triple::aarch64:
1436   case llvm::Triple::aarch64_32:
1437   case llvm::Triple::aarch64_be:
1438   case llvm::Triple::arm:
1439   case llvm::Triple::armeb:
1440   case llvm::Triple::thumb:
1441   case llvm::Triple::thumbeb:
1442     if (Triple.isOSDarwin() || Triple.isOSWindows())
1443       return true;
1444     return false;
1445 
1446   case llvm::Triple::ppc:
1447   case llvm::Triple::ppc64:
1448     if (Triple.isOSDarwin())
1449       return true;
1450     return false;
1451 
1452   case llvm::Triple::hexagon:
1453   case llvm::Triple::ppcle:
1454   case llvm::Triple::ppc64le:
1455   case llvm::Triple::riscv32:
1456   case llvm::Triple::riscv64:
1457   case llvm::Triple::systemz:
1458   case llvm::Triple::xcore:
1459     return false;
1460   }
1461 }
1462 
hasMultipleInvocations(const llvm::Triple & Triple,const ArgList & Args)1463 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1464                                    const ArgList &Args) {
1465   // Supported only on Darwin where we invoke the compiler multiple times
1466   // followed by an invocation to lipo.
1467   if (!Triple.isOSDarwin())
1468     return false;
1469   // If more than one "-arch <arch>" is specified, we're targeting multiple
1470   // architectures resulting in a fat binary.
1471   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1472 }
1473 
checkRemarksOptions(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)1474 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1475                                 const llvm::Triple &Triple) {
1476   // When enabling remarks, we need to error if:
1477   // * The remark file is specified but we're targeting multiple architectures,
1478   // which means more than one remark file is being generated.
1479   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1480   bool hasExplicitOutputFile =
1481       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1482   if (hasMultipleInvocations && hasExplicitOutputFile) {
1483     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1484         << "-foptimization-record-file";
1485     return false;
1486   }
1487   return true;
1488 }
1489 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const JobAction & JA)1490 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1491                                  const llvm::Triple &Triple,
1492                                  const InputInfo &Input,
1493                                  const InputInfo &Output, const JobAction &JA) {
1494   StringRef Format = "yaml";
1495   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1496     Format = A->getValue();
1497 
1498   CmdArgs.push_back("-opt-record-file");
1499 
1500   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1501   if (A) {
1502     CmdArgs.push_back(A->getValue());
1503   } else {
1504     bool hasMultipleArchs =
1505         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1506         Args.getAllArgValues(options::OPT_arch).size() > 1;
1507 
1508     SmallString<128> F;
1509 
1510     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1511       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1512         F = FinalOutput->getValue();
1513     } else {
1514       if (Format != "yaml" && // For YAML, keep the original behavior.
1515           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1516           Output.isFilename())
1517         F = Output.getFilename();
1518     }
1519 
1520     if (F.empty()) {
1521       // Use the input filename.
1522       F = llvm::sys::path::stem(Input.getBaseInput());
1523 
1524       // If we're compiling for an offload architecture (i.e. a CUDA device),
1525       // we need to make the file name for the device compilation different
1526       // from the host compilation.
1527       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1528           !JA.isDeviceOffloading(Action::OFK_Host)) {
1529         llvm::sys::path::replace_extension(F, "");
1530         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1531                                                  Triple.normalize());
1532         F += "-";
1533         F += JA.getOffloadingArch();
1534       }
1535     }
1536 
1537     // If we're having more than one "-arch", we should name the files
1538     // differently so that every cc1 invocation writes to a different file.
1539     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1540     // name from the triple.
1541     if (hasMultipleArchs) {
1542       // First, remember the extension.
1543       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1544       // then, remove it.
1545       llvm::sys::path::replace_extension(F, "");
1546       // attach -<arch> to it.
1547       F += "-";
1548       F += Triple.getArchName();
1549       // put back the extension.
1550       llvm::sys::path::replace_extension(F, OldExtension);
1551     }
1552 
1553     SmallString<32> Extension;
1554     Extension += "opt.";
1555     Extension += Format;
1556 
1557     llvm::sys::path::replace_extension(F, Extension);
1558     CmdArgs.push_back(Args.MakeArgString(F));
1559   }
1560 
1561   if (const Arg *A =
1562           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1563     CmdArgs.push_back("-opt-record-passes");
1564     CmdArgs.push_back(A->getValue());
1565   }
1566 
1567   if (!Format.empty()) {
1568     CmdArgs.push_back("-opt-record-format");
1569     CmdArgs.push_back(Format.data());
1570   }
1571 }
1572 
AddAAPCSVolatileBitfieldArgs(const ArgList & Args,ArgStringList & CmdArgs)1573 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1574   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1575                     options::OPT_fno_aapcs_bitfield_width, true))
1576     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1577 
1578   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1579     CmdArgs.push_back("-faapcs-bitfield-load");
1580 }
1581 
1582 namespace {
RenderARMABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1583 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1584                   ArgStringList &CmdArgs) {
1585   // Select the ABI to use.
1586   // FIXME: Support -meabi.
1587   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1588   const char *ABIName = nullptr;
1589   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1590     ABIName = A->getValue();
1591   } else {
1592     std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1593     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1594   }
1595 
1596   CmdArgs.push_back("-target-abi");
1597   CmdArgs.push_back(ABIName);
1598 }
1599 }
1600 
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const1601 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1602                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1603   RenderARMABI(Triple, Args, CmdArgs);
1604 
1605   // Determine floating point ABI from the options & target defaults.
1606   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1607   if (ABI == arm::FloatABI::Soft) {
1608     // Floating point operations and argument passing are soft.
1609     // FIXME: This changes CPP defines, we need -target-soft-float.
1610     CmdArgs.push_back("-msoft-float");
1611     CmdArgs.push_back("-mfloat-abi");
1612     CmdArgs.push_back("soft");
1613   } else if (ABI == arm::FloatABI::SoftFP) {
1614     // Floating point operations are hard, but argument passing is soft.
1615     CmdArgs.push_back("-mfloat-abi");
1616     CmdArgs.push_back("soft");
1617   } else {
1618     // Floating point operations and argument passing are hard.
1619     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1620     CmdArgs.push_back("-mfloat-abi");
1621     CmdArgs.push_back("hard");
1622   }
1623 
1624   // Forward the -mglobal-merge option for explicit control over the pass.
1625   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1626                                options::OPT_mno_global_merge)) {
1627     CmdArgs.push_back("-mllvm");
1628     if (A->getOption().matches(options::OPT_mno_global_merge))
1629       CmdArgs.push_back("-arm-global-merge=false");
1630     else
1631       CmdArgs.push_back("-arm-global-merge=true");
1632   }
1633 
1634   if (!Args.hasFlag(options::OPT_mimplicit_float,
1635                     options::OPT_mno_implicit_float, true))
1636     CmdArgs.push_back("-no-implicit-float");
1637 
1638   if (Args.getLastArg(options::OPT_mcmse))
1639     CmdArgs.push_back("-mcmse");
1640 
1641   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1642 }
1643 
RenderTargetOptions(const llvm::Triple & EffectiveTriple,const ArgList & Args,bool KernelOrKext,ArgStringList & CmdArgs) const1644 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1645                                 const ArgList &Args, bool KernelOrKext,
1646                                 ArgStringList &CmdArgs) const {
1647   const ToolChain &TC = getToolChain();
1648 
1649   // Add the target features
1650   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1651 
1652   // Add target specific flags.
1653   switch (TC.getArch()) {
1654   default:
1655     break;
1656 
1657   case llvm::Triple::arm:
1658   case llvm::Triple::armeb:
1659   case llvm::Triple::thumb:
1660   case llvm::Triple::thumbeb:
1661     // Use the effective triple, which takes into account the deployment target.
1662     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1663     CmdArgs.push_back("-fallow-half-arguments-and-returns");
1664     break;
1665 
1666   case llvm::Triple::aarch64:
1667   case llvm::Triple::aarch64_32:
1668   case llvm::Triple::aarch64_be:
1669     AddAArch64TargetArgs(Args, CmdArgs);
1670     CmdArgs.push_back("-fallow-half-arguments-and-returns");
1671     break;
1672 
1673   case llvm::Triple::mips:
1674   case llvm::Triple::mipsel:
1675   case llvm::Triple::mips64:
1676   case llvm::Triple::mips64el:
1677     AddMIPSTargetArgs(Args, CmdArgs);
1678     break;
1679 
1680   case llvm::Triple::ppc:
1681   case llvm::Triple::ppcle:
1682   case llvm::Triple::ppc64:
1683   case llvm::Triple::ppc64le:
1684     AddPPCTargetArgs(Args, CmdArgs);
1685     break;
1686 
1687   case llvm::Triple::riscv32:
1688   case llvm::Triple::riscv64:
1689     AddRISCVTargetArgs(Args, CmdArgs);
1690     break;
1691 
1692   case llvm::Triple::sparc:
1693   case llvm::Triple::sparcel:
1694   case llvm::Triple::sparcv9:
1695     AddSparcTargetArgs(Args, CmdArgs);
1696     break;
1697 
1698   case llvm::Triple::systemz:
1699     AddSystemZTargetArgs(Args, CmdArgs);
1700     break;
1701 
1702   case llvm::Triple::x86:
1703   case llvm::Triple::x86_64:
1704     AddX86TargetArgs(Args, CmdArgs);
1705     break;
1706 
1707   case llvm::Triple::lanai:
1708     AddLanaiTargetArgs(Args, CmdArgs);
1709     break;
1710 
1711   case llvm::Triple::hexagon:
1712     AddHexagonTargetArgs(Args, CmdArgs);
1713     break;
1714 
1715   case llvm::Triple::wasm32:
1716   case llvm::Triple::wasm64:
1717     AddWebAssemblyTargetArgs(Args, CmdArgs);
1718     break;
1719 
1720   case llvm::Triple::ve:
1721     AddVETargetArgs(Args, CmdArgs);
1722     break;
1723   }
1724 }
1725 
1726 namespace {
RenderAArch64ABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1727 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1728                       ArgStringList &CmdArgs) {
1729   const char *ABIName = nullptr;
1730   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1731     ABIName = A->getValue();
1732   else if (Triple.isOSDarwin())
1733     ABIName = "darwinpcs";
1734   else
1735     ABIName = "aapcs";
1736 
1737   CmdArgs.push_back("-target-abi");
1738   CmdArgs.push_back(ABIName);
1739 }
1740 }
1741 
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1742 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1743                                  ArgStringList &CmdArgs) const {
1744   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1745 
1746   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1747       Args.hasArg(options::OPT_mkernel) ||
1748       Args.hasArg(options::OPT_fapple_kext))
1749     CmdArgs.push_back("-disable-red-zone");
1750 
1751   if (!Args.hasFlag(options::OPT_mimplicit_float,
1752                     options::OPT_mno_implicit_float, true))
1753     CmdArgs.push_back("-no-implicit-float");
1754 
1755   RenderAArch64ABI(Triple, Args, CmdArgs);
1756 
1757   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1758                                options::OPT_mno_fix_cortex_a53_835769)) {
1759     CmdArgs.push_back("-mllvm");
1760     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1761       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1762     else
1763       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1764   } else if (Triple.isAndroid()) {
1765     // Enabled A53 errata (835769) workaround by default on android
1766     CmdArgs.push_back("-mllvm");
1767     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1768   }
1769 
1770   // Forward the -mglobal-merge option for explicit control over the pass.
1771   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1772                                options::OPT_mno_global_merge)) {
1773     CmdArgs.push_back("-mllvm");
1774     if (A->getOption().matches(options::OPT_mno_global_merge))
1775       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1776     else
1777       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1778   }
1779 
1780   // Enable/disable return address signing and indirect branch targets.
1781   if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1782                                options::OPT_mbranch_protection_EQ)) {
1783 
1784     const Driver &D = getToolChain().getDriver();
1785 
1786     StringRef Scope, Key;
1787     bool IndirectBranches;
1788 
1789     if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1790       Scope = A->getValue();
1791       if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1792           !Scope.equals("all"))
1793         D.Diag(diag::err_invalid_branch_protection)
1794             << Scope << A->getAsString(Args);
1795       Key = "a_key";
1796       IndirectBranches = false;
1797     } else {
1798       StringRef Err;
1799       llvm::AArch64::ParsedBranchProtection PBP;
1800       if (!llvm::AArch64::parseBranchProtection(A->getValue(), PBP, Err))
1801         D.Diag(diag::err_invalid_branch_protection)
1802             << Err << A->getAsString(Args);
1803       Scope = PBP.Scope;
1804       Key = PBP.Key;
1805       IndirectBranches = PBP.BranchTargetEnforcement;
1806     }
1807 
1808     CmdArgs.push_back(
1809         Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1810     CmdArgs.push_back(
1811         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1812     if (IndirectBranches)
1813       CmdArgs.push_back("-mbranch-target-enforce");
1814   }
1815 
1816   // Handle -msve_vector_bits=<bits>
1817   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1818     StringRef Val = A->getValue();
1819     const Driver &D = getToolChain().getDriver();
1820     if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1821         Val.equals("1024") || Val.equals("2048"))
1822       CmdArgs.push_back(
1823           Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
1824     // Silently drop requests for vector-length agnostic code as it's implied.
1825     else if (!Val.equals("scalable"))
1826       // Handle the unsupported values passed to msve-vector-bits.
1827       D.Diag(diag::err_drv_unsupported_option_argument)
1828           << A->getOption().getName() << Val;
1829   }
1830 
1831   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1832 }
1833 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1834 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1835                               ArgStringList &CmdArgs) const {
1836   const Driver &D = getToolChain().getDriver();
1837   StringRef CPUName;
1838   StringRef ABIName;
1839   const llvm::Triple &Triple = getToolChain().getTriple();
1840   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1841 
1842   CmdArgs.push_back("-target-abi");
1843   CmdArgs.push_back(ABIName.data());
1844 
1845   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1846   if (ABI == mips::FloatABI::Soft) {
1847     // Floating point operations and argument passing are soft.
1848     CmdArgs.push_back("-msoft-float");
1849     CmdArgs.push_back("-mfloat-abi");
1850     CmdArgs.push_back("soft");
1851   } else {
1852     // Floating point operations and argument passing are hard.
1853     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1854     CmdArgs.push_back("-mfloat-abi");
1855     CmdArgs.push_back("hard");
1856   }
1857 
1858   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1859                                options::OPT_mno_ldc1_sdc1)) {
1860     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1861       CmdArgs.push_back("-mllvm");
1862       CmdArgs.push_back("-mno-ldc1-sdc1");
1863     }
1864   }
1865 
1866   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1867                                options::OPT_mno_check_zero_division)) {
1868     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1869       CmdArgs.push_back("-mllvm");
1870       CmdArgs.push_back("-mno-check-zero-division");
1871     }
1872   }
1873 
1874   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1875     StringRef v = A->getValue();
1876     CmdArgs.push_back("-mllvm");
1877     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1878     A->claim();
1879   }
1880 
1881   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1882   Arg *ABICalls =
1883       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1884 
1885   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1886   // -mgpopt is the default for static, -fno-pic environments but these two
1887   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1888   // the only case where -mllvm -mgpopt is passed.
1889   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1890   //       passed explicitly when compiling something with -mabicalls
1891   //       (implictly) in affect. Currently the warning is in the backend.
1892   //
1893   // When the ABI in use is  N64, we also need to determine the PIC mode that
1894   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1895   bool NoABICalls =
1896       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1897 
1898   llvm::Reloc::Model RelocationModel;
1899   unsigned PICLevel;
1900   bool IsPIE;
1901   std::tie(RelocationModel, PICLevel, IsPIE) =
1902       ParsePICArgs(getToolChain(), Args);
1903 
1904   NoABICalls = NoABICalls ||
1905                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1906 
1907   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1908   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1909   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1910     CmdArgs.push_back("-mllvm");
1911     CmdArgs.push_back("-mgpopt");
1912 
1913     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1914                                       options::OPT_mno_local_sdata);
1915     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1916                                        options::OPT_mno_extern_sdata);
1917     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1918                                         options::OPT_mno_embedded_data);
1919     if (LocalSData) {
1920       CmdArgs.push_back("-mllvm");
1921       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1922         CmdArgs.push_back("-mlocal-sdata=1");
1923       } else {
1924         CmdArgs.push_back("-mlocal-sdata=0");
1925       }
1926       LocalSData->claim();
1927     }
1928 
1929     if (ExternSData) {
1930       CmdArgs.push_back("-mllvm");
1931       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1932         CmdArgs.push_back("-mextern-sdata=1");
1933       } else {
1934         CmdArgs.push_back("-mextern-sdata=0");
1935       }
1936       ExternSData->claim();
1937     }
1938 
1939     if (EmbeddedData) {
1940       CmdArgs.push_back("-mllvm");
1941       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1942         CmdArgs.push_back("-membedded-data=1");
1943       } else {
1944         CmdArgs.push_back("-membedded-data=0");
1945       }
1946       EmbeddedData->claim();
1947     }
1948 
1949   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1950     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1951 
1952   if (GPOpt)
1953     GPOpt->claim();
1954 
1955   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1956     StringRef Val = StringRef(A->getValue());
1957     if (mips::hasCompactBranches(CPUName)) {
1958       if (Val == "never" || Val == "always" || Val == "optimal") {
1959         CmdArgs.push_back("-mllvm");
1960         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1961       } else
1962         D.Diag(diag::err_drv_unsupported_option_argument)
1963             << A->getOption().getName() << Val;
1964     } else
1965       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1966   }
1967 
1968   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1969                                options::OPT_mno_relax_pic_calls)) {
1970     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1971       CmdArgs.push_back("-mllvm");
1972       CmdArgs.push_back("-mips-jalr-reloc=0");
1973     }
1974   }
1975 }
1976 
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1977 void Clang::AddPPCTargetArgs(const ArgList &Args,
1978                              ArgStringList &CmdArgs) const {
1979   // Select the ABI to use.
1980   const char *ABIName = nullptr;
1981   const llvm::Triple &T = getToolChain().getTriple();
1982   if (T.isOSBinFormatELF()) {
1983     switch (getToolChain().getArch()) {
1984     case llvm::Triple::ppc64: {
1985       if ((T.isOSFreeBSD() && T.getOSMajorVersion() >= 13) ||
1986           T.isOSOpenBSD() || T.isMusl())
1987         ABIName = "elfv2";
1988       else
1989         ABIName = "elfv1";
1990       break;
1991     }
1992     case llvm::Triple::ppc64le:
1993       ABIName = "elfv2";
1994       break;
1995     default:
1996       break;
1997     }
1998   }
1999 
2000   bool IEEELongDouble = false;
2001   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2002     StringRef V = A->getValue();
2003     if (V == "ieeelongdouble")
2004       IEEELongDouble = true;
2005     else if (V == "ibmlongdouble")
2006       IEEELongDouble = false;
2007     else if (V != "altivec")
2008       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2009       // the option if given as we don't have backend support for any targets
2010       // that don't use the altivec abi.
2011       ABIName = A->getValue();
2012   }
2013   if (IEEELongDouble)
2014     CmdArgs.push_back("-mabi=ieeelongdouble");
2015 
2016   ppc::FloatABI FloatABI =
2017       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
2018 
2019   if (FloatABI == ppc::FloatABI::Soft) {
2020     // Floating point operations and argument passing are soft.
2021     CmdArgs.push_back("-msoft-float");
2022     CmdArgs.push_back("-mfloat-abi");
2023     CmdArgs.push_back("soft");
2024   } else {
2025     // Floating point operations and argument passing are hard.
2026     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2027     CmdArgs.push_back("-mfloat-abi");
2028     CmdArgs.push_back("hard");
2029   }
2030 
2031   if (ABIName) {
2032     CmdArgs.push_back("-target-abi");
2033     CmdArgs.push_back(ABIName);
2034   }
2035 }
2036 
SetRISCVSmallDataLimit(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2037 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2038                                    ArgStringList &CmdArgs) {
2039   const Driver &D = TC.getDriver();
2040   const llvm::Triple &Triple = TC.getTriple();
2041   // Default small data limitation is eight.
2042   const char *SmallDataLimit = "8";
2043   // Get small data limitation.
2044   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2045                       options::OPT_fPIC)) {
2046     // Not support linker relaxation for PIC.
2047     SmallDataLimit = "0";
2048     if (Args.hasArg(options::OPT_G)) {
2049       D.Diag(diag::warn_drv_unsupported_sdata);
2050     }
2051   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2052                  .equals_lower("large") &&
2053              (Triple.getArch() == llvm::Triple::riscv64)) {
2054     // Not support linker relaxation for RV64 with large code model.
2055     SmallDataLimit = "0";
2056     if (Args.hasArg(options::OPT_G)) {
2057       D.Diag(diag::warn_drv_unsupported_sdata);
2058     }
2059   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2060     SmallDataLimit = A->getValue();
2061   }
2062   // Forward the -msmall-data-limit= option.
2063   CmdArgs.push_back("-msmall-data-limit");
2064   CmdArgs.push_back(SmallDataLimit);
2065 }
2066 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2067 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2068                                ArgStringList &CmdArgs) const {
2069   const llvm::Triple &Triple = getToolChain().getTriple();
2070   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2071 
2072   CmdArgs.push_back("-target-abi");
2073   CmdArgs.push_back(ABIName.data());
2074 
2075   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2076 
2077   std::string TuneCPU;
2078 
2079   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2080     StringRef Name = A->getValue();
2081 
2082     Name = llvm::RISCV::resolveTuneCPUAlias(Name, Triple.isArch64Bit());
2083     TuneCPU = std::string(Name);
2084   }
2085 
2086   if (!TuneCPU.empty()) {
2087     CmdArgs.push_back("-tune-cpu");
2088     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2089   }
2090 }
2091 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2092 void Clang::AddSparcTargetArgs(const ArgList &Args,
2093                                ArgStringList &CmdArgs) const {
2094   sparc::FloatABI FloatABI =
2095       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2096 
2097   if (FloatABI == sparc::FloatABI::Soft) {
2098     // Floating point operations and argument passing are soft.
2099     CmdArgs.push_back("-msoft-float");
2100     CmdArgs.push_back("-mfloat-abi");
2101     CmdArgs.push_back("soft");
2102   } else {
2103     // Floating point operations and argument passing are hard.
2104     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2105     CmdArgs.push_back("-mfloat-abi");
2106     CmdArgs.push_back("hard");
2107   }
2108 }
2109 
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2110 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2111                                  ArgStringList &CmdArgs) const {
2112   bool HasBackchain = Args.hasFlag(options::OPT_mbackchain,
2113                                    options::OPT_mno_backchain, false);
2114   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2115                                      options::OPT_mno_packed_stack, false);
2116   systemz::FloatABI FloatABI =
2117       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2118   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2119   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2120     const Driver &D = getToolChain().getDriver();
2121     D.Diag(diag::err_drv_unsupported_opt)
2122       << "-mpacked-stack -mbackchain -mhard-float";
2123   }
2124   if (HasBackchain)
2125     CmdArgs.push_back("-mbackchain");
2126   if (HasPackedStack)
2127     CmdArgs.push_back("-mpacked-stack");
2128   if (HasSoftFloat) {
2129     // Floating point operations and argument passing are soft.
2130     CmdArgs.push_back("-msoft-float");
2131     CmdArgs.push_back("-mfloat-abi");
2132     CmdArgs.push_back("soft");
2133   }
2134 }
2135 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2136 void Clang::AddX86TargetArgs(const ArgList &Args,
2137                              ArgStringList &CmdArgs) const {
2138   const Driver &D = getToolChain().getDriver();
2139   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2140 
2141   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2142       Args.hasArg(options::OPT_mkernel) ||
2143       Args.hasArg(options::OPT_fapple_kext))
2144     CmdArgs.push_back("-disable-red-zone");
2145 
2146   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2147                     options::OPT_mno_tls_direct_seg_refs, true))
2148     CmdArgs.push_back("-mno-tls-direct-seg-refs");
2149 
2150   // Default to avoid implicit floating-point for kernel/kext code, but allow
2151   // that to be overridden with -mno-soft-float.
2152   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2153                           Args.hasArg(options::OPT_fapple_kext));
2154   if (Arg *A = Args.getLastArg(
2155           options::OPT_msoft_float, options::OPT_mno_soft_float,
2156           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2157     const Option &O = A->getOption();
2158     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2159                        O.matches(options::OPT_msoft_float));
2160   }
2161   if (NoImplicitFloat)
2162     CmdArgs.push_back("-no-implicit-float");
2163 
2164   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2165     StringRef Value = A->getValue();
2166     if (Value == "intel" || Value == "att") {
2167       CmdArgs.push_back("-mllvm");
2168       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2169     } else {
2170       D.Diag(diag::err_drv_unsupported_option_argument)
2171           << A->getOption().getName() << Value;
2172     }
2173   } else if (D.IsCLMode()) {
2174     CmdArgs.push_back("-mllvm");
2175     CmdArgs.push_back("-x86-asm-syntax=intel");
2176   }
2177 
2178   // Set flags to support MCU ABI.
2179   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2180     CmdArgs.push_back("-mfloat-abi");
2181     CmdArgs.push_back("soft");
2182     CmdArgs.push_back("-mstack-alignment=4");
2183   }
2184 
2185   // Handle -mtune.
2186 
2187   // Default to "generic" unless -march is present or targetting the PS4.
2188   std::string TuneCPU;
2189   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2190       !getToolChain().getTriple().isPS4CPU())
2191     TuneCPU = "generic";
2192 
2193   // Override based on -mtune.
2194   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2195     StringRef Name = A->getValue();
2196 
2197     if (Name == "native") {
2198       Name = llvm::sys::getHostCPUName();
2199       if (!Name.empty())
2200         TuneCPU = std::string(Name);
2201     } else
2202       TuneCPU = std::string(Name);
2203   }
2204 
2205   if (!TuneCPU.empty()) {
2206     CmdArgs.push_back("-tune-cpu");
2207     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2208   }
2209 }
2210 
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2211 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2212                                  ArgStringList &CmdArgs) const {
2213   CmdArgs.push_back("-mqdsp6-compat");
2214   CmdArgs.push_back("-Wreturn-type");
2215 
2216   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2217     CmdArgs.push_back("-mllvm");
2218     CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
2219                                          Twine(G.getValue())));
2220   }
2221 
2222   if (!Args.hasArg(options::OPT_fno_short_enums))
2223     CmdArgs.push_back("-fshort-enums");
2224   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2225     CmdArgs.push_back("-mllvm");
2226     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2227   }
2228   CmdArgs.push_back("-mllvm");
2229   CmdArgs.push_back("-machine-sink-split=0");
2230 }
2231 
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2232 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2233                                ArgStringList &CmdArgs) const {
2234   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2235     StringRef CPUName = A->getValue();
2236 
2237     CmdArgs.push_back("-target-cpu");
2238     CmdArgs.push_back(Args.MakeArgString(CPUName));
2239   }
2240   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2241     StringRef Value = A->getValue();
2242     // Only support mregparm=4 to support old usage. Report error for all other
2243     // cases.
2244     int Mregparm;
2245     if (Value.getAsInteger(10, Mregparm)) {
2246       if (Mregparm != 4) {
2247         getToolChain().getDriver().Diag(
2248             diag::err_drv_unsupported_option_argument)
2249             << A->getOption().getName() << Value;
2250       }
2251     }
2252   }
2253 }
2254 
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2255 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2256                                      ArgStringList &CmdArgs) const {
2257   // Default to "hidden" visibility.
2258   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2259                    options::OPT_fvisibility_ms_compat)) {
2260     CmdArgs.push_back("-fvisibility");
2261     CmdArgs.push_back("hidden");
2262   }
2263 }
2264 
AddVETargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2265 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2266   // Floating point operations and argument passing are hard.
2267   CmdArgs.push_back("-mfloat-abi");
2268   CmdArgs.push_back("hard");
2269 }
2270 
DumpCompilationDatabase(Compilation & C,StringRef Filename,StringRef Target,const InputInfo & Output,const InputInfo & Input,const ArgList & Args) const2271 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2272                                     StringRef Target, const InputInfo &Output,
2273                                     const InputInfo &Input, const ArgList &Args) const {
2274   // If this is a dry run, do not create the compilation database file.
2275   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2276     return;
2277 
2278   using llvm::yaml::escape;
2279   const Driver &D = getToolChain().getDriver();
2280 
2281   if (!CompilationDatabase) {
2282     std::error_code EC;
2283     auto File = std::make_unique<llvm::raw_fd_ostream>(
2284         Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
2285     if (EC) {
2286       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2287                                                        << EC.message();
2288       return;
2289     }
2290     CompilationDatabase = std::move(File);
2291   }
2292   auto &CDB = *CompilationDatabase;
2293   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2294   if (!CWD)
2295     CWD = ".";
2296   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2297   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2298   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2299   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2300   SmallString<128> Buf;
2301   Buf = "-x";
2302   Buf += types::getTypeName(Input.getType());
2303   CDB << ", \"" << escape(Buf) << "\"";
2304   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2305     Buf = "--sysroot=";
2306     Buf += D.SysRoot;
2307     CDB << ", \"" << escape(Buf) << "\"";
2308   }
2309   CDB << ", \"" << escape(Input.getFilename()) << "\"";
2310   for (auto &A: Args) {
2311     auto &O = A->getOption();
2312     // Skip language selection, which is positional.
2313     if (O.getID() == options::OPT_x)
2314       continue;
2315     // Skip writing dependency output and the compilation database itself.
2316     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2317       continue;
2318     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2319       continue;
2320     // Skip inputs.
2321     if (O.getKind() == Option::InputClass)
2322       continue;
2323     // All other arguments are quoted and appended.
2324     ArgStringList ASL;
2325     A->render(Args, ASL);
2326     for (auto &it: ASL)
2327       CDB << ", \"" << escape(it) << "\"";
2328   }
2329   Buf = "--target=";
2330   Buf += Target;
2331   CDB << ", \"" << escape(Buf) << "\"]},\n";
2332 }
2333 
DumpCompilationDatabaseFragmentToDir(StringRef Dir,Compilation & C,StringRef Target,const InputInfo & Output,const InputInfo & Input,const llvm::opt::ArgList & Args) const2334 void Clang::DumpCompilationDatabaseFragmentToDir(
2335     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2336     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2337   // If this is a dry run, do not create the compilation database file.
2338   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2339     return;
2340 
2341   if (CompilationDatabase)
2342     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2343 
2344   SmallString<256> Path = Dir;
2345   const auto &Driver = C.getDriver();
2346   Driver.getVFS().makeAbsolute(Path);
2347   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2348   if (Err) {
2349     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2350     return;
2351   }
2352 
2353   llvm::sys::path::append(
2354       Path,
2355       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2356   int FD;
2357   SmallString<256> TempPath;
2358   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2359                                         llvm::sys::fs::OF_Text);
2360   if (Err) {
2361     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2362     return;
2363   }
2364   CompilationDatabase =
2365       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2366   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2367 }
2368 
CheckARMImplicitITArg(StringRef Value)2369 static bool CheckARMImplicitITArg(StringRef Value) {
2370   return Value == "always" || Value == "never" || Value == "arm" ||
2371          Value == "thumb";
2372 }
2373 
AddARMImplicitITArgs(const ArgList & Args,ArgStringList & CmdArgs,StringRef Value)2374 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2375                                  StringRef Value) {
2376   CmdArgs.push_back("-mllvm");
2377   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2378 }
2379 
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2380 static void CollectArgsForIntegratedAssembler(Compilation &C,
2381                                               const ArgList &Args,
2382                                               ArgStringList &CmdArgs,
2383                                               const Driver &D) {
2384   if (UseRelaxAll(C, Args))
2385     CmdArgs.push_back("-mrelax-all");
2386 
2387   // Only default to -mincremental-linker-compatible if we think we are
2388   // targeting the MSVC linker.
2389   bool DefaultIncrementalLinkerCompatible =
2390       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2391   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2392                    options::OPT_mno_incremental_linker_compatible,
2393                    DefaultIncrementalLinkerCompatible))
2394     CmdArgs.push_back("-mincremental-linker-compatible");
2395 
2396   // If you add more args here, also add them to the block below that
2397   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2398 
2399   // When passing -I arguments to the assembler we sometimes need to
2400   // unconditionally take the next argument.  For example, when parsing
2401   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2402   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2403   // arg after parsing the '-I' arg.
2404   bool TakeNextArg = false;
2405 
2406   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2407   bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2408   const char *MipsTargetFeature = nullptr;
2409   StringRef ImplicitIt;
2410   for (const Arg *A :
2411        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2412                      options::OPT_mimplicit_it_EQ)) {
2413     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2414       switch (C.getDefaultToolChain().getArch()) {
2415       case llvm::Triple::arm:
2416       case llvm::Triple::armeb:
2417       case llvm::Triple::thumb:
2418       case llvm::Triple::thumbeb:
2419         // Only store the value; the last value set takes effect.
2420         ImplicitIt = A->getValue();
2421         if (!CheckARMImplicitITArg(ImplicitIt))
2422           D.Diag(diag::err_drv_unsupported_option_argument)
2423               << A->getOption().getName() << ImplicitIt;
2424         continue;
2425       default:
2426         break;
2427       }
2428     }
2429 
2430     A->claim();
2431 
2432     for (StringRef Value : A->getValues()) {
2433       if (TakeNextArg) {
2434         CmdArgs.push_back(Value.data());
2435         TakeNextArg = false;
2436         continue;
2437       }
2438 
2439       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2440           Value == "-mbig-obj")
2441         continue; // LLVM handles bigobj automatically
2442 
2443       switch (C.getDefaultToolChain().getArch()) {
2444       default:
2445         break;
2446       case llvm::Triple::thumb:
2447       case llvm::Triple::thumbeb:
2448       case llvm::Triple::arm:
2449       case llvm::Triple::armeb:
2450         if (Value.startswith("-mimplicit-it=")) {
2451           // Only store the value; the last value set takes effect.
2452           ImplicitIt = Value.split("=").second;
2453           if (CheckARMImplicitITArg(ImplicitIt))
2454             continue;
2455         }
2456         if (Value == "-mthumb")
2457           // -mthumb has already been processed in ComputeLLVMTriple()
2458           // recognize but skip over here.
2459           continue;
2460         break;
2461       case llvm::Triple::mips:
2462       case llvm::Triple::mipsel:
2463       case llvm::Triple::mips64:
2464       case llvm::Triple::mips64el:
2465         if (Value == "--trap") {
2466           CmdArgs.push_back("-target-feature");
2467           CmdArgs.push_back("+use-tcc-in-div");
2468           continue;
2469         }
2470         if (Value == "--break") {
2471           CmdArgs.push_back("-target-feature");
2472           CmdArgs.push_back("-use-tcc-in-div");
2473           continue;
2474         }
2475         if (Value.startswith("-msoft-float")) {
2476           CmdArgs.push_back("-target-feature");
2477           CmdArgs.push_back("+soft-float");
2478           continue;
2479         }
2480         if (Value.startswith("-mhard-float")) {
2481           CmdArgs.push_back("-target-feature");
2482           CmdArgs.push_back("-soft-float");
2483           continue;
2484         }
2485 
2486         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2487                                 .Case("-mips1", "+mips1")
2488                                 .Case("-mips2", "+mips2")
2489                                 .Case("-mips3", "+mips3")
2490                                 .Case("-mips4", "+mips4")
2491                                 .Case("-mips5", "+mips5")
2492                                 .Case("-mips32", "+mips32")
2493                                 .Case("-mips32r2", "+mips32r2")
2494                                 .Case("-mips32r3", "+mips32r3")
2495                                 .Case("-mips32r5", "+mips32r5")
2496                                 .Case("-mips32r6", "+mips32r6")
2497                                 .Case("-mips64", "+mips64")
2498                                 .Case("-mips64r2", "+mips64r2")
2499                                 .Case("-mips64r3", "+mips64r3")
2500                                 .Case("-mips64r5", "+mips64r5")
2501                                 .Case("-mips64r6", "+mips64r6")
2502                                 .Default(nullptr);
2503         if (MipsTargetFeature)
2504           continue;
2505       }
2506 
2507       if (Value == "-force_cpusubtype_ALL") {
2508         // Do nothing, this is the default and we don't support anything else.
2509       } else if (Value == "-L") {
2510         CmdArgs.push_back("-msave-temp-labels");
2511       } else if (Value == "--fatal-warnings") {
2512         CmdArgs.push_back("-massembler-fatal-warnings");
2513       } else if (Value == "--no-warn" || Value == "-W") {
2514         CmdArgs.push_back("-massembler-no-warn");
2515       } else if (Value == "--noexecstack") {
2516         UseNoExecStack = true;
2517       } else if (Value.startswith("-compress-debug-sections") ||
2518                  Value.startswith("--compress-debug-sections") ||
2519                  Value == "-nocompress-debug-sections" ||
2520                  Value == "--nocompress-debug-sections") {
2521         CmdArgs.push_back(Value.data());
2522       } else if (Value == "-mrelax-relocations=yes" ||
2523                  Value == "--mrelax-relocations=yes") {
2524         UseRelaxRelocations = true;
2525       } else if (Value == "-mrelax-relocations=no" ||
2526                  Value == "--mrelax-relocations=no") {
2527         UseRelaxRelocations = false;
2528       } else if (Value.startswith("-I")) {
2529         CmdArgs.push_back(Value.data());
2530         // We need to consume the next argument if the current arg is a plain
2531         // -I. The next arg will be the include directory.
2532         if (Value == "-I")
2533           TakeNextArg = true;
2534       } else if (Value.startswith("-gdwarf-")) {
2535         // "-gdwarf-N" options are not cc1as options.
2536         unsigned DwarfVersion = DwarfVersionNum(Value);
2537         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2538           CmdArgs.push_back(Value.data());
2539         } else {
2540           RenderDebugEnablingArgs(Args, CmdArgs,
2541                                   codegenoptions::LimitedDebugInfo,
2542                                   DwarfVersion, llvm::DebuggerKind::Default);
2543         }
2544       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2545                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2546         // Do nothing, we'll validate it later.
2547       } else if (Value == "-defsym") {
2548           if (A->getNumValues() != 2) {
2549             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2550             break;
2551           }
2552           const char *S = A->getValue(1);
2553           auto Pair = StringRef(S).split('=');
2554           auto Sym = Pair.first;
2555           auto SVal = Pair.second;
2556 
2557           if (Sym.empty() || SVal.empty()) {
2558             D.Diag(diag::err_drv_defsym_invalid_format) << S;
2559             break;
2560           }
2561           int64_t IVal;
2562           if (SVal.getAsInteger(0, IVal)) {
2563             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2564             break;
2565           }
2566           CmdArgs.push_back(Value.data());
2567           TakeNextArg = true;
2568       } else if (Value == "-fdebug-compilation-dir") {
2569         CmdArgs.push_back("-fdebug-compilation-dir");
2570         TakeNextArg = true;
2571       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2572         // The flag is a -Wa / -Xassembler argument and Options doesn't
2573         // parse the argument, so this isn't automatically aliased to
2574         // -fdebug-compilation-dir (without '=') here.
2575         CmdArgs.push_back("-fdebug-compilation-dir");
2576         CmdArgs.push_back(Value.data());
2577       } else if (Value == "--version") {
2578         D.PrintVersion(C, llvm::outs());
2579       } else {
2580         D.Diag(diag::err_drv_unsupported_option_argument)
2581             << A->getOption().getName() << Value;
2582       }
2583     }
2584   }
2585   if (ImplicitIt.size())
2586     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2587   if (UseRelaxRelocations)
2588     CmdArgs.push_back("--mrelax-relocations");
2589   if (UseNoExecStack)
2590     CmdArgs.push_back("-mnoexecstack");
2591   if (MipsTargetFeature != nullptr) {
2592     CmdArgs.push_back("-target-feature");
2593     CmdArgs.push_back(MipsTargetFeature);
2594   }
2595 
2596   // forward -fembed-bitcode to assmebler
2597   if (C.getDriver().embedBitcodeEnabled() ||
2598       C.getDriver().embedBitcodeMarkerOnly())
2599     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2600 }
2601 
RenderFloatingPointOptions(const ToolChain & TC,const Driver & D,bool OFastEnabled,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)2602 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2603                                        bool OFastEnabled, const ArgList &Args,
2604                                        ArgStringList &CmdArgs,
2605                                        const JobAction &JA) {
2606   // Handle various floating point optimization flags, mapping them to the
2607   // appropriate LLVM code generation flags. This is complicated by several
2608   // "umbrella" flags, so we do this by stepping through the flags incrementally
2609   // adjusting what we think is enabled/disabled, then at the end setting the
2610   // LLVM flags based on the final state.
2611   bool HonorINFs = true;
2612   bool HonorNaNs = true;
2613   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2614   bool MathErrno = TC.IsMathErrnoDefault();
2615   bool AssociativeMath = false;
2616   bool ReciprocalMath = false;
2617   bool SignedZeros = true;
2618   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2619   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2620                                     // overriden by ffp-exception-behavior?
2621   bool RoundingFPMath = false;
2622   bool RoundingMathPresent = false; // Is rounding-math in args?
2623   // -ffp-model values: strict, fast, precise
2624   StringRef FPModel = "";
2625   // -ffp-exception-behavior options: strict, maytrap, ignore
2626   StringRef FPExceptionBehavior = "";
2627   const llvm::DenormalMode DefaultDenormalFPMath =
2628       TC.getDefaultDenormalModeForType(Args, JA);
2629   const llvm::DenormalMode DefaultDenormalFP32Math =
2630       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2631 
2632   llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2633   llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2634   StringRef FPContract = "";
2635   bool StrictFPModel = false;
2636 
2637 
2638   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2639     CmdArgs.push_back("-mlimit-float-precision");
2640     CmdArgs.push_back(A->getValue());
2641   }
2642 
2643   for (const Arg *A : Args) {
2644     auto optID = A->getOption().getID();
2645     bool PreciseFPModel = false;
2646     switch (optID) {
2647     default:
2648       break;
2649     case options::OPT_ffp_model_EQ: {
2650       // If -ffp-model= is seen, reset to fno-fast-math
2651       HonorINFs = true;
2652       HonorNaNs = true;
2653       // Turning *off* -ffast-math restores the toolchain default.
2654       MathErrno = TC.IsMathErrnoDefault();
2655       AssociativeMath = false;
2656       ReciprocalMath = false;
2657       SignedZeros = true;
2658       // -fno_fast_math restores default denormal and fpcontract handling
2659       FPContract = "";
2660       DenormalFPMath = llvm::DenormalMode::getIEEE();
2661 
2662       // FIXME: The target may have picked a non-IEEE default mode here based on
2663       // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2664       DenormalFP32Math = llvm::DenormalMode::getIEEE();
2665 
2666       StringRef Val = A->getValue();
2667       if (OFastEnabled && !Val.equals("fast")) {
2668           // Only -ffp-model=fast is compatible with OFast, ignore.
2669         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2670           << Args.MakeArgString("-ffp-model=" + Val)
2671           << "-Ofast";
2672         break;
2673       }
2674       StrictFPModel = false;
2675       PreciseFPModel = true;
2676       // ffp-model= is a Driver option, it is entirely rewritten into more
2677       // granular options before being passed into cc1.
2678       // Use the gcc option in the switch below.
2679       if (!FPModel.empty() && !FPModel.equals(Val)) {
2680         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2681           << Args.MakeArgString("-ffp-model=" + FPModel)
2682           << Args.MakeArgString("-ffp-model=" + Val);
2683         FPContract = "";
2684       }
2685       if (Val.equals("fast")) {
2686         optID = options::OPT_ffast_math;
2687         FPModel = Val;
2688         FPContract = "fast";
2689       } else if (Val.equals("precise")) {
2690         optID = options::OPT_ffp_contract;
2691         FPModel = Val;
2692         FPContract = "fast";
2693         PreciseFPModel = true;
2694       } else if (Val.equals("strict")) {
2695         StrictFPModel = true;
2696         optID = options::OPT_frounding_math;
2697         FPExceptionBehavior = "strict";
2698         FPModel = Val;
2699         FPContract = "off";
2700         TrappingMath = true;
2701       } else
2702         D.Diag(diag::err_drv_unsupported_option_argument)
2703             << A->getOption().getName() << Val;
2704       break;
2705       }
2706     }
2707 
2708     switch (optID) {
2709     // If this isn't an FP option skip the claim below
2710     default: continue;
2711 
2712     // Options controlling individual features
2713     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2714     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2715     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2716     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2717     case options::OPT_fmath_errno:          MathErrno = true;         break;
2718     case options::OPT_fno_math_errno:       MathErrno = false;        break;
2719     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2720     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2721     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2722     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2723     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2724     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2725     case options::OPT_ftrapping_math:
2726       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2727           !FPExceptionBehavior.equals("strict"))
2728         // Warn that previous value of option is overridden.
2729         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2730           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2731           << "-ftrapping-math";
2732       TrappingMath = true;
2733       TrappingMathPresent = true;
2734       FPExceptionBehavior = "strict";
2735       break;
2736     case options::OPT_fno_trapping_math:
2737       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2738           !FPExceptionBehavior.equals("ignore"))
2739         // Warn that previous value of option is overridden.
2740         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2741           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2742           << "-fno-trapping-math";
2743       TrappingMath = false;
2744       TrappingMathPresent = true;
2745       FPExceptionBehavior = "ignore";
2746       break;
2747 
2748     case options::OPT_frounding_math:
2749       RoundingFPMath = true;
2750       RoundingMathPresent = true;
2751       break;
2752 
2753     case options::OPT_fno_rounding_math:
2754       RoundingFPMath = false;
2755       RoundingMathPresent = false;
2756       break;
2757 
2758     case options::OPT_fdenormal_fp_math_EQ:
2759       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2760       if (!DenormalFPMath.isValid()) {
2761         D.Diag(diag::err_drv_invalid_value)
2762             << A->getAsString(Args) << A->getValue();
2763       }
2764       break;
2765 
2766     case options::OPT_fdenormal_fp_math_f32_EQ:
2767       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2768       if (!DenormalFP32Math.isValid()) {
2769         D.Diag(diag::err_drv_invalid_value)
2770             << A->getAsString(Args) << A->getValue();
2771       }
2772       break;
2773 
2774     // Validate and pass through -ffp-contract option.
2775     case options::OPT_ffp_contract: {
2776       StringRef Val = A->getValue();
2777       if (PreciseFPModel) {
2778         // -ffp-model=precise enables ffp-contract=fast as a side effect
2779         // the FPContract value has already been set to a string literal
2780         // and the Val string isn't a pertinent value.
2781         ;
2782       } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off"))
2783         FPContract = Val;
2784       else
2785         D.Diag(diag::err_drv_unsupported_option_argument)
2786            << A->getOption().getName() << Val;
2787       break;
2788     }
2789 
2790     // Validate and pass through -ffp-model option.
2791     case options::OPT_ffp_model_EQ:
2792       // This should only occur in the error case
2793       // since the optID has been replaced by a more granular
2794       // floating point option.
2795       break;
2796 
2797     // Validate and pass through -ffp-exception-behavior option.
2798     case options::OPT_ffp_exception_behavior_EQ: {
2799       StringRef Val = A->getValue();
2800       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2801           !FPExceptionBehavior.equals(Val))
2802         // Warn that previous value of option is overridden.
2803         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2804           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2805           << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2806       TrappingMath = TrappingMathPresent = false;
2807       if (Val.equals("ignore") || Val.equals("maytrap"))
2808         FPExceptionBehavior = Val;
2809       else if (Val.equals("strict")) {
2810         FPExceptionBehavior = Val;
2811         TrappingMath = TrappingMathPresent = true;
2812       } else
2813         D.Diag(diag::err_drv_unsupported_option_argument)
2814             << A->getOption().getName() << Val;
2815       break;
2816     }
2817 
2818     case options::OPT_ffinite_math_only:
2819       HonorINFs = false;
2820       HonorNaNs = false;
2821       break;
2822     case options::OPT_fno_finite_math_only:
2823       HonorINFs = true;
2824       HonorNaNs = true;
2825       break;
2826 
2827     case options::OPT_funsafe_math_optimizations:
2828       AssociativeMath = true;
2829       ReciprocalMath = true;
2830       SignedZeros = false;
2831       TrappingMath = false;
2832       FPExceptionBehavior = "";
2833       break;
2834     case options::OPT_fno_unsafe_math_optimizations:
2835       AssociativeMath = false;
2836       ReciprocalMath = false;
2837       SignedZeros = true;
2838       TrappingMath = true;
2839       FPExceptionBehavior = "strict";
2840 
2841       // The target may have opted to flush by default, so force IEEE.
2842       DenormalFPMath = llvm::DenormalMode::getIEEE();
2843       DenormalFP32Math = llvm::DenormalMode::getIEEE();
2844       break;
2845 
2846     case options::OPT_Ofast:
2847       // If -Ofast is the optimization level, then -ffast-math should be enabled
2848       if (!OFastEnabled)
2849         continue;
2850       LLVM_FALLTHROUGH;
2851     case options::OPT_ffast_math:
2852       HonorINFs = false;
2853       HonorNaNs = false;
2854       MathErrno = false;
2855       AssociativeMath = true;
2856       ReciprocalMath = true;
2857       SignedZeros = false;
2858       TrappingMath = false;
2859       RoundingFPMath = false;
2860       // If fast-math is set then set the fp-contract mode to fast.
2861       FPContract = "fast";
2862       break;
2863     case options::OPT_fno_fast_math:
2864       HonorINFs = true;
2865       HonorNaNs = true;
2866       // Turning on -ffast-math (with either flag) removes the need for
2867       // MathErrno. However, turning *off* -ffast-math merely restores the
2868       // toolchain default (which may be false).
2869       MathErrno = TC.IsMathErrnoDefault();
2870       AssociativeMath = false;
2871       ReciprocalMath = false;
2872       SignedZeros = true;
2873       TrappingMath = false;
2874       RoundingFPMath = false;
2875       // -fno_fast_math restores default denormal and fpcontract handling
2876       DenormalFPMath = DefaultDenormalFPMath;
2877       DenormalFP32Math = llvm::DenormalMode::getIEEE();
2878       FPContract = "";
2879       break;
2880     }
2881     if (StrictFPModel) {
2882       // If -ffp-model=strict has been specified on command line but
2883       // subsequent options conflict then emit warning diagnostic.
2884       if (HonorINFs && HonorNaNs &&
2885         !AssociativeMath && !ReciprocalMath &&
2886         SignedZeros && TrappingMath && RoundingFPMath &&
2887         (FPContract.equals("off") || FPContract.empty()) &&
2888         DenormalFPMath == llvm::DenormalMode::getIEEE() &&
2889         DenormalFP32Math == llvm::DenormalMode::getIEEE())
2890         // OK: Current Arg doesn't conflict with -ffp-model=strict
2891         ;
2892       else {
2893         StrictFPModel = false;
2894         FPModel = "";
2895         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2896             << "-ffp-model=strict" <<
2897             ((A->getNumValues() == 0) ?  A->getSpelling()
2898             : Args.MakeArgString(A->getSpelling() + A->getValue()));
2899       }
2900     }
2901 
2902     // If we handled this option claim it
2903     A->claim();
2904   }
2905 
2906   if (!HonorINFs)
2907     CmdArgs.push_back("-menable-no-infs");
2908 
2909   if (!HonorNaNs)
2910     CmdArgs.push_back("-menable-no-nans");
2911 
2912   if (MathErrno)
2913     CmdArgs.push_back("-fmath-errno");
2914 
2915   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2916       !TrappingMath)
2917     CmdArgs.push_back("-menable-unsafe-fp-math");
2918 
2919   if (!SignedZeros)
2920     CmdArgs.push_back("-fno-signed-zeros");
2921 
2922   if (AssociativeMath && !SignedZeros && !TrappingMath)
2923     CmdArgs.push_back("-mreassociate");
2924 
2925   if (ReciprocalMath)
2926     CmdArgs.push_back("-freciprocal-math");
2927 
2928   if (TrappingMath) {
2929     // FP Exception Behavior is also set to strict
2930     assert(FPExceptionBehavior.equals("strict"));
2931   }
2932 
2933   // The default is IEEE.
2934   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
2935     llvm::SmallString<64> DenormFlag;
2936     llvm::raw_svector_ostream ArgStr(DenormFlag);
2937     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
2938     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2939   }
2940 
2941   // Add f32 specific denormal mode flag if it's different.
2942   if (DenormalFP32Math != DenormalFPMath) {
2943     llvm::SmallString<64> DenormFlag;
2944     llvm::raw_svector_ostream ArgStr(DenormFlag);
2945     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
2946     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2947   }
2948 
2949   if (!FPContract.empty())
2950     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2951 
2952   if (!RoundingFPMath)
2953     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
2954 
2955   if (RoundingFPMath && RoundingMathPresent)
2956     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
2957 
2958   if (!FPExceptionBehavior.empty())
2959     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
2960                       FPExceptionBehavior));
2961 
2962   ParseMRecip(D, Args, CmdArgs);
2963 
2964   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2965   // individual features enabled by -ffast-math instead of the option itself as
2966   // that's consistent with gcc's behaviour.
2967   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2968       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
2969     CmdArgs.push_back("-ffast-math");
2970     if (FPModel.equals("fast")) {
2971       if (FPContract.equals("fast"))
2972         // All set, do nothing.
2973         ;
2974       else if (FPContract.empty())
2975         // Enable -ffp-contract=fast
2976         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2977       else
2978         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2979           << "-ffp-model=fast"
2980           << Args.MakeArgString("-ffp-contract=" + FPContract);
2981     }
2982   }
2983 
2984   // Handle __FINITE_MATH_ONLY__ similarly.
2985   if (!HonorINFs && !HonorNaNs)
2986     CmdArgs.push_back("-ffinite-math-only");
2987 
2988   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2989     CmdArgs.push_back("-mfpmath");
2990     CmdArgs.push_back(A->getValue());
2991   }
2992 
2993   // Disable a codegen optimization for floating-point casts.
2994   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2995                    options::OPT_fstrict_float_cast_overflow, false))
2996     CmdArgs.push_back("-fno-strict-float-cast-overflow");
2997 }
2998 
RenderAnalyzerOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input)2999 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3000                                   const llvm::Triple &Triple,
3001                                   const InputInfo &Input) {
3002   // Enable region store model by default.
3003   CmdArgs.push_back("-analyzer-store=region");
3004 
3005   // Treat blocks as analysis entry points.
3006   CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3007 
3008   // Add default argument set.
3009   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3010     CmdArgs.push_back("-analyzer-checker=core");
3011     CmdArgs.push_back("-analyzer-checker=apiModeling");
3012 
3013     if (!Triple.isWindowsMSVCEnvironment()) {
3014       CmdArgs.push_back("-analyzer-checker=unix");
3015     } else {
3016       // Enable "unix" checkers that also work on Windows.
3017       CmdArgs.push_back("-analyzer-checker=unix.API");
3018       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3019       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3020       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3021       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3022       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3023     }
3024 
3025     // Disable some unix checkers for PS4.
3026     if (Triple.isPS4CPU()) {
3027       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3028       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3029     }
3030 
3031     if (Triple.isOSDarwin()) {
3032       CmdArgs.push_back("-analyzer-checker=osx");
3033       CmdArgs.push_back(
3034           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3035     }
3036     else if (Triple.isOSFuchsia())
3037       CmdArgs.push_back("-analyzer-checker=fuchsia");
3038 
3039     CmdArgs.push_back("-analyzer-checker=deadcode");
3040 
3041     if (types::isCXX(Input.getType()))
3042       CmdArgs.push_back("-analyzer-checker=cplusplus");
3043 
3044     if (!Triple.isPS4CPU()) {
3045       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3046       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3047       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3048       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3049       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3050       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3051     }
3052 
3053     // Default nullability checks.
3054     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3055     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3056   }
3057 
3058   // Set the output format. The default is plist, for (lame) historical reasons.
3059   CmdArgs.push_back("-analyzer-output");
3060   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3061     CmdArgs.push_back(A->getValue());
3062   else
3063     CmdArgs.push_back("plist");
3064 
3065   // Disable the presentation of standard compiler warnings when using
3066   // --analyze.  We only want to show static analyzer diagnostics or frontend
3067   // errors.
3068   CmdArgs.push_back("-w");
3069 
3070   // Add -Xanalyzer arguments when running as analyzer.
3071   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3072 }
3073 
RenderSSPOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext)3074 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3075                              const ArgList &Args, ArgStringList &CmdArgs,
3076                              bool KernelOrKext) {
3077   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3078 
3079   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3080   // doesn't even have a stack!
3081   if (EffectiveTriple.isNVPTX())
3082     return;
3083 
3084   // -stack-protector=0 is default.
3085   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3086   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3087       TC.GetDefaultStackProtectorLevel(KernelOrKext);
3088 
3089   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3090                                options::OPT_fstack_protector_all,
3091                                options::OPT_fstack_protector_strong,
3092                                options::OPT_fstack_protector)) {
3093     if (A->getOption().matches(options::OPT_fstack_protector))
3094       StackProtectorLevel =
3095           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3096     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3097       StackProtectorLevel = LangOptions::SSPStrong;
3098     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3099       StackProtectorLevel = LangOptions::SSPReq;
3100   } else {
3101     StackProtectorLevel = DefaultStackProtectorLevel;
3102   }
3103 
3104   if (StackProtectorLevel) {
3105     CmdArgs.push_back("-stack-protector");
3106     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3107   }
3108 
3109   // --param ssp-buffer-size=
3110   for (const Arg *A : Args.filtered(options::OPT__param)) {
3111     StringRef Str(A->getValue());
3112     if (Str.startswith("ssp-buffer-size=")) {
3113       if (StackProtectorLevel) {
3114         CmdArgs.push_back("-stack-protector-buffer-size");
3115         // FIXME: Verify the argument is a valid integer.
3116         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3117       }
3118       A->claim();
3119     }
3120   }
3121 
3122   const std::string &TripleStr = EffectiveTriple.getTriple();
3123   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3124     StringRef Value = A->getValue();
3125     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3126       D.Diag(diag::err_drv_unsupported_opt_for_target)
3127           << A->getAsString(Args) << TripleStr;
3128     if (EffectiveTriple.isX86() && Value != "tls" && Value != "global") {
3129       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3130           << A->getOption().getName() << Value << "tls global";
3131       return;
3132     }
3133     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3134       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3135           << A->getOption().getName() << Value << "sysreg global";
3136       return;
3137     }
3138     A->render(Args, CmdArgs);
3139   }
3140 
3141   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3142     StringRef Value = A->getValue();
3143     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3144       D.Diag(diag::err_drv_unsupported_opt_for_target)
3145           << A->getAsString(Args) << TripleStr;
3146     int Offset;
3147     if (Value.getAsInteger(10, Offset)) {
3148       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3149       return;
3150     }
3151     A->render(Args, CmdArgs);
3152   }
3153 
3154   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3155     StringRef Value = A->getValue();
3156     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3157       D.Diag(diag::err_drv_unsupported_opt_for_target)
3158           << A->getAsString(Args) << TripleStr;
3159     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3160       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3161           << A->getOption().getName() << Value << "fs gs";
3162       return;
3163     }
3164     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3165       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3166       return;
3167     }
3168     A->render(Args, CmdArgs);
3169   }
3170 }
3171 
RenderSCPOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3172 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3173                              ArgStringList &CmdArgs) {
3174   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3175 
3176   if (!EffectiveTriple.isOSLinux())
3177     return;
3178 
3179   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3180       !EffectiveTriple.isPPC64())
3181     return;
3182 
3183   if (Args.hasFlag(options::OPT_fstack_clash_protection,
3184                    options::OPT_fno_stack_clash_protection, false))
3185     CmdArgs.push_back("-fstack-clash-protection");
3186 }
3187 
RenderTrivialAutoVarInitOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3188 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3189                                             const ToolChain &TC,
3190                                             const ArgList &Args,
3191                                             ArgStringList &CmdArgs) {
3192   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3193   StringRef TrivialAutoVarInit = "";
3194 
3195   for (const Arg *A : Args) {
3196     switch (A->getOption().getID()) {
3197     default:
3198       continue;
3199     case options::OPT_ftrivial_auto_var_init: {
3200       A->claim();
3201       StringRef Val = A->getValue();
3202       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3203         TrivialAutoVarInit = Val;
3204       else
3205         D.Diag(diag::err_drv_unsupported_option_argument)
3206             << A->getOption().getName() << Val;
3207       break;
3208     }
3209     }
3210   }
3211 
3212   if (TrivialAutoVarInit.empty())
3213     switch (DefaultTrivialAutoVarInit) {
3214     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3215       break;
3216     case LangOptions::TrivialAutoVarInitKind::Pattern:
3217       TrivialAutoVarInit = "pattern";
3218       break;
3219     case LangOptions::TrivialAutoVarInitKind::Zero:
3220       TrivialAutoVarInit = "zero";
3221       break;
3222     }
3223 
3224   if (!TrivialAutoVarInit.empty()) {
3225     if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
3226       D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
3227     CmdArgs.push_back(
3228         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3229   }
3230 
3231   if (Arg *A =
3232           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3233     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3234         StringRef(
3235             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3236             "uninitialized")
3237       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3238     A->claim();
3239     StringRef Val = A->getValue();
3240     if (std::stoi(Val.str()) <= 0)
3241       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3242     CmdArgs.push_back(
3243         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3244   }
3245 }
3246 
RenderOpenCLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3247 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3248                                 types::ID InputType) {
3249   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3250   // for denormal flushing handling based on the target.
3251   const unsigned ForwardedArguments[] = {
3252       options::OPT_cl_opt_disable,
3253       options::OPT_cl_strict_aliasing,
3254       options::OPT_cl_single_precision_constant,
3255       options::OPT_cl_finite_math_only,
3256       options::OPT_cl_kernel_arg_info,
3257       options::OPT_cl_unsafe_math_optimizations,
3258       options::OPT_cl_fast_relaxed_math,
3259       options::OPT_cl_mad_enable,
3260       options::OPT_cl_no_signed_zeros,
3261       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3262       options::OPT_cl_uniform_work_group_size
3263   };
3264 
3265   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3266     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3267     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3268   }
3269 
3270   for (const auto &Arg : ForwardedArguments)
3271     if (const auto *A = Args.getLastArg(Arg))
3272       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3273 
3274   // Only add the default headers if we are compiling OpenCL sources.
3275   if ((types::isOpenCL(InputType) || Args.hasArg(options::OPT_cl_std_EQ)) &&
3276       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3277     CmdArgs.push_back("-finclude-default-header");
3278     CmdArgs.push_back("-fdeclare-opencl-builtins");
3279   }
3280 }
3281 
RenderARCMigrateToolOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)3282 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3283                                         ArgStringList &CmdArgs) {
3284   bool ARCMTEnabled = false;
3285   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3286     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3287                                        options::OPT_ccc_arcmt_modify,
3288                                        options::OPT_ccc_arcmt_migrate)) {
3289       ARCMTEnabled = true;
3290       switch (A->getOption().getID()) {
3291       default: llvm_unreachable("missed a case");
3292       case options::OPT_ccc_arcmt_check:
3293         CmdArgs.push_back("-arcmt-action=check");
3294         break;
3295       case options::OPT_ccc_arcmt_modify:
3296         CmdArgs.push_back("-arcmt-action=modify");
3297         break;
3298       case options::OPT_ccc_arcmt_migrate:
3299         CmdArgs.push_back("-arcmt-action=migrate");
3300         CmdArgs.push_back("-mt-migrate-directory");
3301         CmdArgs.push_back(A->getValue());
3302 
3303         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3304         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3305         break;
3306       }
3307     }
3308   } else {
3309     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3310     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3311     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3312   }
3313 
3314   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3315     if (ARCMTEnabled)
3316       D.Diag(diag::err_drv_argument_not_allowed_with)
3317           << A->getAsString(Args) << "-ccc-arcmt-migrate";
3318 
3319     CmdArgs.push_back("-mt-migrate-directory");
3320     CmdArgs.push_back(A->getValue());
3321 
3322     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3323                      options::OPT_objcmt_migrate_subscripting,
3324                      options::OPT_objcmt_migrate_property)) {
3325       // None specified, means enable them all.
3326       CmdArgs.push_back("-objcmt-migrate-literals");
3327       CmdArgs.push_back("-objcmt-migrate-subscripting");
3328       CmdArgs.push_back("-objcmt-migrate-property");
3329     } else {
3330       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3331       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3332       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3333     }
3334   } else {
3335     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3336     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3337     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3338     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3339     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3340     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3341     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3342     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3343     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3344     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3345     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3346     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3347     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3348     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3349     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3350     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3351   }
3352 }
3353 
RenderBuiltinOptions(const ToolChain & TC,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs)3354 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3355                                  const ArgList &Args, ArgStringList &CmdArgs) {
3356   // -fbuiltin is default unless -mkernel is used.
3357   bool UseBuiltins =
3358       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3359                    !Args.hasArg(options::OPT_mkernel));
3360   if (!UseBuiltins)
3361     CmdArgs.push_back("-fno-builtin");
3362 
3363   // -ffreestanding implies -fno-builtin.
3364   if (Args.hasArg(options::OPT_ffreestanding))
3365     UseBuiltins = false;
3366 
3367   // Process the -fno-builtin-* options.
3368   for (const auto &Arg : Args) {
3369     const Option &O = Arg->getOption();
3370     if (!O.matches(options::OPT_fno_builtin_))
3371       continue;
3372 
3373     Arg->claim();
3374 
3375     // If -fno-builtin is specified, then there's no need to pass the option to
3376     // the frontend.
3377     if (!UseBuiltins)
3378       continue;
3379 
3380     StringRef FuncName = Arg->getValue();
3381     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3382   }
3383 
3384   // le32-specific flags:
3385   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3386   //                     by default.
3387   if (TC.getArch() == llvm::Triple::le32)
3388     CmdArgs.push_back("-fno-math-builtin");
3389 }
3390 
getDefaultModuleCachePath(SmallVectorImpl<char> & Result)3391 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3392   if (llvm::sys::path::cache_directory(Result)) {
3393     llvm::sys::path::append(Result, "clang");
3394     llvm::sys::path::append(Result, "ModuleCache");
3395     return true;
3396   }
3397   return false;
3398 }
3399 
RenderModulesOptions(Compilation & C,const Driver & D,const ArgList & Args,const InputInfo & Input,const InputInfo & Output,ArgStringList & CmdArgs,bool & HaveModules)3400 static void RenderModulesOptions(Compilation &C, const Driver &D,
3401                                  const ArgList &Args, const InputInfo &Input,
3402                                  const InputInfo &Output,
3403                                  ArgStringList &CmdArgs, bool &HaveModules) {
3404   // -fmodules enables the use of precompiled modules (off by default).
3405   // Users can pass -fno-cxx-modules to turn off modules support for
3406   // C++/Objective-C++ programs.
3407   bool HaveClangModules = false;
3408   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3409     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3410                                      options::OPT_fno_cxx_modules, true);
3411     if (AllowedInCXX || !types::isCXX(Input.getType())) {
3412       CmdArgs.push_back("-fmodules");
3413       HaveClangModules = true;
3414     }
3415   }
3416 
3417   HaveModules |= HaveClangModules;
3418   if (Args.hasArg(options::OPT_fmodules_ts)) {
3419     CmdArgs.push_back("-fmodules-ts");
3420     HaveModules = true;
3421   }
3422 
3423   // -fmodule-maps enables implicit reading of module map files. By default,
3424   // this is enabled if we are using Clang's flavor of precompiled modules.
3425   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3426                    options::OPT_fno_implicit_module_maps, HaveClangModules))
3427     CmdArgs.push_back("-fimplicit-module-maps");
3428 
3429   // -fmodules-decluse checks that modules used are declared so (off by default)
3430   if (Args.hasFlag(options::OPT_fmodules_decluse,
3431                    options::OPT_fno_modules_decluse, false))
3432     CmdArgs.push_back("-fmodules-decluse");
3433 
3434   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3435   // all #included headers are part of modules.
3436   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3437                    options::OPT_fno_modules_strict_decluse, false))
3438     CmdArgs.push_back("-fmodules-strict-decluse");
3439 
3440   // -fno-implicit-modules turns off implicitly compiling modules on demand.
3441   bool ImplicitModules = false;
3442   if (!Args.hasFlag(options::OPT_fimplicit_modules,
3443                     options::OPT_fno_implicit_modules, HaveClangModules)) {
3444     if (HaveModules)
3445       CmdArgs.push_back("-fno-implicit-modules");
3446   } else if (HaveModules) {
3447     ImplicitModules = true;
3448     // -fmodule-cache-path specifies where our implicitly-built module files
3449     // should be written.
3450     SmallString<128> Path;
3451     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3452       Path = A->getValue();
3453 
3454     bool HasPath = true;
3455     if (C.isForDiagnostics()) {
3456       // When generating crash reports, we want to emit the modules along with
3457       // the reproduction sources, so we ignore any provided module path.
3458       Path = Output.getFilename();
3459       llvm::sys::path::replace_extension(Path, ".cache");
3460       llvm::sys::path::append(Path, "modules");
3461     } else if (Path.empty()) {
3462       // No module path was provided: use the default.
3463       HasPath = Driver::getDefaultModuleCachePath(Path);
3464     }
3465 
3466     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3467     // That being said, that failure is unlikely and not caching is harmless.
3468     if (HasPath) {
3469       const char Arg[] = "-fmodules-cache-path=";
3470       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3471       CmdArgs.push_back(Args.MakeArgString(Path));
3472     }
3473   }
3474 
3475   if (HaveModules) {
3476     // -fprebuilt-module-path specifies where to load the prebuilt module files.
3477     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3478       CmdArgs.push_back(Args.MakeArgString(
3479           std::string("-fprebuilt-module-path=") + A->getValue()));
3480       A->claim();
3481     }
3482     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3483                      options::OPT_fno_prebuilt_implicit_modules, false))
3484       CmdArgs.push_back("-fprebuilt-implicit-modules");
3485     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3486                      options::OPT_fno_modules_validate_input_files_content,
3487                      false))
3488       CmdArgs.push_back("-fvalidate-ast-input-files-content");
3489   }
3490 
3491   // -fmodule-name specifies the module that is currently being built (or
3492   // used for header checking by -fmodule-maps).
3493   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3494 
3495   // -fmodule-map-file can be used to specify files containing module
3496   // definitions.
3497   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3498 
3499   // -fbuiltin-module-map can be used to load the clang
3500   // builtin headers modulemap file.
3501   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3502     SmallString<128> BuiltinModuleMap(D.ResourceDir);
3503     llvm::sys::path::append(BuiltinModuleMap, "include");
3504     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3505     if (llvm::sys::fs::exists(BuiltinModuleMap))
3506       CmdArgs.push_back(
3507           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3508   }
3509 
3510   // The -fmodule-file=<name>=<file> form specifies the mapping of module
3511   // names to precompiled module files (the module is loaded only if used).
3512   // The -fmodule-file=<file> form can be used to unconditionally load
3513   // precompiled module files (whether used or not).
3514   if (HaveModules)
3515     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3516   else
3517     Args.ClaimAllArgs(options::OPT_fmodule_file);
3518 
3519   // When building modules and generating crashdumps, we need to dump a module
3520   // dependency VFS alongside the output.
3521   if (HaveClangModules && C.isForDiagnostics()) {
3522     SmallString<128> VFSDir(Output.getFilename());
3523     llvm::sys::path::replace_extension(VFSDir, ".cache");
3524     // Add the cache directory as a temp so the crash diagnostics pick it up.
3525     C.addTempFile(Args.MakeArgString(VFSDir));
3526 
3527     llvm::sys::path::append(VFSDir, "vfs");
3528     CmdArgs.push_back("-module-dependency-dir");
3529     CmdArgs.push_back(Args.MakeArgString(VFSDir));
3530   }
3531 
3532   if (HaveClangModules)
3533     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3534 
3535   // Pass through all -fmodules-ignore-macro arguments.
3536   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3537   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3538   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3539 
3540   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3541 
3542   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3543     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3544       D.Diag(diag::err_drv_argument_not_allowed_with)
3545           << A->getAsString(Args) << "-fbuild-session-timestamp";
3546 
3547     llvm::sys::fs::file_status Status;
3548     if (llvm::sys::fs::status(A->getValue(), Status))
3549       D.Diag(diag::err_drv_no_such_file) << A->getValue();
3550     CmdArgs.push_back(
3551         Args.MakeArgString("-fbuild-session-timestamp=" +
3552                            Twine((uint64_t)Status.getLastModificationTime()
3553                                      .time_since_epoch()
3554                                      .count())));
3555   }
3556 
3557   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3558     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3559                          options::OPT_fbuild_session_file))
3560       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3561 
3562     Args.AddLastArg(CmdArgs,
3563                     options::OPT_fmodules_validate_once_per_build_session);
3564   }
3565 
3566   if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3567                    options::OPT_fno_modules_validate_system_headers,
3568                    ImplicitModules))
3569     CmdArgs.push_back("-fmodules-validate-system-headers");
3570 
3571   Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3572 }
3573 
RenderCharacterOptions(const ArgList & Args,const llvm::Triple & T,ArgStringList & CmdArgs)3574 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3575                                    ArgStringList &CmdArgs) {
3576   // -fsigned-char is default.
3577   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3578                                      options::OPT_fno_signed_char,
3579                                      options::OPT_funsigned_char,
3580                                      options::OPT_fno_unsigned_char)) {
3581     if (A->getOption().matches(options::OPT_funsigned_char) ||
3582         A->getOption().matches(options::OPT_fno_signed_char)) {
3583       CmdArgs.push_back("-fno-signed-char");
3584     }
3585   } else if (!isSignedCharDefault(T)) {
3586     CmdArgs.push_back("-fno-signed-char");
3587   }
3588 
3589   // The default depends on the language standard.
3590   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3591 
3592   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3593                                      options::OPT_fno_short_wchar)) {
3594     if (A->getOption().matches(options::OPT_fshort_wchar)) {
3595       CmdArgs.push_back("-fwchar-type=short");
3596       CmdArgs.push_back("-fno-signed-wchar");
3597     } else {
3598       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3599       CmdArgs.push_back("-fwchar-type=int");
3600       if (T.isOSzOS() ||
3601           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3602         CmdArgs.push_back("-fno-signed-wchar");
3603       else
3604         CmdArgs.push_back("-fsigned-wchar");
3605     }
3606   }
3607 }
3608 
RenderObjCOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,ObjCRuntime & Runtime,bool InferCovariantReturns,const InputInfo & Input,ArgStringList & CmdArgs)3609 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3610                               const llvm::Triple &T, const ArgList &Args,
3611                               ObjCRuntime &Runtime, bool InferCovariantReturns,
3612                               const InputInfo &Input, ArgStringList &CmdArgs) {
3613   const llvm::Triple::ArchType Arch = TC.getArch();
3614 
3615   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3616   // is the default. Except for deployment target of 10.5, next runtime is
3617   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3618   if (Runtime.isNonFragile()) {
3619     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3620                       options::OPT_fno_objc_legacy_dispatch,
3621                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3622       if (TC.UseObjCMixedDispatch())
3623         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3624       else
3625         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3626     }
3627   }
3628 
3629   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3630   // to do Array/Dictionary subscripting by default.
3631   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3632       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3633     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3634 
3635   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3636   // NOTE: This logic is duplicated in ToolChains.cpp.
3637   if (isObjCAutoRefCount(Args)) {
3638     TC.CheckObjCARC();
3639 
3640     CmdArgs.push_back("-fobjc-arc");
3641 
3642     // FIXME: It seems like this entire block, and several around it should be
3643     // wrapped in isObjC, but for now we just use it here as this is where it
3644     // was being used previously.
3645     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3646       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3647         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3648       else
3649         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3650     }
3651 
3652     // Allow the user to enable full exceptions code emission.
3653     // We default off for Objective-C, on for Objective-C++.
3654     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3655                      options::OPT_fno_objc_arc_exceptions,
3656                      /*Default=*/types::isCXX(Input.getType())))
3657       CmdArgs.push_back("-fobjc-arc-exceptions");
3658   }
3659 
3660   // Silence warning for full exception code emission options when explicitly
3661   // set to use no ARC.
3662   if (Args.hasArg(options::OPT_fno_objc_arc)) {
3663     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3664     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3665   }
3666 
3667   // Allow the user to control whether messages can be converted to runtime
3668   // functions.
3669   if (types::isObjC(Input.getType())) {
3670     auto *Arg = Args.getLastArg(
3671         options::OPT_fobjc_convert_messages_to_runtime_calls,
3672         options::OPT_fno_objc_convert_messages_to_runtime_calls);
3673     if (Arg &&
3674         Arg->getOption().matches(
3675             options::OPT_fno_objc_convert_messages_to_runtime_calls))
3676       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3677   }
3678 
3679   // -fobjc-infer-related-result-type is the default, except in the Objective-C
3680   // rewriter.
3681   if (InferCovariantReturns)
3682     CmdArgs.push_back("-fno-objc-infer-related-result-type");
3683 
3684   // Pass down -fobjc-weak or -fno-objc-weak if present.
3685   if (types::isObjC(Input.getType())) {
3686     auto WeakArg =
3687         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3688     if (!WeakArg) {
3689       // nothing to do
3690     } else if (!Runtime.allowsWeak()) {
3691       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3692         D.Diag(diag::err_objc_weak_unsupported);
3693     } else {
3694       WeakArg->render(Args, CmdArgs);
3695     }
3696   }
3697 
3698   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
3699     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
3700 }
3701 
RenderDiagnosticsOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)3702 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3703                                      ArgStringList &CmdArgs) {
3704   bool CaretDefault = true;
3705   bool ColumnDefault = true;
3706 
3707   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3708                                      options::OPT__SLASH_diagnostics_column,
3709                                      options::OPT__SLASH_diagnostics_caret)) {
3710     switch (A->getOption().getID()) {
3711     case options::OPT__SLASH_diagnostics_caret:
3712       CaretDefault = true;
3713       ColumnDefault = true;
3714       break;
3715     case options::OPT__SLASH_diagnostics_column:
3716       CaretDefault = false;
3717       ColumnDefault = true;
3718       break;
3719     case options::OPT__SLASH_diagnostics_classic:
3720       CaretDefault = false;
3721       ColumnDefault = false;
3722       break;
3723     }
3724   }
3725 
3726   // -fcaret-diagnostics is default.
3727   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3728                     options::OPT_fno_caret_diagnostics, CaretDefault))
3729     CmdArgs.push_back("-fno-caret-diagnostics");
3730 
3731   // -fdiagnostics-fixit-info is default, only pass non-default.
3732   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3733                     options::OPT_fno_diagnostics_fixit_info))
3734     CmdArgs.push_back("-fno-diagnostics-fixit-info");
3735 
3736   // Enable -fdiagnostics-show-option by default.
3737   if (!Args.hasFlag(options::OPT_fdiagnostics_show_option,
3738                     options::OPT_fno_diagnostics_show_option, true))
3739     CmdArgs.push_back("-fno-diagnostics-show-option");
3740 
3741   if (const Arg *A =
3742           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3743     CmdArgs.push_back("-fdiagnostics-show-category");
3744     CmdArgs.push_back(A->getValue());
3745   }
3746 
3747   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3748                    options::OPT_fno_diagnostics_show_hotness, false))
3749     CmdArgs.push_back("-fdiagnostics-show-hotness");
3750 
3751   if (const Arg *A =
3752           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3753     std::string Opt =
3754         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3755     CmdArgs.push_back(Args.MakeArgString(Opt));
3756   }
3757 
3758   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3759     CmdArgs.push_back("-fdiagnostics-format");
3760     CmdArgs.push_back(A->getValue());
3761   }
3762 
3763   if (const Arg *A = Args.getLastArg(
3764           options::OPT_fdiagnostics_show_note_include_stack,
3765           options::OPT_fno_diagnostics_show_note_include_stack)) {
3766     const Option &O = A->getOption();
3767     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3768       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3769     else
3770       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3771   }
3772 
3773   // Color diagnostics are parsed by the driver directly from argv and later
3774   // re-parsed to construct this job; claim any possible color diagnostic here
3775   // to avoid warn_drv_unused_argument and diagnose bad
3776   // OPT_fdiagnostics_color_EQ values.
3777   for (const Arg *A : Args) {
3778     const Option &O = A->getOption();
3779     if (!O.matches(options::OPT_fcolor_diagnostics) &&
3780         !O.matches(options::OPT_fdiagnostics_color) &&
3781         !O.matches(options::OPT_fno_color_diagnostics) &&
3782         !O.matches(options::OPT_fno_diagnostics_color) &&
3783         !O.matches(options::OPT_fdiagnostics_color_EQ))
3784       continue;
3785 
3786     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3787       StringRef Value(A->getValue());
3788       if (Value != "always" && Value != "never" && Value != "auto")
3789         D.Diag(diag::err_drv_clang_unsupported)
3790             << ("-fdiagnostics-color=" + Value).str();
3791     }
3792     A->claim();
3793   }
3794 
3795   if (D.getDiags().getDiagnosticOptions().ShowColors)
3796     CmdArgs.push_back("-fcolor-diagnostics");
3797 
3798   if (Args.hasArg(options::OPT_fansi_escape_codes))
3799     CmdArgs.push_back("-fansi-escape-codes");
3800 
3801   if (!Args.hasFlag(options::OPT_fshow_source_location,
3802                     options::OPT_fno_show_source_location))
3803     CmdArgs.push_back("-fno-show-source-location");
3804 
3805   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3806     CmdArgs.push_back("-fdiagnostics-absolute-paths");
3807 
3808   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3809                     ColumnDefault))
3810     CmdArgs.push_back("-fno-show-column");
3811 
3812   if (!Args.hasFlag(options::OPT_fspell_checking,
3813                     options::OPT_fno_spell_checking))
3814     CmdArgs.push_back("-fno-spell-checking");
3815 }
3816 
3817 enum class DwarfFissionKind { None, Split, Single };
3818 
getDebugFissionKind(const Driver & D,const ArgList & Args,Arg * & Arg)3819 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3820                                             const ArgList &Args, Arg *&Arg) {
3821   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
3822                         options::OPT_gno_split_dwarf);
3823   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
3824     return DwarfFissionKind::None;
3825 
3826   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3827     return DwarfFissionKind::Split;
3828 
3829   StringRef Value = Arg->getValue();
3830   if (Value == "split")
3831     return DwarfFissionKind::Split;
3832   if (Value == "single")
3833     return DwarfFissionKind::Single;
3834 
3835   D.Diag(diag::err_drv_unsupported_option_argument)
3836       << Arg->getOption().getName() << Arg->getValue();
3837   return DwarfFissionKind::None;
3838 }
3839 
renderDwarfFormat(const Driver & D,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs,unsigned DwarfVersion)3840 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
3841                               const ArgList &Args, ArgStringList &CmdArgs,
3842                               unsigned DwarfVersion) {
3843   auto *DwarfFormatArg =
3844       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
3845   if (!DwarfFormatArg)
3846     return;
3847 
3848   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
3849     if (DwarfVersion < 3)
3850       D.Diag(diag::err_drv_argument_only_allowed_with)
3851           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
3852     else if (!T.isArch64Bit())
3853       D.Diag(diag::err_drv_argument_only_allowed_with)
3854           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
3855     else if (!T.isOSBinFormatELF())
3856       D.Diag(diag::err_drv_argument_only_allowed_with)
3857           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
3858   }
3859 
3860   DwarfFormatArg->render(Args, CmdArgs);
3861 }
3862 
renderDebugOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,bool EmitCodeView,bool IRInput,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind & DebugInfoKind,DwarfFissionKind & DwarfFission)3863 static void renderDebugOptions(const ToolChain &TC, const Driver &D,
3864                                const llvm::Triple &T, const ArgList &Args,
3865                                bool EmitCodeView, bool IRInput,
3866                                ArgStringList &CmdArgs,
3867                                codegenoptions::DebugInfoKind &DebugInfoKind,
3868                                DwarfFissionKind &DwarfFission) {
3869   // These two forms of profiling info can't be used together.
3870   if (const Arg *A1 = Args.getLastArg(options::OPT_fpseudo_probe_for_profiling))
3871     if (const Arg *A2 = Args.getLastArg(options::OPT_fdebug_info_for_profiling))
3872       D.Diag(diag::err_drv_argument_not_allowed_with)
3873           << A1->getAsString(Args) << A2->getAsString(Args);
3874 
3875   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3876                    options::OPT_fno_debug_info_for_profiling, false) &&
3877       checkDebugInfoOption(
3878           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3879     CmdArgs.push_back("-fdebug-info-for-profiling");
3880 
3881   // The 'g' groups options involve a somewhat intricate sequence of decisions
3882   // about what to pass from the driver to the frontend, but by the time they
3883   // reach cc1 they've been factored into three well-defined orthogonal choices:
3884   //  * what level of debug info to generate
3885   //  * what dwarf version to write
3886   //  * what debugger tuning to use
3887   // This avoids having to monkey around further in cc1 other than to disable
3888   // codeview if not running in a Windows environment. Perhaps even that
3889   // decision should be made in the driver as well though.
3890   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3891 
3892   bool SplitDWARFInlining =
3893       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3894                    options::OPT_fno_split_dwarf_inlining, false);
3895 
3896   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
3897   // object file generation and no IR generation, -gN should not be needed. So
3898   // allow -gsplit-dwarf with either -gN or IR input.
3899   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
3900     Arg *SplitDWARFArg;
3901     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3902     if (DwarfFission != DwarfFissionKind::None &&
3903         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3904       DwarfFission = DwarfFissionKind::None;
3905       SplitDWARFInlining = false;
3906     }
3907   }
3908   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3909     DebugInfoKind = codegenoptions::LimitedDebugInfo;
3910 
3911     // If the last option explicitly specified a debug-info level, use it.
3912     if (checkDebugInfoOption(A, Args, D, TC) &&
3913         A->getOption().matches(options::OPT_gN_Group)) {
3914       DebugInfoKind = DebugLevelToInfoKind(*A);
3915       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3916       // complicated if you've disabled inline info in the skeleton CUs
3917       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3918       // line-tables-only, so let those compose naturally in that case.
3919       if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3920           DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3921           (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3922            SplitDWARFInlining))
3923         DwarfFission = DwarfFissionKind::None;
3924     }
3925   }
3926 
3927   // If a debugger tuning argument appeared, remember it.
3928   if (const Arg *A =
3929           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3930     if (checkDebugInfoOption(A, Args, D, TC)) {
3931       if (A->getOption().matches(options::OPT_glldb))
3932         DebuggerTuning = llvm::DebuggerKind::LLDB;
3933       else if (A->getOption().matches(options::OPT_gsce))
3934         DebuggerTuning = llvm::DebuggerKind::SCE;
3935       else if (A->getOption().matches(options::OPT_gdbx))
3936         DebuggerTuning = llvm::DebuggerKind::DBX;
3937       else
3938         DebuggerTuning = llvm::DebuggerKind::GDB;
3939     }
3940   }
3941 
3942   // If a -gdwarf argument appeared, remember it.
3943   const Arg *GDwarfN = getDwarfNArg(Args);
3944   bool EmitDwarf = false;
3945   if (GDwarfN) {
3946     if (checkDebugInfoOption(GDwarfN, Args, D, TC))
3947       EmitDwarf = true;
3948     else
3949       GDwarfN = nullptr;
3950   }
3951 
3952   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3953     if (checkDebugInfoOption(A, Args, D, TC))
3954       EmitCodeView = true;
3955   }
3956 
3957   // If the user asked for debug info but did not explicitly specify -gcodeview
3958   // or -gdwarf, ask the toolchain for the default format.
3959   if (!EmitCodeView && !EmitDwarf &&
3960       DebugInfoKind != codegenoptions::NoDebugInfo) {
3961     switch (TC.getDefaultDebugFormat()) {
3962     case codegenoptions::DIF_CodeView:
3963       EmitCodeView = true;
3964       break;
3965     case codegenoptions::DIF_DWARF:
3966       EmitDwarf = true;
3967       break;
3968     }
3969   }
3970 
3971   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
3972   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
3973                                       // be lower than what the user wanted.
3974   unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args);
3975   if (EmitDwarf) {
3976     // Start with the platform default DWARF version
3977     RequestedDWARFVersion = TC.GetDefaultDwarfVersion();
3978     assert(RequestedDWARFVersion &&
3979            "toolchain default DWARF version must be nonzero");
3980 
3981     // If the user specified a default DWARF version, that takes precedence
3982     // over the platform default.
3983     if (DefaultDWARFVersion)
3984       RequestedDWARFVersion = DefaultDWARFVersion;
3985 
3986     // Override with a user-specified DWARF version
3987     if (GDwarfN)
3988       if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling()))
3989         RequestedDWARFVersion = ExplicitVersion;
3990     // Clamp effective DWARF version to the max supported by the toolchain.
3991     EffectiveDWARFVersion =
3992         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
3993   }
3994 
3995   // -gline-directives-only supported only for the DWARF debug info.
3996   if (RequestedDWARFVersion == 0 &&
3997       DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3998     DebugInfoKind = codegenoptions::NoDebugInfo;
3999 
4000   // strict DWARF is set to false by default. But for DBX, we need it to be set
4001   // as true by default.
4002   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4003     (void)checkDebugInfoOption(A, Args, D, TC);
4004   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4005                    DebuggerTuning == llvm::DebuggerKind::DBX))
4006     CmdArgs.push_back("-gstrict-dwarf");
4007 
4008   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4009   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4010 
4011   // Column info is included by default for everything except SCE and
4012   // CodeView. Clang doesn't track end columns, just starting columns, which,
4013   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4014   // Microsoft debuggers don't handle missing end columns well, and the AIX
4015   // debugger DBX also doesn't handle the columns well, so it's better not to
4016   // include any column info.
4017   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4018     (void)checkDebugInfoOption(A, Args, D, TC);
4019   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4020                     !EmitCodeView &&
4021                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4022                          DebuggerTuning != llvm::DebuggerKind::DBX)))
4023     CmdArgs.push_back("-gno-column-info");
4024 
4025   // FIXME: Move backend command line options to the module.
4026   // If -gline-tables-only or -gline-directives-only is the last option it wins.
4027   if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
4028     if (checkDebugInfoOption(A, Args, D, TC)) {
4029       if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
4030           DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
4031         DebugInfoKind = codegenoptions::LimitedDebugInfo;
4032         CmdArgs.push_back("-dwarf-ext-refs");
4033         CmdArgs.push_back("-fmodule-format=obj");
4034       }
4035     }
4036 
4037   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4038     CmdArgs.push_back("-fsplit-dwarf-inlining");
4039 
4040   // After we've dealt with all combinations of things that could
4041   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4042   // figure out if we need to "upgrade" it to standalone debug info.
4043   // We parse these two '-f' options whether or not they will be used,
4044   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4045   bool NeedFullDebug = Args.hasFlag(
4046       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4047       DebuggerTuning == llvm::DebuggerKind::LLDB ||
4048           TC.GetDefaultStandaloneDebug());
4049   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4050     (void)checkDebugInfoOption(A, Args, D, TC);
4051 
4052   if (DebugInfoKind == codegenoptions::LimitedDebugInfo) {
4053     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4054                      options::OPT_feliminate_unused_debug_types, false))
4055       DebugInfoKind = codegenoptions::UnusedTypeInfo;
4056     else if (NeedFullDebug)
4057       DebugInfoKind = codegenoptions::FullDebugInfo;
4058   }
4059 
4060   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4061                    false)) {
4062     // Source embedding is a vendor extension to DWARF v5. By now we have
4063     // checked if a DWARF version was stated explicitly, and have otherwise
4064     // fallen back to the target default, so if this is still not at least 5
4065     // we emit an error.
4066     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4067     if (RequestedDWARFVersion < 5)
4068       D.Diag(diag::err_drv_argument_only_allowed_with)
4069           << A->getAsString(Args) << "-gdwarf-5";
4070     else if (EffectiveDWARFVersion < 5)
4071       // The toolchain has reduced allowed dwarf version, so we can't enable
4072       // -gembed-source.
4073       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4074           << A->getAsString(Args) << TC.getTripleString() << 5
4075           << EffectiveDWARFVersion;
4076     else if (checkDebugInfoOption(A, Args, D, TC))
4077       CmdArgs.push_back("-gembed-source");
4078   }
4079 
4080   if (EmitCodeView) {
4081     CmdArgs.push_back("-gcodeview");
4082 
4083     // Emit codeview type hashes if requested.
4084     if (Args.hasFlag(options::OPT_gcodeview_ghash,
4085                      options::OPT_gno_codeview_ghash, false)) {
4086       CmdArgs.push_back("-gcodeview-ghash");
4087     }
4088   }
4089 
4090   // Omit inline line tables if requested.
4091   if (Args.hasFlag(options::OPT_gno_inline_line_tables,
4092                    options::OPT_ginline_line_tables, false)) {
4093     CmdArgs.push_back("-gno-inline-line-tables");
4094   }
4095 
4096   // When emitting remarks, we need at least debug lines in the output.
4097   if (willEmitRemarks(Args) &&
4098       DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
4099     DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4100 
4101   // Adjust the debug info kind for the given toolchain.
4102   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4103 
4104   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4105                           DebuggerTuning);
4106 
4107   // -fdebug-macro turns on macro debug info generation.
4108   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4109                    false))
4110     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4111                              D, TC))
4112       CmdArgs.push_back("-debug-info-macro");
4113 
4114   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4115   const auto *PubnamesArg =
4116       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4117                       options::OPT_gpubnames, options::OPT_gno_pubnames);
4118   if (DwarfFission != DwarfFissionKind::None ||
4119       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4120     if (!PubnamesArg ||
4121         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4122          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4123       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4124                                            options::OPT_gpubnames)
4125                             ? "-gpubnames"
4126                             : "-ggnu-pubnames");
4127 
4128   if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
4129                    options::OPT_fno_debug_ranges_base_address, false)) {
4130     CmdArgs.push_back("-fdebug-ranges-base-address");
4131   }
4132 
4133   // -gdwarf-aranges turns on the emission of the aranges section in the
4134   // backend.
4135   // Always enabled for SCE tuning.
4136   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4137   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4138     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4139   if (NeedAranges) {
4140     CmdArgs.push_back("-mllvm");
4141     CmdArgs.push_back("-generate-arange-section");
4142   }
4143 
4144   if (Args.hasFlag(options::OPT_fforce_dwarf_frame,
4145                    options::OPT_fno_force_dwarf_frame, false))
4146     CmdArgs.push_back("-fforce-dwarf-frame");
4147 
4148   if (Args.hasFlag(options::OPT_fdebug_types_section,
4149                    options::OPT_fno_debug_types_section, false)) {
4150     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4151       D.Diag(diag::err_drv_unsupported_opt_for_target)
4152           << Args.getLastArg(options::OPT_fdebug_types_section)
4153                  ->getAsString(Args)
4154           << T.getTriple();
4155     } else if (checkDebugInfoOption(
4156                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4157                    TC)) {
4158       CmdArgs.push_back("-mllvm");
4159       CmdArgs.push_back("-generate-type-units");
4160     }
4161   }
4162 
4163   // Decide how to render forward declarations of template instantiations.
4164   // SCE wants full descriptions, others just get them in the name.
4165   if (DebuggerTuning == llvm::DebuggerKind::SCE)
4166     CmdArgs.push_back("-debug-forward-template-params");
4167 
4168   // Do we need to explicitly import anonymous namespaces into the parent
4169   // scope?
4170   if (DebuggerTuning == llvm::DebuggerKind::SCE)
4171     CmdArgs.push_back("-dwarf-explicit-import");
4172 
4173   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4174   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4175 }
4176 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4177 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4178                          const InputInfo &Output, const InputInfoList &Inputs,
4179                          const ArgList &Args, const char *LinkingOutput) const {
4180   const auto &TC = getToolChain();
4181   const llvm::Triple &RawTriple = TC.getTriple();
4182   const llvm::Triple &Triple = TC.getEffectiveTriple();
4183   const std::string &TripleStr = Triple.getTriple();
4184 
4185   bool KernelOrKext =
4186       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4187   const Driver &D = TC.getDriver();
4188   ArgStringList CmdArgs;
4189 
4190   // Check number of inputs for sanity. We need at least one input.
4191   assert(Inputs.size() >= 1 && "Must have at least one input.");
4192   // CUDA/HIP compilation may have multiple inputs (source file + results of
4193   // device-side compilations). OpenMP device jobs also take the host IR as a
4194   // second input. Module precompilation accepts a list of header files to
4195   // include as part of the module. All other jobs are expected to have exactly
4196   // one input.
4197   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4198   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4199   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4200   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4201   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4202   bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
4203   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4204                                  JA.isDeviceOffloading(Action::OFK_Host));
4205   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4206   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4207 
4208   // A header module compilation doesn't have a main input file, so invent a
4209   // fake one as a placeholder.
4210   const char *ModuleName = [&]{
4211     auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
4212     return ModuleNameArg ? ModuleNameArg->getValue() : "";
4213   }();
4214   InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
4215 
4216   const InputInfo &Input =
4217       IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
4218 
4219   InputInfoList ModuleHeaderInputs;
4220   const InputInfo *CudaDeviceInput = nullptr;
4221   const InputInfo *OpenMPDeviceInput = nullptr;
4222   for (const InputInfo &I : Inputs) {
4223     if (&I == &Input) {
4224       // This is the primary input.
4225     } else if (IsHeaderModulePrecompile &&
4226                types::getPrecompiledType(I.getType()) == types::TY_PCH) {
4227       types::ID Expected = HeaderModuleInput.getType();
4228       if (I.getType() != Expected) {
4229         D.Diag(diag::err_drv_module_header_wrong_kind)
4230             << I.getFilename() << types::getTypeName(I.getType())
4231             << types::getTypeName(Expected);
4232       }
4233       ModuleHeaderInputs.push_back(I);
4234     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4235       CudaDeviceInput = &I;
4236     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4237       OpenMPDeviceInput = &I;
4238     } else {
4239       llvm_unreachable("unexpectedly given multiple inputs");
4240     }
4241   }
4242 
4243   const llvm::Triple *AuxTriple =
4244       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4245   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4246   bool IsIAMCU = RawTriple.isOSIAMCU();
4247 
4248   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
4249   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4250   // Windows), we need to pass Windows-specific flags to cc1.
4251   if (IsCuda || IsHIP)
4252     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4253 
4254   // C++ is not supported for IAMCU.
4255   if (IsIAMCU && types::isCXX(Input.getType()))
4256     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4257 
4258   // Invoke ourselves in -cc1 mode.
4259   //
4260   // FIXME: Implement custom jobs for internal actions.
4261   CmdArgs.push_back("-cc1");
4262 
4263   // Add the "effective" target triple.
4264   CmdArgs.push_back("-triple");
4265   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4266 
4267   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4268     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4269     Args.ClaimAllArgs(options::OPT_MJ);
4270   } else if (const Arg *GenCDBFragment =
4271                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4272     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4273                                          TripleStr, Output, Input, Args);
4274     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4275   }
4276 
4277   if (IsCuda || IsHIP) {
4278     // We have to pass the triple of the host if compiling for a CUDA/HIP device
4279     // and vice-versa.
4280     std::string NormalizedTriple;
4281     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4282         JA.isDeviceOffloading(Action::OFK_HIP))
4283       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4284                              ->getTriple()
4285                              .normalize();
4286     else {
4287       // Host-side compilation.
4288       NormalizedTriple =
4289           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4290                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4291               ->getTriple()
4292               .normalize();
4293       if (IsCuda) {
4294         // We need to figure out which CUDA version we're compiling for, as that
4295         // determines how we load and launch GPU kernels.
4296         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4297             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4298         assert(CTC && "Expected valid CUDA Toolchain.");
4299         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4300           CmdArgs.push_back(Args.MakeArgString(
4301               Twine("-target-sdk-version=") +
4302               CudaVersionToString(CTC->CudaInstallation.version())));
4303       }
4304     }
4305     CmdArgs.push_back("-aux-triple");
4306     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4307   }
4308 
4309   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4310     CmdArgs.push_back("-fsycl-is-device");
4311 
4312     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4313       A->render(Args, CmdArgs);
4314     } else {
4315       // Ensure the default version in SYCL mode is 2020.
4316       CmdArgs.push_back("-sycl-std=2020");
4317     }
4318   }
4319 
4320   if (IsOpenMPDevice) {
4321     // We have to pass the triple of the host if compiling for an OpenMP device.
4322     std::string NormalizedTriple =
4323         C.getSingleOffloadToolChain<Action::OFK_Host>()
4324             ->getTriple()
4325             .normalize();
4326     CmdArgs.push_back("-aux-triple");
4327     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4328   }
4329 
4330   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4331                                Triple.getArch() == llvm::Triple::thumb)) {
4332     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4333     unsigned Version = 0;
4334     bool Failure =
4335         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4336     if (Failure || Version < 7)
4337       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4338                                                 << TripleStr;
4339   }
4340 
4341   // Push all default warning arguments that are specific to
4342   // the given target.  These come before user provided warning options
4343   // are provided.
4344   TC.addClangWarningOptions(CmdArgs);
4345 
4346   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4347   if (Triple.isSPIR())
4348     CmdArgs.push_back("-Wspir-compat");
4349 
4350   // Select the appropriate action.
4351   RewriteKind rewriteKind = RK_None;
4352 
4353   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4354   // it claims when not running an assembler. Otherwise, clang would emit
4355   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4356   // flags while debugging something. That'd be somewhat inconvenient, and it's
4357   // also inconsistent with most other flags -- we don't warn on
4358   // -ffunction-sections not being used in -E mode either for example, even
4359   // though it's not really used either.
4360   if (!isa<AssembleJobAction>(JA)) {
4361     // The args claimed here should match the args used in
4362     // CollectArgsForIntegratedAssembler().
4363     if (TC.useIntegratedAs()) {
4364       Args.ClaimAllArgs(options::OPT_mrelax_all);
4365       Args.ClaimAllArgs(options::OPT_mno_relax_all);
4366       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4367       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4368       switch (C.getDefaultToolChain().getArch()) {
4369       case llvm::Triple::arm:
4370       case llvm::Triple::armeb:
4371       case llvm::Triple::thumb:
4372       case llvm::Triple::thumbeb:
4373         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4374         break;
4375       default:
4376         break;
4377       }
4378     }
4379     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4380     Args.ClaimAllArgs(options::OPT_Xassembler);
4381   }
4382 
4383   if (isa<AnalyzeJobAction>(JA)) {
4384     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4385     CmdArgs.push_back("-analyze");
4386   } else if (isa<MigrateJobAction>(JA)) {
4387     CmdArgs.push_back("-migrate");
4388   } else if (isa<PreprocessJobAction>(JA)) {
4389     if (Output.getType() == types::TY_Dependencies)
4390       CmdArgs.push_back("-Eonly");
4391     else {
4392       CmdArgs.push_back("-E");
4393       if (Args.hasArg(options::OPT_rewrite_objc) &&
4394           !Args.hasArg(options::OPT_g_Group))
4395         CmdArgs.push_back("-P");
4396     }
4397   } else if (isa<AssembleJobAction>(JA)) {
4398     CmdArgs.push_back("-emit-obj");
4399 
4400     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4401 
4402     // Also ignore explicit -force_cpusubtype_ALL option.
4403     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4404   } else if (isa<PrecompileJobAction>(JA)) {
4405     if (JA.getType() == types::TY_Nothing)
4406       CmdArgs.push_back("-fsyntax-only");
4407     else if (JA.getType() == types::TY_ModuleFile)
4408       CmdArgs.push_back(IsHeaderModulePrecompile
4409                             ? "-emit-header-module"
4410                             : "-emit-module-interface");
4411     else
4412       CmdArgs.push_back("-emit-pch");
4413   } else if (isa<VerifyPCHJobAction>(JA)) {
4414     CmdArgs.push_back("-verify-pch");
4415   } else {
4416     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4417            "Invalid action for clang tool.");
4418     if (JA.getType() == types::TY_Nothing) {
4419       CmdArgs.push_back("-fsyntax-only");
4420     } else if (JA.getType() == types::TY_LLVM_IR ||
4421                JA.getType() == types::TY_LTO_IR) {
4422       CmdArgs.push_back("-emit-llvm");
4423     } else if (JA.getType() == types::TY_LLVM_BC ||
4424                JA.getType() == types::TY_LTO_BC) {
4425       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4426       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4427           Args.hasArg(options::OPT_emit_llvm)) {
4428         CmdArgs.push_back("-emit-llvm");
4429       } else {
4430         CmdArgs.push_back("-emit-llvm-bc");
4431       }
4432     } else if (JA.getType() == types::TY_IFS ||
4433                JA.getType() == types::TY_IFS_CPP) {
4434       StringRef ArgStr =
4435           Args.hasArg(options::OPT_interface_stub_version_EQ)
4436               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4437               : "experimental-ifs-v2";
4438       CmdArgs.push_back("-emit-interface-stubs");
4439       CmdArgs.push_back(
4440           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4441     } else if (JA.getType() == types::TY_PP_Asm) {
4442       CmdArgs.push_back("-S");
4443     } else if (JA.getType() == types::TY_AST) {
4444       CmdArgs.push_back("-emit-pch");
4445     } else if (JA.getType() == types::TY_ModuleFile) {
4446       CmdArgs.push_back("-module-file-info");
4447     } else if (JA.getType() == types::TY_RewrittenObjC) {
4448       CmdArgs.push_back("-rewrite-objc");
4449       rewriteKind = RK_NonFragile;
4450     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4451       CmdArgs.push_back("-rewrite-objc");
4452       rewriteKind = RK_Fragile;
4453     } else {
4454       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4455     }
4456 
4457     // Preserve use-list order by default when emitting bitcode, so that
4458     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4459     // same result as running passes here.  For LTO, we don't need to preserve
4460     // the use-list order, since serialization to bitcode is part of the flow.
4461     if (JA.getType() == types::TY_LLVM_BC)
4462       CmdArgs.push_back("-emit-llvm-uselists");
4463 
4464     if (IsUsingLTO) {
4465       if (!IsDeviceOffloadAction) {
4466         if (Args.hasArg(options::OPT_flto))
4467           CmdArgs.push_back("-flto");
4468         else {
4469           if (D.getLTOMode() == LTOK_Thin)
4470             CmdArgs.push_back("-flto=thin");
4471           else
4472             CmdArgs.push_back("-flto=full");
4473         }
4474         CmdArgs.push_back("-flto-unit");
4475       } else if (Triple.isAMDGPU()) {
4476         // Only AMDGPU supports device-side LTO
4477         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4478         CmdArgs.push_back(Args.MakeArgString(
4479             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4480         CmdArgs.push_back("-flto-unit");
4481       } else {
4482         D.Diag(diag::err_drv_unsupported_opt_for_target)
4483             << Args.getLastArg(options::OPT_foffload_lto,
4484                                options::OPT_foffload_lto_EQ)
4485                    ->getAsString(Args)
4486             << Triple.getTriple();
4487       }
4488     }
4489   }
4490 
4491   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4492     if (!types::isLLVMIR(Input.getType()))
4493       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4494     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4495   }
4496 
4497   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4498     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4499 
4500   if (Args.getLastArg(options::OPT_save_temps_EQ))
4501     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4502 
4503   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4504                                      options::OPT_fmemory_profile_EQ,
4505                                      options::OPT_fno_memory_profile);
4506   if (MemProfArg &&
4507       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4508     MemProfArg->render(Args, CmdArgs);
4509 
4510   // Embed-bitcode option.
4511   // Only white-listed flags below are allowed to be embedded.
4512   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4513       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4514     // Add flags implied by -fembed-bitcode.
4515     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4516     // Disable all llvm IR level optimizations.
4517     CmdArgs.push_back("-disable-llvm-passes");
4518 
4519     // Render target options.
4520     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4521 
4522     // reject options that shouldn't be supported in bitcode
4523     // also reject kernel/kext
4524     static const constexpr unsigned kBitcodeOptionBlacklist[] = {
4525         options::OPT_mkernel,
4526         options::OPT_fapple_kext,
4527         options::OPT_ffunction_sections,
4528         options::OPT_fno_function_sections,
4529         options::OPT_fdata_sections,
4530         options::OPT_fno_data_sections,
4531         options::OPT_fbasic_block_sections_EQ,
4532         options::OPT_funique_internal_linkage_names,
4533         options::OPT_fno_unique_internal_linkage_names,
4534         options::OPT_funique_section_names,
4535         options::OPT_fno_unique_section_names,
4536         options::OPT_funique_basic_block_section_names,
4537         options::OPT_fno_unique_basic_block_section_names,
4538         options::OPT_mrestrict_it,
4539         options::OPT_mno_restrict_it,
4540         options::OPT_mstackrealign,
4541         options::OPT_mno_stackrealign,
4542         options::OPT_mstack_alignment,
4543         options::OPT_mcmodel_EQ,
4544         options::OPT_mlong_calls,
4545         options::OPT_mno_long_calls,
4546         options::OPT_ggnu_pubnames,
4547         options::OPT_gdwarf_aranges,
4548         options::OPT_fdebug_types_section,
4549         options::OPT_fno_debug_types_section,
4550         options::OPT_fdwarf_directory_asm,
4551         options::OPT_fno_dwarf_directory_asm,
4552         options::OPT_mrelax_all,
4553         options::OPT_mno_relax_all,
4554         options::OPT_ftrap_function_EQ,
4555         options::OPT_ffixed_r9,
4556         options::OPT_mfix_cortex_a53_835769,
4557         options::OPT_mno_fix_cortex_a53_835769,
4558         options::OPT_ffixed_x18,
4559         options::OPT_mglobal_merge,
4560         options::OPT_mno_global_merge,
4561         options::OPT_mred_zone,
4562         options::OPT_mno_red_zone,
4563         options::OPT_Wa_COMMA,
4564         options::OPT_Xassembler,
4565         options::OPT_mllvm,
4566     };
4567     for (const auto &A : Args)
4568       if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
4569           std::end(kBitcodeOptionBlacklist))
4570         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4571 
4572     // Render the CodeGen options that need to be passed.
4573     if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4574                       options::OPT_fno_optimize_sibling_calls))
4575       CmdArgs.push_back("-mdisable-tail-calls");
4576 
4577     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4578                                CmdArgs, JA);
4579 
4580     // Render ABI arguments
4581     switch (TC.getArch()) {
4582     default: break;
4583     case llvm::Triple::arm:
4584     case llvm::Triple::armeb:
4585     case llvm::Triple::thumbeb:
4586       RenderARMABI(Triple, Args, CmdArgs);
4587       break;
4588     case llvm::Triple::aarch64:
4589     case llvm::Triple::aarch64_32:
4590     case llvm::Triple::aarch64_be:
4591       RenderAArch64ABI(Triple, Args, CmdArgs);
4592       break;
4593     }
4594 
4595     // Optimization level for CodeGen.
4596     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4597       if (A->getOption().matches(options::OPT_O4)) {
4598         CmdArgs.push_back("-O3");
4599         D.Diag(diag::warn_O4_is_O3);
4600       } else {
4601         A->render(Args, CmdArgs);
4602       }
4603     }
4604 
4605     // Input/Output file.
4606     if (Output.getType() == types::TY_Dependencies) {
4607       // Handled with other dependency code.
4608     } else if (Output.isFilename()) {
4609       CmdArgs.push_back("-o");
4610       CmdArgs.push_back(Output.getFilename());
4611     } else {
4612       assert(Output.isNothing() && "Input output.");
4613     }
4614 
4615     for (const auto &II : Inputs) {
4616       addDashXForInput(Args, II, CmdArgs);
4617       if (II.isFilename())
4618         CmdArgs.push_back(II.getFilename());
4619       else
4620         II.getInputArg().renderAsInput(Args, CmdArgs);
4621     }
4622 
4623     C.addCommand(std::make_unique<Command>(
4624         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
4625         CmdArgs, Inputs, Output));
4626     return;
4627   }
4628 
4629   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
4630     CmdArgs.push_back("-fembed-bitcode=marker");
4631 
4632   // We normally speed up the clang process a bit by skipping destructors at
4633   // exit, but when we're generating diagnostics we can rely on some of the
4634   // cleanup.
4635   if (!C.isForDiagnostics())
4636     CmdArgs.push_back("-disable-free");
4637 
4638 #ifdef NDEBUG
4639   const bool IsAssertBuild = false;
4640 #else
4641   const bool IsAssertBuild = true;
4642 #endif
4643 
4644   // Disable the verification pass in -asserts builds.
4645   if (!IsAssertBuild)
4646     CmdArgs.push_back("-disable-llvm-verifier");
4647 
4648   // Discard value names in assert builds unless otherwise specified.
4649   if (Args.hasFlag(options::OPT_fdiscard_value_names,
4650                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4651     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
4652         (std::any_of(Inputs.begin(), Inputs.end(),
4653                      [](const clang::driver::InputInfo &II) {
4654                        return types::isLLVMIR(II.getType());
4655                      }))) {
4656       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4657     }
4658     CmdArgs.push_back("-discard-value-names");
4659   }
4660 
4661   // Set the main file name, so that debug info works even with
4662   // -save-temps.
4663   CmdArgs.push_back("-main-file-name");
4664   CmdArgs.push_back(getBaseInputName(Args, Input));
4665 
4666   // Some flags which affect the language (via preprocessor
4667   // defines).
4668   if (Args.hasArg(options::OPT_static))
4669     CmdArgs.push_back("-static-define");
4670 
4671   if (Args.hasArg(options::OPT_municode))
4672     CmdArgs.push_back("-DUNICODE");
4673 
4674   if (isa<AnalyzeJobAction>(JA))
4675     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4676 
4677   if (isa<AnalyzeJobAction>(JA) ||
4678       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
4679     CmdArgs.push_back("-setup-static-analyzer");
4680 
4681   // Enable compatilibily mode to avoid analyzer-config related errors.
4682   // Since we can't access frontend flags through hasArg, let's manually iterate
4683   // through them.
4684   bool FoundAnalyzerConfig = false;
4685   for (auto Arg : Args.filtered(options::OPT_Xclang))
4686     if (StringRef(Arg->getValue()) == "-analyzer-config") {
4687       FoundAnalyzerConfig = true;
4688       break;
4689     }
4690   if (!FoundAnalyzerConfig)
4691     for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
4692       if (StringRef(Arg->getValue()) == "-analyzer-config") {
4693         FoundAnalyzerConfig = true;
4694         break;
4695       }
4696   if (FoundAnalyzerConfig)
4697     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
4698 
4699   CheckCodeGenerationOptions(D, Args);
4700 
4701   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
4702   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
4703   if (FunctionAlignment) {
4704     CmdArgs.push_back("-function-alignment");
4705     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
4706   }
4707 
4708   llvm::Reloc::Model RelocationModel;
4709   unsigned PICLevel;
4710   bool IsPIE;
4711   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
4712 
4713   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
4714                 RelocationModel == llvm::Reloc::ROPI_RWPI;
4715   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
4716                 RelocationModel == llvm::Reloc::ROPI_RWPI;
4717 
4718   if (Args.hasArg(options::OPT_mcmse) &&
4719       !Args.hasArg(options::OPT_fallow_unsupported)) {
4720     if (IsROPI)
4721       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
4722     if (IsRWPI)
4723       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
4724   }
4725 
4726   if (IsROPI && types::isCXX(Input.getType()) &&
4727       !Args.hasArg(options::OPT_fallow_unsupported))
4728     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4729 
4730   const char *RMName = RelocationModelName(RelocationModel);
4731   if (RMName) {
4732     CmdArgs.push_back("-mrelocation-model");
4733     CmdArgs.push_back(RMName);
4734   }
4735   if (PICLevel > 0) {
4736     CmdArgs.push_back("-pic-level");
4737     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4738     if (IsPIE)
4739       CmdArgs.push_back("-pic-is-pie");
4740   }
4741 
4742   if (RelocationModel == llvm::Reloc::ROPI ||
4743       RelocationModel == llvm::Reloc::ROPI_RWPI)
4744     CmdArgs.push_back("-fropi");
4745   if (RelocationModel == llvm::Reloc::RWPI ||
4746       RelocationModel == llvm::Reloc::ROPI_RWPI)
4747     CmdArgs.push_back("-frwpi");
4748 
4749   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4750     CmdArgs.push_back("-meabi");
4751     CmdArgs.push_back(A->getValue());
4752   }
4753 
4754   // -fsemantic-interposition is forwarded to CC1: set the
4755   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
4756   // make default visibility external linkage definitions dso_preemptable.
4757   //
4758   // -fno-semantic-interposition: if the target supports .Lfoo$local local
4759   // aliases (make default visibility external linkage definitions dso_local).
4760   // This is the CC1 default for ELF to match COFF/Mach-O.
4761   //
4762   // Otherwise use Clang's traditional behavior: like
4763   // -fno-semantic-interposition but local aliases are not used. So references
4764   // can be interposed if not optimized out.
4765   if (Triple.isOSBinFormatELF()) {
4766     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
4767                              options::OPT_fno_semantic_interposition);
4768     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
4769       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
4770       bool SupportsLocalAlias =
4771           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
4772       if (!A)
4773         CmdArgs.push_back("-fhalf-no-semantic-interposition");
4774       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
4775         A->render(Args, CmdArgs);
4776       else if (!SupportsLocalAlias)
4777         CmdArgs.push_back("-fhalf-no-semantic-interposition");
4778     }
4779   }
4780 
4781   {
4782     std::string Model;
4783     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
4784       if (!TC.isThreadModelSupported(A->getValue()))
4785         D.Diag(diag::err_drv_invalid_thread_model_for_target)
4786             << A->getValue() << A->getAsString(Args);
4787       Model = A->getValue();
4788     } else
4789       Model = TC.getThreadModel();
4790     if (Model != "posix") {
4791       CmdArgs.push_back("-mthread-model");
4792       CmdArgs.push_back(Args.MakeArgString(Model));
4793     }
4794   }
4795 
4796   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4797 
4798   if (Args.hasFlag(options::OPT_fmerge_all_constants,
4799                    options::OPT_fno_merge_all_constants, false))
4800     CmdArgs.push_back("-fmerge-all-constants");
4801 
4802   if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
4803                    options::OPT_fdelete_null_pointer_checks, false))
4804     CmdArgs.push_back("-fno-delete-null-pointer-checks");
4805 
4806   // LLVM Code Generator Options.
4807 
4808   for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
4809     StringRef Map = A->getValue();
4810     if (!llvm::sys::fs::exists(Map)) {
4811       D.Diag(diag::err_drv_no_such_file) << Map;
4812     } else {
4813       A->render(Args, CmdArgs);
4814       A->claim();
4815     }
4816   }
4817 
4818   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
4819                                options::OPT_mabi_EQ_vec_default)) {
4820     if (!Triple.isOSAIX())
4821       D.Diag(diag::err_drv_unsupported_opt_for_target)
4822           << A->getSpelling() << RawTriple.str();
4823     if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
4824       CmdArgs.push_back("-mabi=vec-extabi");
4825     else
4826       D.Diag(diag::err_aix_default_altivec_abi);
4827   }
4828 
4829   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4830     StringRef v = A->getValue();
4831     CmdArgs.push_back("-mllvm");
4832     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4833     A->claim();
4834   }
4835 
4836   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4837                     true))
4838     CmdArgs.push_back("-fno-jump-tables");
4839 
4840   if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4841                    options::OPT_fno_profile_sample_accurate, false))
4842     CmdArgs.push_back("-fprofile-sample-accurate");
4843 
4844   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4845                     options::OPT_fno_preserve_as_comments, true))
4846     CmdArgs.push_back("-fno-preserve-as-comments");
4847 
4848   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4849     CmdArgs.push_back("-mregparm");
4850     CmdArgs.push_back(A->getValue());
4851   }
4852 
4853   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
4854                                options::OPT_msvr4_struct_return)) {
4855     if (!TC.getTriple().isPPC32()) {
4856       D.Diag(diag::err_drv_unsupported_opt_for_target)
4857           << A->getSpelling() << RawTriple.str();
4858     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
4859       CmdArgs.push_back("-maix-struct-return");
4860     } else {
4861       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
4862       CmdArgs.push_back("-msvr4-struct-return");
4863     }
4864   }
4865 
4866   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4867                                options::OPT_freg_struct_return)) {
4868     if (TC.getArch() != llvm::Triple::x86) {
4869       D.Diag(diag::err_drv_unsupported_opt_for_target)
4870           << A->getSpelling() << RawTriple.str();
4871     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4872       CmdArgs.push_back("-fpcc-struct-return");
4873     } else {
4874       assert(A->getOption().matches(options::OPT_freg_struct_return));
4875       CmdArgs.push_back("-freg-struct-return");
4876     }
4877   }
4878 
4879   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4880     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4881 
4882   if (Args.hasArg(options::OPT_fenable_matrix)) {
4883     // enable-matrix is needed by both the LangOpts and by LLVM.
4884     CmdArgs.push_back("-fenable-matrix");
4885     CmdArgs.push_back("-mllvm");
4886     CmdArgs.push_back("-enable-matrix");
4887   }
4888 
4889   CodeGenOptions::FramePointerKind FPKeepKind =
4890                   getFramePointerKind(Args, RawTriple);
4891   const char *FPKeepKindStr = nullptr;
4892   switch (FPKeepKind) {
4893   case CodeGenOptions::FramePointerKind::None:
4894     FPKeepKindStr = "-mframe-pointer=none";
4895     break;
4896   case CodeGenOptions::FramePointerKind::NonLeaf:
4897     FPKeepKindStr = "-mframe-pointer=non-leaf";
4898     break;
4899   case CodeGenOptions::FramePointerKind::All:
4900     FPKeepKindStr = "-mframe-pointer=all";
4901     break;
4902   }
4903   assert(FPKeepKindStr && "unknown FramePointerKind");
4904   CmdArgs.push_back(FPKeepKindStr);
4905 
4906   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4907                     options::OPT_fno_zero_initialized_in_bss, true))
4908     CmdArgs.push_back("-fno-zero-initialized-in-bss");
4909 
4910   bool OFastEnabled = isOptimizationLevelFast(Args);
4911   // If -Ofast is the optimization level, then -fstrict-aliasing should be
4912   // enabled.  This alias option is being used to simplify the hasFlag logic.
4913   OptSpecifier StrictAliasingAliasOption =
4914       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4915   // We turn strict aliasing off by default if we're in CL mode, since MSVC
4916   // doesn't do any TBAA.
4917   bool TBAAOnByDefault = !D.IsCLMode();
4918   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4919                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4920     CmdArgs.push_back("-relaxed-aliasing");
4921   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4922                     options::OPT_fno_struct_path_tbaa))
4923     CmdArgs.push_back("-no-struct-path-tbaa");
4924   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4925                    false))
4926     CmdArgs.push_back("-fstrict-enums");
4927   if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4928                     true))
4929     CmdArgs.push_back("-fno-strict-return");
4930   if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4931                    options::OPT_fno_allow_editor_placeholders, false))
4932     CmdArgs.push_back("-fallow-editor-placeholders");
4933   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4934                    options::OPT_fno_strict_vtable_pointers,
4935                    false))
4936     CmdArgs.push_back("-fstrict-vtable-pointers");
4937   if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4938                    options::OPT_fno_force_emit_vtables,
4939                    false))
4940     CmdArgs.push_back("-fforce-emit-vtables");
4941   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4942                     options::OPT_fno_optimize_sibling_calls))
4943     CmdArgs.push_back("-mdisable-tail-calls");
4944   if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
4945                    options::OPT_fescaping_block_tail_calls, false))
4946     CmdArgs.push_back("-fno-escaping-block-tail-calls");
4947 
4948   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4949                   options::OPT_fno_fine_grained_bitfield_accesses);
4950 
4951   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
4952                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
4953 
4954   // Handle segmented stacks.
4955   if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack,
4956                    false))
4957     CmdArgs.push_back("-fsplit-stack");
4958 
4959   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
4960 
4961   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
4962     const llvm::Triple::ArchType Arch = TC.getArch();
4963     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
4964       StringRef V = A->getValue();
4965       if (V == "64")
4966         CmdArgs.push_back("-fextend-arguments=64");
4967       else if (V != "32")
4968         D.Diag(diag::err_drv_invalid_argument_to_option)
4969             << A->getValue() << A->getOption().getName();
4970     } else
4971       D.Diag(diag::err_drv_unsupported_opt_for_target)
4972           << A->getOption().getName() << TripleStr;
4973   }
4974 
4975   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
4976     if (TC.getArch() == llvm::Triple::avr)
4977       A->render(Args, CmdArgs);
4978     else
4979       D.Diag(diag::err_drv_unsupported_opt_for_target)
4980           << A->getAsString(Args) << TripleStr;
4981   }
4982 
4983   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4984     if (TC.getTriple().isX86())
4985       A->render(Args, CmdArgs);
4986     else if (TC.getTriple().isPPC() &&
4987              (A->getOption().getID() != options::OPT_mlong_double_80))
4988       A->render(Args, CmdArgs);
4989     else
4990       D.Diag(diag::err_drv_unsupported_opt_for_target)
4991           << A->getAsString(Args) << TripleStr;
4992   }
4993 
4994   // Decide whether to use verbose asm. Verbose assembly is the default on
4995   // toolchains which have the integrated assembler on by default.
4996   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
4997   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4998                     IsIntegratedAssemblerDefault))
4999     CmdArgs.push_back("-fno-verbose-asm");
5000 
5001   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5002   // use that to indicate the MC default in the backend.
5003   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5004     StringRef V = A->getValue();
5005     unsigned Num;
5006     if (V == "none")
5007       A->render(Args, CmdArgs);
5008     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5009              (V.empty() || (V.consume_front(".") &&
5010                             !V.consumeInteger(10, Num) && V.empty())))
5011       A->render(Args, CmdArgs);
5012     else
5013       D.Diag(diag::err_drv_invalid_argument_to_option)
5014           << A->getValue() << A->getOption().getName();
5015   }
5016 
5017   if (!TC.useIntegratedAs())
5018     CmdArgs.push_back("-no-integrated-as");
5019 
5020   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5021     CmdArgs.push_back("-mdebug-pass");
5022     CmdArgs.push_back("Structure");
5023   }
5024   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5025     CmdArgs.push_back("-mdebug-pass");
5026     CmdArgs.push_back("Arguments");
5027   }
5028 
5029   // Enable -mconstructor-aliases except on darwin, where we have to work around
5030   // a linker bug (see <rdar://problem/7651567>), and CUDA/AMDGPU device code,
5031   // where aliases aren't supported. Similarly, aliases aren't yet supported
5032   // for AIX.
5033   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX() &&
5034       !RawTriple.isAMDGPU() && !RawTriple.isOSAIX())
5035     CmdArgs.push_back("-mconstructor-aliases");
5036 
5037   // Darwin's kernel doesn't support guard variables; just die if we
5038   // try to use them.
5039   if (KernelOrKext && RawTriple.isOSDarwin())
5040     CmdArgs.push_back("-fforbid-guard-variables");
5041 
5042   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5043                    Triple.isWindowsGNUEnvironment())) {
5044     CmdArgs.push_back("-mms-bitfields");
5045   }
5046 
5047   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5048   // defaults to -fno-direct-access-external-data. Pass the option if different
5049   // from the default.
5050   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5051                                options::OPT_fno_direct_access_external_data))
5052     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5053         (PICLevel == 0))
5054       A->render(Args, CmdArgs);
5055 
5056   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5057     CmdArgs.push_back("-fno-plt");
5058   }
5059 
5060   // -fhosted is default.
5061   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5062   // use Freestanding.
5063   bool Freestanding =
5064       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5065       KernelOrKext;
5066   if (Freestanding)
5067     CmdArgs.push_back("-ffreestanding");
5068 
5069   // This is a coarse approximation of what llvm-gcc actually does, both
5070   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5071   // complicated ways.
5072   bool UnwindTables =
5073       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
5074                    options::OPT_fno_asynchronous_unwind_tables,
5075                    (TC.IsUnwindTablesDefault(Args) ||
5076                     TC.getSanitizerArgs().needsUnwindTables()) &&
5077                        !Freestanding);
5078   UnwindTables = Args.hasFlag(options::OPT_funwind_tables,
5079                               options::OPT_fno_unwind_tables, UnwindTables);
5080   if (UnwindTables)
5081     CmdArgs.push_back("-munwind-tables");
5082 
5083   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5084   // `--gpu-use-aux-triple-only` is specified.
5085   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5086       (IsCudaDevice || IsHIPDevice)) {
5087     const ArgList &HostArgs =
5088         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5089     std::string HostCPU =
5090         getCPUName(HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5091     if (!HostCPU.empty()) {
5092       CmdArgs.push_back("-aux-target-cpu");
5093       CmdArgs.push_back(Args.MakeArgString(HostCPU));
5094     }
5095     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5096                       /*ForAS*/ false, /*IsAux*/ true);
5097   }
5098 
5099   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5100 
5101   // FIXME: Handle -mtune=.
5102   (void)Args.hasArg(options::OPT_mtune_EQ);
5103 
5104   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5105     StringRef CM = A->getValue();
5106     if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5107         CM == "tiny")
5108       A->render(Args, CmdArgs);
5109     else
5110       D.Diag(diag::err_drv_invalid_argument_to_option)
5111           << CM << A->getOption().getName();
5112   }
5113 
5114   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5115     StringRef Value = A->getValue();
5116     unsigned TLSSize = 0;
5117     Value.getAsInteger(10, TLSSize);
5118     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5119       D.Diag(diag::err_drv_unsupported_opt_for_target)
5120           << A->getOption().getName() << TripleStr;
5121     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5122       D.Diag(diag::err_drv_invalid_int_value)
5123           << A->getOption().getName() << Value;
5124     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5125   }
5126 
5127   // Add the target cpu
5128   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
5129   if (!CPU.empty()) {
5130     CmdArgs.push_back("-target-cpu");
5131     CmdArgs.push_back(Args.MakeArgString(CPU));
5132   }
5133 
5134   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5135 
5136   // FIXME: For now we want to demote any errors to warnings, when they have
5137   // been raised for asking the wrong question of scalable vectors, such as
5138   // asking for the fixed number of elements. This may happen because code that
5139   // is not yet ported to work for scalable vectors uses the wrong interfaces,
5140   // whereas the behaviour is actually correct. Emitting a warning helps bring
5141   // up scalable vector support in an incremental way. When scalable vector
5142   // support is stable enough, all uses of wrong interfaces should be considered
5143   // as errors, but until then, we can live with a warning being emitted by the
5144   // compiler. This way, Clang can be used to compile code with scalable vectors
5145   // and identify possible issues.
5146   if (isa<BackendJobAction>(JA)) {
5147     CmdArgs.push_back("-mllvm");
5148     CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
5149   }
5150 
5151   // These two are potentially updated by AddClangCLArgs.
5152   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5153   bool EmitCodeView = false;
5154 
5155   // Add clang-cl arguments.
5156   types::ID InputType = Input.getType();
5157   if (D.IsCLMode())
5158     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5159 
5160   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5161   renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5162                      types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5163                      DwarfFission);
5164 
5165   // Add the split debug info name to the command lines here so we
5166   // can propagate it to the backend.
5167   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5168                     (TC.getTriple().isOSBinFormatELF() ||
5169                      TC.getTriple().isOSBinFormatWasm()) &&
5170                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5171                      isa<BackendJobAction>(JA));
5172   if (SplitDWARF) {
5173     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5174     CmdArgs.push_back("-split-dwarf-file");
5175     CmdArgs.push_back(SplitDWARFOut);
5176     if (DwarfFission == DwarfFissionKind::Split) {
5177       CmdArgs.push_back("-split-dwarf-output");
5178       CmdArgs.push_back(SplitDWARFOut);
5179     }
5180   }
5181 
5182   // Pass the linker version in use.
5183   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5184     CmdArgs.push_back("-target-linker-version");
5185     CmdArgs.push_back(A->getValue());
5186   }
5187 
5188   // Explicitly error on some things we know we don't support and can't just
5189   // ignore.
5190   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5191     Arg *Unsupported;
5192     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5193         TC.getArch() == llvm::Triple::x86) {
5194       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5195           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5196         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5197             << Unsupported->getOption().getName();
5198     }
5199     // The faltivec option has been superseded by the maltivec option.
5200     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5201       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5202           << Unsupported->getOption().getName()
5203           << "please use -maltivec and include altivec.h explicitly";
5204     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5205       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5206           << Unsupported->getOption().getName() << "please use -mno-altivec";
5207   }
5208 
5209   Args.AddAllArgs(CmdArgs, options::OPT_v);
5210 
5211   if (Args.getLastArg(options::OPT_H)) {
5212     CmdArgs.push_back("-H");
5213     CmdArgs.push_back("-sys-header-deps");
5214   }
5215   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5216 
5217   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
5218     CmdArgs.push_back("-header-include-file");
5219     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5220                           ? D.CCPrintHeadersFilename.c_str()
5221                           : "-");
5222     CmdArgs.push_back("-sys-header-deps");
5223   }
5224   Args.AddLastArg(CmdArgs, options::OPT_P);
5225   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5226 
5227   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5228     CmdArgs.push_back("-diagnostic-log-file");
5229     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5230                           ? D.CCLogDiagnosticsFilename.c_str()
5231                           : "-");
5232   }
5233 
5234   // Give the gen diagnostics more chances to succeed, by avoiding intentional
5235   // crashes.
5236   if (D.CCGenDiagnostics)
5237     CmdArgs.push_back("-disable-pragma-debug-crash");
5238 
5239   // Allow backend to put its diagnostic files in the same place as frontend
5240   // crash diagnostics files.
5241   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5242     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5243     CmdArgs.push_back("-mllvm");
5244     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5245   }
5246 
5247   bool UseSeparateSections = isUseSeparateSections(Triple);
5248 
5249   if (Args.hasFlag(options::OPT_ffunction_sections,
5250                    options::OPT_fno_function_sections, UseSeparateSections)) {
5251     CmdArgs.push_back("-ffunction-sections");
5252   }
5253 
5254   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5255     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5256       StringRef Val = A->getValue();
5257       if (Val != "all" && Val != "labels" && Val != "none" &&
5258           !Val.startswith("list="))
5259         D.Diag(diag::err_drv_invalid_value)
5260             << A->getAsString(Args) << A->getValue();
5261       else
5262         A->render(Args, CmdArgs);
5263     } else {
5264       D.Diag(diag::err_drv_unsupported_opt_for_target)
5265           << A->getAsString(Args) << TripleStr;
5266     }
5267   }
5268 
5269   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5270   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5271                    UseSeparateSections || HasDefaultDataSections)) {
5272     CmdArgs.push_back("-fdata-sections");
5273   }
5274 
5275   if (!Args.hasFlag(options::OPT_funique_section_names,
5276                     options::OPT_fno_unique_section_names, true))
5277     CmdArgs.push_back("-fno-unique-section-names");
5278 
5279   if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
5280                    options::OPT_fno_unique_internal_linkage_names, false))
5281     CmdArgs.push_back("-funique-internal-linkage-names");
5282 
5283   if (Args.hasFlag(options::OPT_funique_basic_block_section_names,
5284                    options::OPT_fno_unique_basic_block_section_names, false))
5285     CmdArgs.push_back("-funique-basic-block-section-names");
5286 
5287   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5288                                options::OPT_fno_split_machine_functions)) {
5289     // This codegen pass is only available on x86-elf targets.
5290     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5291       if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5292         A->render(Args, CmdArgs);
5293     } else {
5294       D.Diag(diag::err_drv_unsupported_opt_for_target)
5295           << A->getAsString(Args) << TripleStr;
5296     }
5297   }
5298 
5299   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5300                   options::OPT_finstrument_functions_after_inlining,
5301                   options::OPT_finstrument_function_entry_bare);
5302 
5303   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5304   // for sampling, overhead of call arc collection is way too high and there's
5305   // no way to collect the output.
5306   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5307     addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
5308 
5309   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5310 
5311   // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
5312   if (RawTriple.isPS4CPU() &&
5313       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5314     PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
5315     PS4cpu::addSanitizerArgs(TC, CmdArgs);
5316   }
5317 
5318   // Pass options for controlling the default header search paths.
5319   if (Args.hasArg(options::OPT_nostdinc)) {
5320     CmdArgs.push_back("-nostdsysteminc");
5321     CmdArgs.push_back("-nobuiltininc");
5322   } else {
5323     if (Args.hasArg(options::OPT_nostdlibinc))
5324       CmdArgs.push_back("-nostdsysteminc");
5325     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5326     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5327   }
5328 
5329   // Pass the path to compiler resource files.
5330   CmdArgs.push_back("-resource-dir");
5331   CmdArgs.push_back(D.ResourceDir.c_str());
5332 
5333   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5334 
5335   RenderARCMigrateToolOptions(D, Args, CmdArgs);
5336 
5337   // Add preprocessing options like -I, -D, etc. if we are using the
5338   // preprocessor.
5339   //
5340   // FIXME: Support -fpreprocessed
5341   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5342     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5343 
5344   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5345   // that "The compiler can only warn and ignore the option if not recognized".
5346   // When building with ccache, it will pass -D options to clang even on
5347   // preprocessed inputs and configure concludes that -fPIC is not supported.
5348   Args.ClaimAllArgs(options::OPT_D);
5349 
5350   // Manually translate -O4 to -O3; let clang reject others.
5351   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5352     if (A->getOption().matches(options::OPT_O4)) {
5353       CmdArgs.push_back("-O3");
5354       D.Diag(diag::warn_O4_is_O3);
5355     } else {
5356       A->render(Args, CmdArgs);
5357     }
5358   }
5359 
5360   // Warn about ignored options to clang.
5361   for (const Arg *A :
5362        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5363     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5364     A->claim();
5365   }
5366 
5367   for (const Arg *A :
5368        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5369     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5370     A->claim();
5371   }
5372 
5373   claimNoWarnArgs(Args);
5374 
5375   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5376 
5377   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
5378   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5379     CmdArgs.push_back("-pedantic");
5380   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5381   Args.AddLastArg(CmdArgs, options::OPT_w);
5382 
5383   // Fixed point flags
5384   if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
5385                    /*Default=*/false))
5386     Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
5387 
5388   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5389     A->render(Args, CmdArgs);
5390 
5391   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5392   // (-ansi is equivalent to -std=c89 or -std=c++98).
5393   //
5394   // If a std is supplied, only add -trigraphs if it follows the
5395   // option.
5396   bool ImplyVCPPCVer = false;
5397   bool ImplyVCPPCXXVer = false;
5398   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5399   if (Std) {
5400     if (Std->getOption().matches(options::OPT_ansi))
5401       if (types::isCXX(InputType))
5402         CmdArgs.push_back("-std=c++98");
5403       else
5404         CmdArgs.push_back("-std=c89");
5405     else
5406       Std->render(Args, CmdArgs);
5407 
5408     // If -f(no-)trigraphs appears after the language standard flag, honor it.
5409     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5410                                  options::OPT_ftrigraphs,
5411                                  options::OPT_fno_trigraphs))
5412       if (A != Std)
5413         A->render(Args, CmdArgs);
5414   } else {
5415     // Honor -std-default.
5416     //
5417     // FIXME: Clang doesn't correctly handle -std= when the input language
5418     // doesn't match. For the time being just ignore this for C++ inputs;
5419     // eventually we want to do all the standard defaulting here instead of
5420     // splitting it between the driver and clang -cc1.
5421     if (!types::isCXX(InputType)) {
5422       if (!Args.hasArg(options::OPT__SLASH_std)) {
5423         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5424                                   /*Joined=*/true);
5425       } else
5426         ImplyVCPPCVer = true;
5427     }
5428     else if (IsWindowsMSVC)
5429       ImplyVCPPCXXVer = true;
5430 
5431     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5432                     options::OPT_fno_trigraphs);
5433 
5434     // HIP headers has minimum C++ standard requirements. Therefore set the
5435     // default language standard.
5436     if (IsHIP)
5437       CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11");
5438   }
5439 
5440   // GCC's behavior for -Wwrite-strings is a bit strange:
5441   //  * In C, this "warning flag" changes the types of string literals from
5442   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5443   //    for the discarded qualifier.
5444   //  * In C++, this is just a normal warning flag.
5445   //
5446   // Implementing this warning correctly in C is hard, so we follow GCC's
5447   // behavior for now. FIXME: Directly diagnose uses of a string literal as
5448   // a non-const char* in C, rather than using this crude hack.
5449   if (!types::isCXX(InputType)) {
5450     // FIXME: This should behave just like a warning flag, and thus should also
5451     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5452     Arg *WriteStrings =
5453         Args.getLastArg(options::OPT_Wwrite_strings,
5454                         options::OPT_Wno_write_strings, options::OPT_w);
5455     if (WriteStrings &&
5456         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5457       CmdArgs.push_back("-fconst-strings");
5458   }
5459 
5460   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5461   // during C++ compilation, which it is by default. GCC keeps this define even
5462   // in the presence of '-w', match this behavior bug-for-bug.
5463   if (types::isCXX(InputType) &&
5464       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5465                    true)) {
5466     CmdArgs.push_back("-fdeprecated-macro");
5467   }
5468 
5469   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5470   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5471     if (Asm->getOption().matches(options::OPT_fasm))
5472       CmdArgs.push_back("-fgnu-keywords");
5473     else
5474       CmdArgs.push_back("-fno-gnu-keywords");
5475   }
5476 
5477   if (ShouldDisableDwarfDirectory(Args, TC))
5478     CmdArgs.push_back("-fno-dwarf-directory-asm");
5479 
5480   if (!ShouldEnableAutolink(Args, TC, JA))
5481     CmdArgs.push_back("-fno-autolink");
5482 
5483   // Add in -fdebug-compilation-dir if necessary.
5484   addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5485 
5486   addDebugPrefixMapArg(D, Args, CmdArgs);
5487 
5488   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5489                                options::OPT_ftemplate_depth_EQ)) {
5490     CmdArgs.push_back("-ftemplate-depth");
5491     CmdArgs.push_back(A->getValue());
5492   }
5493 
5494   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5495     CmdArgs.push_back("-foperator-arrow-depth");
5496     CmdArgs.push_back(A->getValue());
5497   }
5498 
5499   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5500     CmdArgs.push_back("-fconstexpr-depth");
5501     CmdArgs.push_back(A->getValue());
5502   }
5503 
5504   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5505     CmdArgs.push_back("-fconstexpr-steps");
5506     CmdArgs.push_back(A->getValue());
5507   }
5508 
5509   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
5510     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
5511 
5512   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5513     CmdArgs.push_back("-fbracket-depth");
5514     CmdArgs.push_back(A->getValue());
5515   }
5516 
5517   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5518                                options::OPT_Wlarge_by_value_copy_def)) {
5519     if (A->getNumValues()) {
5520       StringRef bytes = A->getValue();
5521       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5522     } else
5523       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5524   }
5525 
5526   if (Args.hasArg(options::OPT_relocatable_pch))
5527     CmdArgs.push_back("-relocatable-pch");
5528 
5529   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
5530     static const char *kCFABIs[] = {
5531       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
5532     };
5533 
5534     if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
5535       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
5536     else
5537       A->render(Args, CmdArgs);
5538   }
5539 
5540   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5541     CmdArgs.push_back("-fconstant-string-class");
5542     CmdArgs.push_back(A->getValue());
5543   }
5544 
5545   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5546     CmdArgs.push_back("-ftabstop");
5547     CmdArgs.push_back(A->getValue());
5548   }
5549 
5550   if (Args.hasFlag(options::OPT_fstack_size_section,
5551                    options::OPT_fno_stack_size_section, RawTriple.isPS4()))
5552     CmdArgs.push_back("-fstack-size-section");
5553 
5554   if (Args.hasArg(options::OPT_fstack_usage)) {
5555     CmdArgs.push_back("-stack-usage-file");
5556 
5557     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5558       SmallString<128> OutputFilename(OutputOpt->getValue());
5559       llvm::sys::path::replace_extension(OutputFilename, "su");
5560       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
5561     } else
5562       CmdArgs.push_back(
5563           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
5564   }
5565 
5566   CmdArgs.push_back("-ferror-limit");
5567   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
5568     CmdArgs.push_back(A->getValue());
5569   else
5570     CmdArgs.push_back("19");
5571 
5572   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
5573     CmdArgs.push_back("-fmacro-backtrace-limit");
5574     CmdArgs.push_back(A->getValue());
5575   }
5576 
5577   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
5578     CmdArgs.push_back("-ftemplate-backtrace-limit");
5579     CmdArgs.push_back(A->getValue());
5580   }
5581 
5582   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
5583     CmdArgs.push_back("-fconstexpr-backtrace-limit");
5584     CmdArgs.push_back(A->getValue());
5585   }
5586 
5587   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
5588     CmdArgs.push_back("-fspell-checking-limit");
5589     CmdArgs.push_back(A->getValue());
5590   }
5591 
5592   // Pass -fmessage-length=.
5593   unsigned MessageLength = 0;
5594   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
5595     StringRef V(A->getValue());
5596     if (V.getAsInteger(0, MessageLength))
5597       D.Diag(diag::err_drv_invalid_argument_to_option)
5598           << V << A->getOption().getName();
5599   } else {
5600     // If -fmessage-length=N was not specified, determine whether this is a
5601     // terminal and, if so, implicitly define -fmessage-length appropriately.
5602     MessageLength = llvm::sys::Process::StandardErrColumns();
5603   }
5604   if (MessageLength != 0)
5605     CmdArgs.push_back(
5606         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
5607 
5608   // -fvisibility= and -fvisibility-ms-compat are of a piece.
5609   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
5610                                      options::OPT_fvisibility_ms_compat)) {
5611     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
5612       CmdArgs.push_back("-fvisibility");
5613       CmdArgs.push_back(A->getValue());
5614     } else {
5615       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
5616       CmdArgs.push_back("-fvisibility");
5617       CmdArgs.push_back("hidden");
5618       CmdArgs.push_back("-ftype-visibility");
5619       CmdArgs.push_back("default");
5620     }
5621   }
5622 
5623   if (!RawTriple.isPS4())
5624     if (const Arg *A =
5625             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
5626                             options::OPT_fno_visibility_from_dllstorageclass)) {
5627       if (A->getOption().matches(
5628               options::OPT_fvisibility_from_dllstorageclass)) {
5629         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
5630         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
5631         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
5632         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
5633         Args.AddLastArg(CmdArgs,
5634                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
5635       }
5636     }
5637 
5638   if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
5639     if (Triple.isOSAIX())
5640       CmdArgs.push_back("-mignore-xcoff-visibility");
5641     else
5642       D.Diag(diag::err_drv_unsupported_opt_for_target)
5643           << A->getAsString(Args) << TripleStr;
5644   }
5645 
5646   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
5647   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
5648                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
5649   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
5650 
5651   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
5652 
5653   // Forward -f (flag) options which we can pass directly.
5654   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5655   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5656   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
5657   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5658   Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
5659                   options::OPT_fno_emulated_tls);
5660 
5661   // AltiVec-like language extensions aren't relevant for assembling.
5662   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
5663     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5664 
5665   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5666   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5667 
5668   // Forward flags for OpenMP. We don't do this if the current action is an
5669   // device offloading action other than OpenMP.
5670   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5671                    options::OPT_fno_openmp, false) &&
5672       (JA.isDeviceOffloading(Action::OFK_None) ||
5673        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
5674     switch (D.getOpenMPRuntime(Args)) {
5675     case Driver::OMPRT_OMP:
5676     case Driver::OMPRT_IOMP5:
5677       // Clang can generate useful OpenMP code for these two runtime libraries.
5678       CmdArgs.push_back("-fopenmp");
5679 
5680       // If no option regarding the use of TLS in OpenMP codegeneration is
5681       // given, decide a default based on the target. Otherwise rely on the
5682       // options and pass the right information to the frontend.
5683       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5684                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5685         CmdArgs.push_back("-fnoopenmp-use-tls");
5686       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
5687                       options::OPT_fno_openmp_simd);
5688       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
5689       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5690       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
5691       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
5692       Args.AddAllArgs(CmdArgs,
5693                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
5694       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
5695                        options::OPT_fno_openmp_optimistic_collapse,
5696                        /*Default=*/false))
5697         CmdArgs.push_back("-fopenmp-optimistic-collapse");
5698 
5699       // When in OpenMP offloading mode with NVPTX target, forward
5700       // cuda-mode flag
5701       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
5702                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
5703         CmdArgs.push_back("-fopenmp-cuda-mode");
5704 
5705       // When in OpenMP offloading mode with NVPTX target, forward
5706       // cuda-parallel-target-regions flag
5707       if (Args.hasFlag(options::OPT_fopenmp_cuda_parallel_target_regions,
5708                        options::OPT_fno_openmp_cuda_parallel_target_regions,
5709                        /*Default=*/true))
5710         CmdArgs.push_back("-fopenmp-cuda-parallel-target-regions");
5711 
5712       // When in OpenMP offloading mode with NVPTX target, check if full runtime
5713       // is required.
5714       if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
5715                        options::OPT_fno_openmp_cuda_force_full_runtime,
5716                        /*Default=*/false))
5717         CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
5718       break;
5719     default:
5720       // By default, if Clang doesn't know how to generate useful OpenMP code
5721       // for a specific runtime library, we just don't pass the '-fopenmp' flag
5722       // down to the actual compilation.
5723       // FIXME: It would be better to have a mode which *only* omits IR
5724       // generation based on the OpenMP support so that we get consistent
5725       // semantic analysis, etc.
5726       break;
5727     }
5728   } else {
5729     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
5730                     options::OPT_fno_openmp_simd);
5731     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5732   }
5733 
5734   const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
5735   Sanitize.addArgs(TC, Args, CmdArgs, InputType);
5736 
5737   const XRayArgs &XRay = TC.getXRayArgs();
5738   XRay.addArgs(TC, Args, CmdArgs, InputType);
5739 
5740   for (const auto &Filename :
5741        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
5742     if (D.getVFS().exists(Filename))
5743       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
5744     else
5745       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
5746   }
5747 
5748   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
5749     StringRef S0 = A->getValue(), S = S0;
5750     unsigned Size, Offset = 0;
5751     if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
5752       D.Diag(diag::err_drv_unsupported_opt_for_target)
5753           << A->getAsString(Args) << TripleStr;
5754     else if (S.consumeInteger(10, Size) ||
5755              (!S.empty() && (!S.consume_front(",") ||
5756                              S.consumeInteger(10, Offset) || !S.empty())))
5757       D.Diag(diag::err_drv_invalid_argument_to_option)
5758           << S0 << A->getOption().getName();
5759     else if (Size < Offset)
5760       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
5761     else {
5762       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
5763       CmdArgs.push_back(Args.MakeArgString(
5764           "-fpatchable-function-entry-offset=" + Twine(Offset)));
5765     }
5766   }
5767 
5768   if (TC.SupportsProfiling()) {
5769     Args.AddLastArg(CmdArgs, options::OPT_pg);
5770 
5771     llvm::Triple::ArchType Arch = TC.getArch();
5772     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
5773       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
5774         A->render(Args, CmdArgs);
5775       else
5776         D.Diag(diag::err_drv_unsupported_opt_for_target)
5777             << A->getAsString(Args) << TripleStr;
5778     }
5779     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
5780       if (Arch == llvm::Triple::systemz)
5781         A->render(Args, CmdArgs);
5782       else
5783         D.Diag(diag::err_drv_unsupported_opt_for_target)
5784             << A->getAsString(Args) << TripleStr;
5785     }
5786     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
5787       if (Arch == llvm::Triple::systemz)
5788         A->render(Args, CmdArgs);
5789       else
5790         D.Diag(diag::err_drv_unsupported_opt_for_target)
5791             << A->getAsString(Args) << TripleStr;
5792     }
5793   }
5794 
5795   if (Args.getLastArg(options::OPT_fapple_kext) ||
5796       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5797     CmdArgs.push_back("-fapple-kext");
5798 
5799   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
5800   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5801   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5802   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5803   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5804   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
5805   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
5806   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
5807   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5808   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
5809   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
5810 
5811   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5812     CmdArgs.push_back("-ftrapv-handler");
5813     CmdArgs.push_back(A->getValue());
5814   }
5815 
5816   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5817 
5818   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5819   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5820   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5821     if (A->getOption().matches(options::OPT_fwrapv))
5822       CmdArgs.push_back("-fwrapv");
5823   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5824                                       options::OPT_fno_strict_overflow)) {
5825     if (A->getOption().matches(options::OPT_fno_strict_overflow))
5826       CmdArgs.push_back("-fwrapv");
5827   }
5828 
5829   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5830                                options::OPT_fno_reroll_loops))
5831     if (A->getOption().matches(options::OPT_freroll_loops))
5832       CmdArgs.push_back("-freroll-loops");
5833 
5834   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
5835                   options::OPT_fno_finite_loops);
5836 
5837   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5838   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5839                   options::OPT_fno_unroll_loops);
5840 
5841   Args.AddLastArg(CmdArgs, options::OPT_pthread);
5842 
5843   if (Args.hasFlag(options::OPT_mspeculative_load_hardening,
5844                    options::OPT_mno_speculative_load_hardening, false))
5845     CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
5846 
5847   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
5848   RenderSCPOptions(TC, Args, CmdArgs);
5849   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
5850 
5851   // Translate -mstackrealign
5852   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5853                    false))
5854     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5855 
5856   if (Args.hasArg(options::OPT_mstack_alignment)) {
5857     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5858     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5859   }
5860 
5861   if (Args.hasArg(options::OPT_mstack_probe_size)) {
5862     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5863 
5864     if (!Size.empty())
5865       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5866     else
5867       CmdArgs.push_back("-mstack-probe-size=0");
5868   }
5869 
5870   if (!Args.hasFlag(options::OPT_mstack_arg_probe,
5871                     options::OPT_mno_stack_arg_probe, true))
5872     CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
5873 
5874   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5875                                options::OPT_mno_restrict_it)) {
5876     if (A->getOption().matches(options::OPT_mrestrict_it)) {
5877       CmdArgs.push_back("-mllvm");
5878       CmdArgs.push_back("-arm-restrict-it");
5879     } else {
5880       CmdArgs.push_back("-mllvm");
5881       CmdArgs.push_back("-arm-no-restrict-it");
5882     }
5883   } else if (Triple.isOSWindows() &&
5884              (Triple.getArch() == llvm::Triple::arm ||
5885               Triple.getArch() == llvm::Triple::thumb)) {
5886     // Windows on ARM expects restricted IT blocks
5887     CmdArgs.push_back("-mllvm");
5888     CmdArgs.push_back("-arm-restrict-it");
5889   }
5890 
5891   // Forward -cl options to -cc1
5892   RenderOpenCLOptions(Args, CmdArgs, InputType);
5893 
5894   if (IsHIP) {
5895     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
5896                      options::OPT_fno_hip_new_launch_api, true))
5897       CmdArgs.push_back("-fhip-new-launch-api");
5898     if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
5899                      options::OPT_fno_gpu_allow_device_init, false))
5900       CmdArgs.push_back("-fgpu-allow-device-init");
5901   }
5902 
5903   if (IsCuda || IsHIP) {
5904     if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5905       CmdArgs.push_back("-fgpu-rdc");
5906     if (Args.hasFlag(options::OPT_fgpu_defer_diag,
5907                      options::OPT_fno_gpu_defer_diag, false))
5908       CmdArgs.push_back("-fgpu-defer-diag");
5909     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
5910                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
5911                      false)) {
5912       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
5913       CmdArgs.push_back("-fgpu-defer-diag");
5914     }
5915   }
5916 
5917   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
5918     CmdArgs.push_back(
5919         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
5920   }
5921 
5922   // Forward -f options with positive and negative forms; we translate these by
5923   // hand.  Do not propagate PGO options to the GPU-side compilations as the
5924   // profile info is for the host-side compilation only.
5925   if (!(IsCudaDevice || IsHIPDevice)) {
5926     if (Arg *A = getLastProfileSampleUseArg(Args)) {
5927       auto *PGOArg = Args.getLastArg(
5928           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
5929           options::OPT_fcs_profile_generate,
5930           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
5931           options::OPT_fprofile_use_EQ);
5932       if (PGOArg)
5933         D.Diag(diag::err_drv_argument_not_allowed_with)
5934             << "SampleUse with PGO options";
5935 
5936       StringRef fname = A->getValue();
5937       if (!llvm::sys::fs::exists(fname))
5938         D.Diag(diag::err_drv_no_such_file) << fname;
5939       else
5940         A->render(Args, CmdArgs);
5941     }
5942     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
5943 
5944     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
5945                      options::OPT_fno_pseudo_probe_for_profiling, false))
5946       CmdArgs.push_back("-fpseudo-probe-for-profiling");
5947   }
5948   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
5949 
5950   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5951                     options::OPT_fno_assume_sane_operator_new))
5952     CmdArgs.push_back("-fno-assume-sane-operator-new");
5953 
5954   // -fblocks=0 is default.
5955   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5956                    TC.IsBlocksDefault()) ||
5957       (Args.hasArg(options::OPT_fgnu_runtime) &&
5958        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5959        !Args.hasArg(options::OPT_fno_blocks))) {
5960     CmdArgs.push_back("-fblocks");
5961 
5962     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
5963       CmdArgs.push_back("-fblocks-runtime-optional");
5964   }
5965 
5966   // -fencode-extended-block-signature=1 is default.
5967   if (TC.IsEncodeExtendedBlockSignatureDefault())
5968     CmdArgs.push_back("-fencode-extended-block-signature");
5969 
5970   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
5971                    false) &&
5972       types::isCXX(InputType)) {
5973     CmdArgs.push_back("-fcoroutines-ts");
5974   }
5975 
5976   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
5977                   options::OPT_fno_double_square_bracket_attributes);
5978 
5979   // -faccess-control is default.
5980   if (Args.hasFlag(options::OPT_fno_access_control,
5981                    options::OPT_faccess_control, false))
5982     CmdArgs.push_back("-fno-access-control");
5983 
5984   // -felide-constructors is the default.
5985   if (Args.hasFlag(options::OPT_fno_elide_constructors,
5986                    options::OPT_felide_constructors, false))
5987     CmdArgs.push_back("-fno-elide-constructors");
5988 
5989   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
5990 
5991   if (KernelOrKext || (types::isCXX(InputType) &&
5992                        (RTTIMode == ToolChain::RM_Disabled)))
5993     CmdArgs.push_back("-fno-rtti");
5994 
5995   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
5996   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5997                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
5998     CmdArgs.push_back("-fshort-enums");
5999 
6000   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6001 
6002   // -fuse-cxa-atexit is default.
6003   if (!Args.hasFlag(
6004           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6005           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6006               TC.getArch() != llvm::Triple::xcore &&
6007               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6008                RawTriple.hasEnvironment())) ||
6009       KernelOrKext)
6010     CmdArgs.push_back("-fno-use-cxa-atexit");
6011 
6012   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6013                    options::OPT_fno_register_global_dtors_with_atexit,
6014                    RawTriple.isOSDarwin() && !KernelOrKext))
6015     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6016 
6017   // -fno-use-line-directives is default.
6018   if (Args.hasFlag(options::OPT_fuse_line_directives,
6019                    options::OPT_fno_use_line_directives, false))
6020     CmdArgs.push_back("-fuse-line-directives");
6021 
6022   // -fms-extensions=0 is default.
6023   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6024                    IsWindowsMSVC))
6025     CmdArgs.push_back("-fms-extensions");
6026 
6027   // -fms-compatibility=0 is default.
6028   bool IsMSVCCompat = Args.hasFlag(
6029       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6030       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6031                                      options::OPT_fno_ms_extensions, true)));
6032   if (IsMSVCCompat)
6033     CmdArgs.push_back("-fms-compatibility");
6034 
6035   // Handle -fgcc-version, if present.
6036   VersionTuple GNUCVer;
6037   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6038     // Check that the version has 1 to 3 components and the minor and patch
6039     // versions fit in two decimal digits.
6040     StringRef Val = A->getValue();
6041     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6042     bool Invalid = GNUCVer.tryParse(Val);
6043     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
6044     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
6045     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6046       D.Diag(diag::err_drv_invalid_value)
6047           << A->getAsString(Args) << A->getValue();
6048     }
6049   } else if (!IsMSVCCompat) {
6050     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6051     GNUCVer = VersionTuple(4, 2, 1);
6052   }
6053   if (!GNUCVer.empty()) {
6054     CmdArgs.push_back(
6055         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6056   }
6057 
6058   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6059   if (!MSVT.empty())
6060     CmdArgs.push_back(
6061         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6062 
6063   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6064   if (ImplyVCPPCVer) {
6065     StringRef LanguageStandard;
6066     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6067       Std = StdArg;
6068       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6069                              .Case("c11", "-std=c11")
6070                              .Case("c17", "-std=c17")
6071                              .Default("");
6072       if (LanguageStandard.empty())
6073         D.Diag(clang::diag::warn_drv_unused_argument)
6074             << StdArg->getAsString(Args);
6075     }
6076     CmdArgs.push_back(LanguageStandard.data());
6077   }
6078   if (ImplyVCPPCXXVer) {
6079     StringRef LanguageStandard;
6080     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6081       Std = StdArg;
6082       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6083                              .Case("c++14", "-std=c++14")
6084                              .Case("c++17", "-std=c++17")
6085                              .Case("c++latest", "-std=c++20")
6086                              .Default("");
6087       if (LanguageStandard.empty())
6088         D.Diag(clang::diag::warn_drv_unused_argument)
6089             << StdArg->getAsString(Args);
6090     }
6091 
6092     if (LanguageStandard.empty()) {
6093       if (IsMSVC2015Compatible)
6094         LanguageStandard = "-std=c++14";
6095       else
6096         LanguageStandard = "-std=c++11";
6097     }
6098 
6099     CmdArgs.push_back(LanguageStandard.data());
6100   }
6101 
6102   // -fno-borland-extensions is default.
6103   if (Args.hasFlag(options::OPT_fborland_extensions,
6104                    options::OPT_fno_borland_extensions, false))
6105     CmdArgs.push_back("-fborland-extensions");
6106 
6107   // -fno-declspec is default, except for PS4.
6108   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6109                    RawTriple.isPS4()))
6110     CmdArgs.push_back("-fdeclspec");
6111   else if (Args.hasArg(options::OPT_fno_declspec))
6112     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6113 
6114   // -fthreadsafe-static is default, except for MSVC compatibility versions less
6115   // than 19.
6116   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6117                     options::OPT_fno_threadsafe_statics,
6118                     !IsWindowsMSVC || IsMSVC2015Compatible))
6119     CmdArgs.push_back("-fno-threadsafe-statics");
6120 
6121   // -fno-delayed-template-parsing is default, except when targeting MSVC.
6122   // Many old Windows SDK versions require this to parse.
6123   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6124   // compiler. We should be able to disable this by default at some point.
6125   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6126                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6127     CmdArgs.push_back("-fdelayed-template-parsing");
6128 
6129   // -fgnu-keywords default varies depending on language; only pass if
6130   // specified.
6131   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6132                   options::OPT_fno_gnu_keywords);
6133 
6134   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
6135                    false))
6136     CmdArgs.push_back("-fgnu89-inline");
6137 
6138   if (Args.hasArg(options::OPT_fno_inline))
6139     CmdArgs.push_back("-fno-inline");
6140 
6141   Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
6142                   options::OPT_finline_hint_functions,
6143                   options::OPT_fno_inline_functions);
6144 
6145   // FIXME: Find a better way to determine whether the language has modules
6146   // support by default, or just assume that all languages do.
6147   bool HaveModules =
6148       Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") ||
6149               Std->containsValue("c++latest"));
6150   RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
6151 
6152   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6153                    options::OPT_fno_pch_validate_input_files_content, false))
6154     CmdArgs.push_back("-fvalidate-ast-input-files-content");
6155   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6156                    options::OPT_fno_pch_instantiate_templates, false))
6157     CmdArgs.push_back("-fpch-instantiate-templates");
6158   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6159                    false))
6160     CmdArgs.push_back("-fmodules-codegen");
6161   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6162                    false))
6163     CmdArgs.push_back("-fmodules-debuginfo");
6164 
6165   Args.AddLastArg(CmdArgs, options::OPT_flegacy_pass_manager,
6166                   options::OPT_fno_legacy_pass_manager);
6167 
6168   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6169   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6170                     Input, CmdArgs);
6171 
6172   if (types::isObjC(Input.getType()) &&
6173       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6174                    options::OPT_fno_objc_encode_cxx_class_template_spec,
6175                    !Runtime.isNeXTFamily()))
6176     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6177 
6178   if (Args.hasFlag(options::OPT_fapplication_extension,
6179                    options::OPT_fno_application_extension, false))
6180     CmdArgs.push_back("-fapplication-extension");
6181 
6182   // Handle GCC-style exception args.
6183   bool EH = false;
6184   if (!C.getDriver().IsCLMode())
6185     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6186 
6187   // Handle exception personalities
6188   Arg *A = Args.getLastArg(
6189       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6190       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6191   if (A) {
6192     const Option &Opt = A->getOption();
6193     if (Opt.matches(options::OPT_fsjlj_exceptions))
6194       CmdArgs.push_back("-exception-model=sjlj");
6195     if (Opt.matches(options::OPT_fseh_exceptions))
6196       CmdArgs.push_back("-exception-model=seh");
6197     if (Opt.matches(options::OPT_fdwarf_exceptions))
6198       CmdArgs.push_back("-exception-model=dwarf");
6199     if (Opt.matches(options::OPT_fwasm_exceptions))
6200       CmdArgs.push_back("-exception-model=wasm");
6201   } else {
6202     switch (TC.GetExceptionModel(Args)) {
6203     default:
6204       break;
6205     case llvm::ExceptionHandling::DwarfCFI:
6206       CmdArgs.push_back("-exception-model=dwarf");
6207       break;
6208     case llvm::ExceptionHandling::SjLj:
6209       CmdArgs.push_back("-exception-model=sjlj");
6210       break;
6211     case llvm::ExceptionHandling::WinEH:
6212       CmdArgs.push_back("-exception-model=seh");
6213       break;
6214     }
6215   }
6216 
6217   // C++ "sane" operator new.
6218   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
6219                     options::OPT_fno_assume_sane_operator_new))
6220     CmdArgs.push_back("-fno-assume-sane-operator-new");
6221 
6222   // -frelaxed-template-template-args is off by default, as it is a severe
6223   // breaking change until a corresponding change to template partial ordering
6224   // is provided.
6225   if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
6226                    options::OPT_fno_relaxed_template_template_args, false))
6227     CmdArgs.push_back("-frelaxed-template-template-args");
6228 
6229   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6230   // most platforms.
6231   if (Args.hasFlag(options::OPT_fsized_deallocation,
6232                    options::OPT_fno_sized_deallocation, false))
6233     CmdArgs.push_back("-fsized-deallocation");
6234 
6235   // -faligned-allocation is on by default in C++17 onwards and otherwise off
6236   // by default.
6237   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6238                                options::OPT_fno_aligned_allocation,
6239                                options::OPT_faligned_new_EQ)) {
6240     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6241       CmdArgs.push_back("-fno-aligned-allocation");
6242     else
6243       CmdArgs.push_back("-faligned-allocation");
6244   }
6245 
6246   // The default new alignment can be specified using a dedicated option or via
6247   // a GCC-compatible option that also turns on aligned allocation.
6248   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6249                                options::OPT_faligned_new_EQ))
6250     CmdArgs.push_back(
6251         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6252 
6253   // -fconstant-cfstrings is default, and may be subject to argument translation
6254   // on Darwin.
6255   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6256                     options::OPT_fno_constant_cfstrings) ||
6257       !Args.hasFlag(options::OPT_mconstant_cfstrings,
6258                     options::OPT_mno_constant_cfstrings))
6259     CmdArgs.push_back("-fno-constant-cfstrings");
6260 
6261   // -fno-pascal-strings is default, only pass non-default.
6262   if (Args.hasFlag(options::OPT_fpascal_strings,
6263                    options::OPT_fno_pascal_strings, false))
6264     CmdArgs.push_back("-fpascal-strings");
6265 
6266   // Honor -fpack-struct= and -fpack-struct, if given. Note that
6267   // -fno-pack-struct doesn't apply to -fpack-struct=.
6268   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6269     std::string PackStructStr = "-fpack-struct=";
6270     PackStructStr += A->getValue();
6271     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6272   } else if (Args.hasFlag(options::OPT_fpack_struct,
6273                           options::OPT_fno_pack_struct, false)) {
6274     CmdArgs.push_back("-fpack-struct=1");
6275   }
6276 
6277   // Handle -fmax-type-align=N and -fno-type-align
6278   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6279   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6280     if (!SkipMaxTypeAlign) {
6281       std::string MaxTypeAlignStr = "-fmax-type-align=";
6282       MaxTypeAlignStr += A->getValue();
6283       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6284     }
6285   } else if (RawTriple.isOSDarwin()) {
6286     if (!SkipMaxTypeAlign) {
6287       std::string MaxTypeAlignStr = "-fmax-type-align=16";
6288       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6289     }
6290   }
6291 
6292   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6293     CmdArgs.push_back("-Qn");
6294 
6295   // -fno-common is the default, set -fcommon only when that flag is set.
6296   if (Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common, false))
6297     CmdArgs.push_back("-fcommon");
6298 
6299   // -fsigned-bitfields is default, and clang doesn't yet support
6300   // -funsigned-bitfields.
6301   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6302                     options::OPT_funsigned_bitfields))
6303     D.Diag(diag::warn_drv_clang_unsupported)
6304         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6305 
6306   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6307   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
6308     D.Diag(diag::err_drv_clang_unsupported)
6309         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6310 
6311   // -finput_charset=UTF-8 is default. Reject others
6312   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6313     StringRef value = inputCharset->getValue();
6314     if (!value.equals_lower("utf-8"))
6315       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6316                                           << value;
6317   }
6318 
6319   // -fexec_charset=UTF-8 is default. Reject others
6320   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6321     StringRef value = execCharset->getValue();
6322     if (!value.equals_lower("utf-8"))
6323       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6324                                           << value;
6325   }
6326 
6327   RenderDiagnosticsOptions(D, Args, CmdArgs);
6328 
6329   // -fno-asm-blocks is default.
6330   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
6331                    false))
6332     CmdArgs.push_back("-fasm-blocks");
6333 
6334   // -fgnu-inline-asm is default.
6335   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
6336                     options::OPT_fno_gnu_inline_asm, true))
6337     CmdArgs.push_back("-fno-gnu-inline-asm");
6338 
6339   // Enable vectorization per default according to the optimization level
6340   // selected. For optimization levels that want vectorization we use the alias
6341   // option to simplify the hasFlag logic.
6342   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
6343   OptSpecifier VectorizeAliasOption =
6344       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
6345   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
6346                    options::OPT_fno_vectorize, EnableVec))
6347     CmdArgs.push_back("-vectorize-loops");
6348 
6349   // -fslp-vectorize is enabled based on the optimization level selected.
6350   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
6351   OptSpecifier SLPVectAliasOption =
6352       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
6353   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
6354                    options::OPT_fno_slp_vectorize, EnableSLPVec))
6355     CmdArgs.push_back("-vectorize-slp");
6356 
6357   ParseMPreferVectorWidth(D, Args, CmdArgs);
6358 
6359   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
6360   Args.AddLastArg(CmdArgs,
6361                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
6362 
6363   // -fdollars-in-identifiers default varies depending on platform and
6364   // language; only pass if specified.
6365   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
6366                                options::OPT_fno_dollars_in_identifiers)) {
6367     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
6368       CmdArgs.push_back("-fdollars-in-identifiers");
6369     else
6370       CmdArgs.push_back("-fno-dollars-in-identifiers");
6371   }
6372 
6373   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
6374   // practical purposes.
6375   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
6376                                options::OPT_fno_unit_at_a_time)) {
6377     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
6378       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
6379   }
6380 
6381   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
6382                    options::OPT_fno_apple_pragma_pack, false))
6383     CmdArgs.push_back("-fapple-pragma-pack");
6384 
6385   if (Args.hasFlag(options::OPT_fxl_pragma_pack,
6386                    options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
6387     CmdArgs.push_back("-fxl-pragma-pack");
6388 
6389   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
6390   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
6391     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
6392 
6393   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
6394                                      options::OPT_fno_rewrite_imports, false);
6395   if (RewriteImports)
6396     CmdArgs.push_back("-frewrite-imports");
6397 
6398   // Enable rewrite includes if the user's asked for it or if we're generating
6399   // diagnostics.
6400   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
6401   // nice to enable this when doing a crashdump for modules as well.
6402   if (Args.hasFlag(options::OPT_frewrite_includes,
6403                    options::OPT_fno_rewrite_includes, false) ||
6404       (C.isForDiagnostics() && !HaveModules))
6405     CmdArgs.push_back("-frewrite-includes");
6406 
6407   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
6408   if (Arg *A = Args.getLastArg(options::OPT_traditional,
6409                                options::OPT_traditional_cpp)) {
6410     if (isa<PreprocessJobAction>(JA))
6411       CmdArgs.push_back("-traditional-cpp");
6412     else
6413       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
6414   }
6415 
6416   Args.AddLastArg(CmdArgs, options::OPT_dM);
6417   Args.AddLastArg(CmdArgs, options::OPT_dD);
6418 
6419   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
6420 
6421   // Handle serialized diagnostics.
6422   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
6423     CmdArgs.push_back("-serialize-diagnostic-file");
6424     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
6425   }
6426 
6427   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
6428     CmdArgs.push_back("-fretain-comments-from-system-headers");
6429 
6430   // Forward -fcomment-block-commands to -cc1.
6431   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
6432   // Forward -fparse-all-comments to -cc1.
6433   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
6434 
6435   // Turn -fplugin=name.so into -load name.so
6436   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
6437     CmdArgs.push_back("-load");
6438     CmdArgs.push_back(A->getValue());
6439     A->claim();
6440   }
6441 
6442   // Forward -fpass-plugin=name.so to -cc1.
6443   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
6444     CmdArgs.push_back(
6445         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
6446     A->claim();
6447   }
6448 
6449   // Setup statistics file output.
6450   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
6451   if (!StatsFile.empty())
6452     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
6453 
6454   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
6455   // parser.
6456   // -finclude-default-header flag is for preprocessor,
6457   // do not pass it to other cc1 commands when save-temps is enabled
6458   if (C.getDriver().isSaveTempsEnabled() &&
6459       !isa<PreprocessJobAction>(JA)) {
6460     for (auto Arg : Args.filtered(options::OPT_Xclang)) {
6461       Arg->claim();
6462       if (StringRef(Arg->getValue()) != "-finclude-default-header")
6463         CmdArgs.push_back(Arg->getValue());
6464     }
6465   }
6466   else {
6467     Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
6468   }
6469   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
6470     A->claim();
6471 
6472     // We translate this by hand to the -cc1 argument, since nightly test uses
6473     // it and developers have been trained to spell it with -mllvm. Both
6474     // spellings are now deprecated and should be removed.
6475     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
6476       CmdArgs.push_back("-disable-llvm-optzns");
6477     } else {
6478       A->render(Args, CmdArgs);
6479     }
6480   }
6481 
6482   // With -save-temps, we want to save the unoptimized bitcode output from the
6483   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
6484   // by the frontend.
6485   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
6486   // has slightly different breakdown between stages.
6487   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
6488   // pristine IR generated by the frontend. Ideally, a new compile action should
6489   // be added so both IR can be captured.
6490   if ((C.getDriver().isSaveTempsEnabled() ||
6491        JA.isHostOffloading(Action::OFK_OpenMP)) &&
6492       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
6493       isa<CompileJobAction>(JA))
6494     CmdArgs.push_back("-disable-llvm-passes");
6495 
6496   Args.AddAllArgs(CmdArgs, options::OPT_undef);
6497 
6498   const char *Exec = D.getClangProgramPath();
6499 
6500   // Optionally embed the -cc1 level arguments into the debug info or a
6501   // section, for build analysis.
6502   // Also record command line arguments into the debug info if
6503   // -grecord-gcc-switches options is set on.
6504   // By default, -gno-record-gcc-switches is set on and no recording.
6505   auto GRecordSwitches =
6506       Args.hasFlag(options::OPT_grecord_command_line,
6507                    options::OPT_gno_record_command_line, false);
6508   auto FRecordSwitches =
6509       Args.hasFlag(options::OPT_frecord_command_line,
6510                    options::OPT_fno_record_command_line, false);
6511   if (FRecordSwitches && !Triple.isOSBinFormatELF())
6512     D.Diag(diag::err_drv_unsupported_opt_for_target)
6513         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
6514         << TripleStr;
6515   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
6516     ArgStringList OriginalArgs;
6517     for (const auto &Arg : Args)
6518       Arg->render(Args, OriginalArgs);
6519 
6520     SmallString<256> Flags;
6521     EscapeSpacesAndBackslashes(Exec, Flags);
6522     for (const char *OriginalArg : OriginalArgs) {
6523       SmallString<128> EscapedArg;
6524       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6525       Flags += " ";
6526       Flags += EscapedArg;
6527     }
6528     auto FlagsArgString = Args.MakeArgString(Flags);
6529     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
6530       CmdArgs.push_back("-dwarf-debug-flags");
6531       CmdArgs.push_back(FlagsArgString);
6532     }
6533     if (FRecordSwitches) {
6534       CmdArgs.push_back("-record-command-line");
6535       CmdArgs.push_back(FlagsArgString);
6536     }
6537   }
6538 
6539   // Host-side cuda compilation receives all device-side outputs in a single
6540   // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
6541   if ((IsCuda || IsHIP) && CudaDeviceInput) {
6542       CmdArgs.push_back("-fcuda-include-gpubinary");
6543       CmdArgs.push_back(CudaDeviceInput->getFilename());
6544       if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
6545         CmdArgs.push_back("-fgpu-rdc");
6546   }
6547 
6548   if (IsCuda) {
6549     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
6550                      options::OPT_fno_cuda_short_ptr, false))
6551       CmdArgs.push_back("-fcuda-short-ptr");
6552   }
6553 
6554   if (IsCuda || IsHIP) {
6555     // Determine the original source input.
6556     const Action *SourceAction = &JA;
6557     while (SourceAction->getKind() != Action::InputClass) {
6558       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6559       SourceAction = SourceAction->getInputs()[0];
6560     }
6561     auto CUID = cast<InputAction>(SourceAction)->getId();
6562     if (!CUID.empty())
6563       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
6564   }
6565 
6566   if (IsHIP)
6567     CmdArgs.push_back("-fcuda-allow-variadic-functions");
6568 
6569   if (IsCudaDevice || IsHIPDevice) {
6570     StringRef InlineThresh =
6571         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
6572     if (!InlineThresh.empty()) {
6573       std::string ArgStr =
6574           std::string("-inline-threshold=") + InlineThresh.str();
6575       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
6576     }
6577   }
6578 
6579   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
6580   // to specify the result of the compile phase on the host, so the meaningful
6581   // device declarations can be identified. Also, -fopenmp-is-device is passed
6582   // along to tell the frontend that it is generating code for a device, so that
6583   // only the relevant declarations are emitted.
6584   if (IsOpenMPDevice) {
6585     CmdArgs.push_back("-fopenmp-is-device");
6586     if (OpenMPDeviceInput) {
6587       CmdArgs.push_back("-fopenmp-host-ir-file-path");
6588       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
6589     }
6590   }
6591 
6592   if (Triple.isAMDGPU()) {
6593     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
6594 
6595     if (Args.hasFlag(options::OPT_munsafe_fp_atomics,
6596                      options::OPT_mno_unsafe_fp_atomics, /*Default=*/false))
6597       CmdArgs.push_back("-munsafe-fp-atomics");
6598   }
6599 
6600   // For all the host OpenMP offloading compile jobs we need to pass the targets
6601   // information using -fopenmp-targets= option.
6602   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
6603     SmallString<128> TargetInfo("-fopenmp-targets=");
6604 
6605     Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
6606     assert(Tgts && Tgts->getNumValues() &&
6607            "OpenMP offloading has to have targets specified.");
6608     for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
6609       if (i)
6610         TargetInfo += ',';
6611       // We need to get the string from the triple because it may be not exactly
6612       // the same as the one we get directly from the arguments.
6613       llvm::Triple T(Tgts->getValue(i));
6614       TargetInfo += T.getTriple();
6615     }
6616     CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
6617   }
6618 
6619   bool VirtualFunctionElimination =
6620       Args.hasFlag(options::OPT_fvirtual_function_elimination,
6621                    options::OPT_fno_virtual_function_elimination, false);
6622   if (VirtualFunctionElimination) {
6623     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
6624     // in the future).
6625     if (LTOMode != LTOK_Full)
6626       D.Diag(diag::err_drv_argument_only_allowed_with)
6627           << "-fvirtual-function-elimination"
6628           << "-flto=full";
6629 
6630     CmdArgs.push_back("-fvirtual-function-elimination");
6631   }
6632 
6633   // VFE requires whole-program-vtables, and enables it by default.
6634   bool WholeProgramVTables = Args.hasFlag(
6635       options::OPT_fwhole_program_vtables,
6636       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
6637   if (VirtualFunctionElimination && !WholeProgramVTables) {
6638     D.Diag(diag::err_drv_argument_not_allowed_with)
6639         << "-fno-whole-program-vtables"
6640         << "-fvirtual-function-elimination";
6641   }
6642 
6643   if (WholeProgramVTables) {
6644     if (!IsUsingLTO)
6645       D.Diag(diag::err_drv_argument_only_allowed_with)
6646           << "-fwhole-program-vtables"
6647           << "-flto";
6648     CmdArgs.push_back("-fwhole-program-vtables");
6649   }
6650 
6651   bool DefaultsSplitLTOUnit =
6652       (WholeProgramVTables || Sanitize.needsLTO()) &&
6653       (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
6654   bool SplitLTOUnit =
6655       Args.hasFlag(options::OPT_fsplit_lto_unit,
6656                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
6657   if (Sanitize.needsLTO() && !SplitLTOUnit)
6658     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
6659                                                     << "-fsanitize=cfi";
6660   if (SplitLTOUnit)
6661     CmdArgs.push_back("-fsplit-lto-unit");
6662 
6663   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
6664                                options::OPT_fno_global_isel)) {
6665     CmdArgs.push_back("-mllvm");
6666     if (A->getOption().matches(options::OPT_fglobal_isel)) {
6667       CmdArgs.push_back("-global-isel=1");
6668 
6669       // GISel is on by default on AArch64 -O0, so don't bother adding
6670       // the fallback remarks for it. Other combinations will add a warning of
6671       // some kind.
6672       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
6673       bool IsOptLevelSupported = false;
6674 
6675       Arg *A = Args.getLastArg(options::OPT_O_Group);
6676       if (Triple.getArch() == llvm::Triple::aarch64) {
6677         if (!A || A->getOption().matches(options::OPT_O0))
6678           IsOptLevelSupported = true;
6679       }
6680       if (!IsArchSupported || !IsOptLevelSupported) {
6681         CmdArgs.push_back("-mllvm");
6682         CmdArgs.push_back("-global-isel-abort=2");
6683 
6684         if (!IsArchSupported)
6685           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
6686         else
6687           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
6688       }
6689     } else {
6690       CmdArgs.push_back("-global-isel=0");
6691     }
6692   }
6693 
6694   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
6695      CmdArgs.push_back("-forder-file-instrumentation");
6696      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
6697      // on, we need to pass these flags as linker flags and that will be handled
6698      // outside of the compiler.
6699      if (!IsUsingLTO) {
6700        CmdArgs.push_back("-mllvm");
6701        CmdArgs.push_back("-enable-order-file-instrumentation");
6702      }
6703   }
6704 
6705   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
6706                                options::OPT_fno_force_enable_int128)) {
6707     if (A->getOption().matches(options::OPT_fforce_enable_int128))
6708       CmdArgs.push_back("-fforce-enable-int128");
6709   }
6710 
6711   if (Args.hasFlag(options::OPT_fkeep_static_consts,
6712                    options::OPT_fno_keep_static_consts, false))
6713     CmdArgs.push_back("-fkeep-static-consts");
6714 
6715   if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
6716                    options::OPT_fno_complete_member_pointers, false))
6717     CmdArgs.push_back("-fcomplete-member-pointers");
6718 
6719   if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
6720                     options::OPT_fno_cxx_static_destructors, true))
6721     CmdArgs.push_back("-fno-c++-static-destructors");
6722 
6723   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
6724 
6725   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
6726                                options::OPT_mno_outline_atomics)) {
6727     if (A->getOption().matches(options::OPT_moutline_atomics)) {
6728       // Option -moutline-atomics supported for AArch64 target only.
6729       if (!Triple.isAArch64()) {
6730         D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
6731             << Triple.getArchName();
6732       } else {
6733         CmdArgs.push_back("-target-feature");
6734         CmdArgs.push_back("+outline-atomics");
6735       }
6736     } else {
6737       CmdArgs.push_back("-target-feature");
6738       CmdArgs.push_back("-outline-atomics");
6739     }
6740   } else if (Triple.isAArch64() &&
6741              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
6742     CmdArgs.push_back("-target-feature");
6743     CmdArgs.push_back("+outline-atomics");
6744   }
6745 
6746   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
6747                    (TC.getTriple().isOSBinFormatELF() ||
6748                     TC.getTriple().isOSBinFormatCOFF()) &&
6749                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
6750                        !TC.getTriple().isOSNetBSD() &&
6751                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
6752                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
6753     CmdArgs.push_back("-faddrsig");
6754 
6755   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
6756       (EH || UnwindTables || DebugInfoKind != codegenoptions::NoDebugInfo))
6757     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
6758 
6759   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
6760     std::string Str = A->getAsString(Args);
6761     if (!TC.getTriple().isOSBinFormatELF())
6762       D.Diag(diag::err_drv_unsupported_opt_for_target)
6763           << Str << TC.getTripleString();
6764     CmdArgs.push_back(Args.MakeArgString(Str));
6765   }
6766 
6767   // Add the "-o out -x type src.c" flags last. This is done primarily to make
6768   // the -cc1 command easier to edit when reproducing compiler crashes.
6769   if (Output.getType() == types::TY_Dependencies) {
6770     // Handled with other dependency code.
6771   } else if (Output.isFilename()) {
6772     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
6773         Output.getType() == clang::driver::types::TY_IFS) {
6774       SmallString<128> OutputFilename(Output.getFilename());
6775       llvm::sys::path::replace_extension(OutputFilename, "ifs");
6776       CmdArgs.push_back("-o");
6777       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6778     } else {
6779       CmdArgs.push_back("-o");
6780       CmdArgs.push_back(Output.getFilename());
6781     }
6782   } else {
6783     assert(Output.isNothing() && "Invalid output.");
6784   }
6785 
6786   addDashXForInput(Args, Input, CmdArgs);
6787 
6788   ArrayRef<InputInfo> FrontendInputs = Input;
6789   if (IsHeaderModulePrecompile)
6790     FrontendInputs = ModuleHeaderInputs;
6791   else if (Input.isNothing())
6792     FrontendInputs = {};
6793 
6794   for (const InputInfo &Input : FrontendInputs) {
6795     if (Input.isFilename())
6796       CmdArgs.push_back(Input.getFilename());
6797     else
6798       Input.getInputArg().renderAsInput(Args, CmdArgs);
6799   }
6800 
6801   if (D.CC1Main && !D.CCGenDiagnostics) {
6802     // Invoke the CC1 directly in this process
6803     C.addCommand(std::make_unique<CC1Command>(JA, *this,
6804                                               ResponseFileSupport::AtFileUTF8(),
6805                                               Exec, CmdArgs, Inputs, Output));
6806   } else {
6807     C.addCommand(std::make_unique<Command>(JA, *this,
6808                                            ResponseFileSupport::AtFileUTF8(),
6809                                            Exec, CmdArgs, Inputs, Output));
6810   }
6811 
6812   // Make the compile command echo its inputs for /showFilenames.
6813   if (Output.getType() == types::TY_Object &&
6814       Args.hasFlag(options::OPT__SLASH_showFilenames,
6815                    options::OPT__SLASH_showFilenames_, false)) {
6816     C.getJobs().getJobs().back()->PrintInputFilenames = true;
6817   }
6818 
6819   if (Arg *A = Args.getLastArg(options::OPT_pg))
6820     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
6821         !Args.hasArg(options::OPT_mfentry))
6822       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6823                                                       << A->getAsString(Args);
6824 
6825   // Claim some arguments which clang supports automatically.
6826 
6827   // -fpch-preprocess is used with gcc to add a special marker in the output to
6828   // include the PCH file.
6829   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6830 
6831   // Claim some arguments which clang doesn't support, but we don't
6832   // care to warn the user about.
6833   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6834   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6835 
6836   // Disable warnings for clang -E -emit-llvm foo.c
6837   Args.ClaimAllArgs(options::OPT_emit_llvm);
6838 }
6839 
Clang(const ToolChain & TC)6840 Clang::Clang(const ToolChain &TC)
6841     // CAUTION! The first constructor argument ("clang") is not arbitrary,
6842     // as it is for other tools. Some operations on a Tool actually test
6843     // whether that tool is Clang based on the Tool's Name as a string.
6844     : Tool("clang", "clang frontend", TC) {}
6845 
~Clang()6846 Clang::~Clang() {}
6847 
6848 /// Add options related to the Objective-C runtime/ABI.
6849 ///
6850 /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,const InputInfoList & inputs,ArgStringList & cmdArgs,RewriteKind rewriteKind) const6851 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6852                                       const InputInfoList &inputs,
6853                                       ArgStringList &cmdArgs,
6854                                       RewriteKind rewriteKind) const {
6855   // Look for the controlling runtime option.
6856   Arg *runtimeArg =
6857       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6858                       options::OPT_fobjc_runtime_EQ);
6859 
6860   // Just forward -fobjc-runtime= to the frontend.  This supercedes
6861   // options about fragility.
6862   if (runtimeArg &&
6863       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6864     ObjCRuntime runtime;
6865     StringRef value = runtimeArg->getValue();
6866     if (runtime.tryParse(value)) {
6867       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6868           << value;
6869     }
6870     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
6871         (runtime.getVersion() >= VersionTuple(2, 0)))
6872       if (!getToolChain().getTriple().isOSBinFormatELF() &&
6873           !getToolChain().getTriple().isOSBinFormatCOFF()) {
6874         getToolChain().getDriver().Diag(
6875             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
6876           << runtime.getVersion().getMajor();
6877       }
6878 
6879     runtimeArg->render(args, cmdArgs);
6880     return runtime;
6881   }
6882 
6883   // Otherwise, we'll need the ABI "version".  Version numbers are
6884   // slightly confusing for historical reasons:
6885   //   1 - Traditional "fragile" ABI
6886   //   2 - Non-fragile ABI, version 1
6887   //   3 - Non-fragile ABI, version 2
6888   unsigned objcABIVersion = 1;
6889   // If -fobjc-abi-version= is present, use that to set the version.
6890   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6891     StringRef value = abiArg->getValue();
6892     if (value == "1")
6893       objcABIVersion = 1;
6894     else if (value == "2")
6895       objcABIVersion = 2;
6896     else if (value == "3")
6897       objcABIVersion = 3;
6898     else
6899       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6900   } else {
6901     // Otherwise, determine if we are using the non-fragile ABI.
6902     bool nonFragileABIIsDefault =
6903         (rewriteKind == RK_NonFragile ||
6904          (rewriteKind == RK_None &&
6905           getToolChain().IsObjCNonFragileABIDefault()));
6906     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6907                      options::OPT_fno_objc_nonfragile_abi,
6908                      nonFragileABIIsDefault)) {
6909 // Determine the non-fragile ABI version to use.
6910 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6911       unsigned nonFragileABIVersion = 1;
6912 #else
6913       unsigned nonFragileABIVersion = 2;
6914 #endif
6915 
6916       if (Arg *abiArg =
6917               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6918         StringRef value = abiArg->getValue();
6919         if (value == "1")
6920           nonFragileABIVersion = 1;
6921         else if (value == "2")
6922           nonFragileABIVersion = 2;
6923         else
6924           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6925               << value;
6926       }
6927 
6928       objcABIVersion = 1 + nonFragileABIVersion;
6929     } else {
6930       objcABIVersion = 1;
6931     }
6932   }
6933 
6934   // We don't actually care about the ABI version other than whether
6935   // it's non-fragile.
6936   bool isNonFragile = objcABIVersion != 1;
6937 
6938   // If we have no runtime argument, ask the toolchain for its default runtime.
6939   // However, the rewriter only really supports the Mac runtime, so assume that.
6940   ObjCRuntime runtime;
6941   if (!runtimeArg) {
6942     switch (rewriteKind) {
6943     case RK_None:
6944       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6945       break;
6946     case RK_Fragile:
6947       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6948       break;
6949     case RK_NonFragile:
6950       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6951       break;
6952     }
6953 
6954     // -fnext-runtime
6955   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6956     // On Darwin, make this use the default behavior for the toolchain.
6957     if (getToolChain().getTriple().isOSDarwin()) {
6958       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6959 
6960       // Otherwise, build for a generic macosx port.
6961     } else {
6962       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6963     }
6964 
6965     // -fgnu-runtime
6966   } else {
6967     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6968     // Legacy behaviour is to target the gnustep runtime if we are in
6969     // non-fragile mode or the GCC runtime in fragile mode.
6970     if (isNonFragile)
6971       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
6972     else
6973       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6974   }
6975 
6976   if (llvm::any_of(inputs, [](const InputInfo &input) {
6977         return types::isObjC(input.getType());
6978       }))
6979     cmdArgs.push_back(
6980         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6981   return runtime;
6982 }
6983 
maybeConsumeDash(const std::string & EH,size_t & I)6984 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6985   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6986   I += HaveDash;
6987   return !HaveDash;
6988 }
6989 
6990 namespace {
6991 struct EHFlags {
6992   bool Synch = false;
6993   bool Asynch = false;
6994   bool NoUnwindC = false;
6995 };
6996 } // end anonymous namespace
6997 
6998 /// /EH controls whether to run destructor cleanups when exceptions are
6999 /// thrown.  There are three modifiers:
7000 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7001 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7002 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7003 /// - c: Assume that extern "C" functions are implicitly nounwind.
7004 /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)7005 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7006   EHFlags EH;
7007 
7008   std::vector<std::string> EHArgs =
7009       Args.getAllArgValues(options::OPT__SLASH_EH);
7010   for (auto EHVal : EHArgs) {
7011     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7012       switch (EHVal[I]) {
7013       case 'a':
7014         EH.Asynch = maybeConsumeDash(EHVal, I);
7015         if (EH.Asynch)
7016           EH.Synch = false;
7017         continue;
7018       case 'c':
7019         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7020         continue;
7021       case 's':
7022         EH.Synch = maybeConsumeDash(EHVal, I);
7023         if (EH.Synch)
7024           EH.Asynch = false;
7025         continue;
7026       default:
7027         break;
7028       }
7029       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7030       break;
7031     }
7032   }
7033   // The /GX, /GX- flags are only processed if there are not /EH flags.
7034   // The default is that /GX is not specified.
7035   if (EHArgs.empty() &&
7036       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7037                    /*Default=*/false)) {
7038     EH.Synch = true;
7039     EH.NoUnwindC = true;
7040   }
7041 
7042   return EH;
7043 }
7044 
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind * DebugInfoKind,bool * EmitCodeView) const7045 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7046                            ArgStringList &CmdArgs,
7047                            codegenoptions::DebugInfoKind *DebugInfoKind,
7048                            bool *EmitCodeView) const {
7049   unsigned RTOptionID = options::OPT__SLASH_MT;
7050   bool isNVPTX = getToolChain().getTriple().isNVPTX();
7051 
7052   if (Args.hasArg(options::OPT__SLASH_LDd))
7053     // The /LDd option implies /MTd. The dependent lib part can be overridden,
7054     // but defining _DEBUG is sticky.
7055     RTOptionID = options::OPT__SLASH_MTd;
7056 
7057   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
7058     RTOptionID = A->getOption().getID();
7059 
7060   StringRef FlagForCRT;
7061   switch (RTOptionID) {
7062   case options::OPT__SLASH_MD:
7063     if (Args.hasArg(options::OPT__SLASH_LDd))
7064       CmdArgs.push_back("-D_DEBUG");
7065     CmdArgs.push_back("-D_MT");
7066     CmdArgs.push_back("-D_DLL");
7067     FlagForCRT = "--dependent-lib=msvcrt";
7068     break;
7069   case options::OPT__SLASH_MDd:
7070     CmdArgs.push_back("-D_DEBUG");
7071     CmdArgs.push_back("-D_MT");
7072     CmdArgs.push_back("-D_DLL");
7073     FlagForCRT = "--dependent-lib=msvcrtd";
7074     break;
7075   case options::OPT__SLASH_MT:
7076     if (Args.hasArg(options::OPT__SLASH_LDd))
7077       CmdArgs.push_back("-D_DEBUG");
7078     CmdArgs.push_back("-D_MT");
7079     CmdArgs.push_back("-flto-visibility-public-std");
7080     FlagForCRT = "--dependent-lib=libcmt";
7081     break;
7082   case options::OPT__SLASH_MTd:
7083     CmdArgs.push_back("-D_DEBUG");
7084     CmdArgs.push_back("-D_MT");
7085     CmdArgs.push_back("-flto-visibility-public-std");
7086     FlagForCRT = "--dependent-lib=libcmtd";
7087     break;
7088   default:
7089     llvm_unreachable("Unexpected option ID.");
7090   }
7091 
7092   if (Args.hasArg(options::OPT__SLASH_Zl)) {
7093     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
7094   } else {
7095     CmdArgs.push_back(FlagForCRT.data());
7096 
7097     // This provides POSIX compatibility (maps 'open' to '_open'), which most
7098     // users want.  The /Za flag to cl.exe turns this off, but it's not
7099     // implemented in clang.
7100     CmdArgs.push_back("--dependent-lib=oldnames");
7101   }
7102 
7103   if (Arg *ShowIncludes =
7104           Args.getLastArg(options::OPT__SLASH_showIncludes,
7105                           options::OPT__SLASH_showIncludes_user)) {
7106     CmdArgs.push_back("--show-includes");
7107     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7108       CmdArgs.push_back("-sys-header-deps");
7109   }
7110 
7111   // This controls whether or not we emit RTTI data for polymorphic types.
7112   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7113                    /*Default=*/false))
7114     CmdArgs.push_back("-fno-rtti-data");
7115 
7116   // This controls whether or not we emit stack-protector instrumentation.
7117   // In MSVC, Buffer Security Check (/GS) is on by default.
7118   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7119                                /*Default=*/true)) {
7120     CmdArgs.push_back("-stack-protector");
7121     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7122   }
7123 
7124   // Emit CodeView if -Z7 or -gline-tables-only are present.
7125   if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7126                                           options::OPT_gline_tables_only)) {
7127     *EmitCodeView = true;
7128     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7129       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
7130     else
7131       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
7132   } else {
7133     *EmitCodeView = false;
7134   }
7135 
7136   const Driver &D = getToolChain().getDriver();
7137   EHFlags EH = parseClangCLEHFlags(D, Args);
7138   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7139     if (types::isCXX(InputType))
7140       CmdArgs.push_back("-fcxx-exceptions");
7141     CmdArgs.push_back("-fexceptions");
7142     if (EH.Asynch)
7143       CmdArgs.push_back("-fasync-exceptions");
7144   }
7145   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7146     CmdArgs.push_back("-fexternc-nounwind");
7147 
7148   // /EP should expand to -E -P.
7149   if (Args.hasArg(options::OPT__SLASH_EP)) {
7150     CmdArgs.push_back("-E");
7151     CmdArgs.push_back("-P");
7152   }
7153 
7154   unsigned VolatileOptionID;
7155   if (getToolChain().getTriple().isX86())
7156     VolatileOptionID = options::OPT__SLASH_volatile_ms;
7157   else
7158     VolatileOptionID = options::OPT__SLASH_volatile_iso;
7159 
7160   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7161     VolatileOptionID = A->getOption().getID();
7162 
7163   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7164     CmdArgs.push_back("-fms-volatile");
7165 
7166  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7167                   options::OPT__SLASH_Zc_dllexportInlines,
7168                   false)) {
7169   CmdArgs.push_back("-fno-dllexport-inlines");
7170  }
7171 
7172   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7173   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7174   if (MostGeneralArg && BestCaseArg)
7175     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7176         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7177 
7178   if (MostGeneralArg) {
7179     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7180     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7181     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7182 
7183     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7184     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7185     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7186       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7187           << FirstConflict->getAsString(Args)
7188           << SecondConflict->getAsString(Args);
7189 
7190     if (SingleArg)
7191       CmdArgs.push_back("-fms-memptr-rep=single");
7192     else if (MultipleArg)
7193       CmdArgs.push_back("-fms-memptr-rep=multiple");
7194     else
7195       CmdArgs.push_back("-fms-memptr-rep=virtual");
7196   }
7197 
7198   // Parse the default calling convention options.
7199   if (Arg *CCArg =
7200           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7201                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7202                           options::OPT__SLASH_Gregcall)) {
7203     unsigned DCCOptId = CCArg->getOption().getID();
7204     const char *DCCFlag = nullptr;
7205     bool ArchSupported = !isNVPTX;
7206     llvm::Triple::ArchType Arch = getToolChain().getArch();
7207     switch (DCCOptId) {
7208     case options::OPT__SLASH_Gd:
7209       DCCFlag = "-fdefault-calling-conv=cdecl";
7210       break;
7211     case options::OPT__SLASH_Gr:
7212       ArchSupported = Arch == llvm::Triple::x86;
7213       DCCFlag = "-fdefault-calling-conv=fastcall";
7214       break;
7215     case options::OPT__SLASH_Gz:
7216       ArchSupported = Arch == llvm::Triple::x86;
7217       DCCFlag = "-fdefault-calling-conv=stdcall";
7218       break;
7219     case options::OPT__SLASH_Gv:
7220       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7221       DCCFlag = "-fdefault-calling-conv=vectorcall";
7222       break;
7223     case options::OPT__SLASH_Gregcall:
7224       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7225       DCCFlag = "-fdefault-calling-conv=regcall";
7226       break;
7227     }
7228 
7229     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7230     if (ArchSupported && DCCFlag)
7231       CmdArgs.push_back(DCCFlag);
7232   }
7233 
7234   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7235 
7236   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7237     CmdArgs.push_back("-fdiagnostics-format");
7238     CmdArgs.push_back("msvc");
7239   }
7240 
7241   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
7242     StringRef GuardArgs = A->getValue();
7243     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7244     // "ehcont-".
7245     if (GuardArgs.equals_lower("cf")) {
7246       // Emit CFG instrumentation and the table of address-taken functions.
7247       CmdArgs.push_back("-cfguard");
7248     } else if (GuardArgs.equals_lower("cf,nochecks")) {
7249       // Emit only the table of address-taken functions.
7250       CmdArgs.push_back("-cfguard-no-checks");
7251     } else if (GuardArgs.equals_lower("ehcont")) {
7252       // Emit EH continuation table.
7253       CmdArgs.push_back("-ehcontguard");
7254     } else if (GuardArgs.equals_lower("cf-") ||
7255                GuardArgs.equals_lower("ehcont-")) {
7256       // Do nothing, but we might want to emit a security warning in future.
7257     } else {
7258       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7259     }
7260   }
7261 }
7262 
getBaseInputName(const ArgList & Args,const InputInfo & Input)7263 const char *Clang::getBaseInputName(const ArgList &Args,
7264                                     const InputInfo &Input) {
7265   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7266 }
7267 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)7268 const char *Clang::getBaseInputStem(const ArgList &Args,
7269                                     const InputInfoList &Inputs) {
7270   const char *Str = getBaseInputName(Args, Inputs[0]);
7271 
7272   if (const char *End = strrchr(Str, '.'))
7273     return Args.MakeArgString(std::string(Str, End));
7274 
7275   return Str;
7276 }
7277 
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)7278 const char *Clang::getDependencyFileName(const ArgList &Args,
7279                                          const InputInfoList &Inputs) {
7280   // FIXME: Think about this more.
7281 
7282   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7283     SmallString<128> OutputFilename(OutputOpt->getValue());
7284     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
7285     return Args.MakeArgString(OutputFilename);
7286   }
7287 
7288   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
7289 }
7290 
7291 // Begin ClangAs
7292 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7293 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
7294                                 ArgStringList &CmdArgs) const {
7295   StringRef CPUName;
7296   StringRef ABIName;
7297   const llvm::Triple &Triple = getToolChain().getTriple();
7298   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
7299 
7300   CmdArgs.push_back("-target-abi");
7301   CmdArgs.push_back(ABIName.data());
7302 }
7303 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7304 void ClangAs::AddX86TargetArgs(const ArgList &Args,
7305                                ArgStringList &CmdArgs) const {
7306   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
7307                         /*IsLTO=*/false);
7308 
7309   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
7310     StringRef Value = A->getValue();
7311     if (Value == "intel" || Value == "att") {
7312       CmdArgs.push_back("-mllvm");
7313       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
7314     } else {
7315       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
7316           << A->getOption().getName() << Value;
7317     }
7318   }
7319 }
7320 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7321 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
7322                                ArgStringList &CmdArgs) const {
7323   const llvm::Triple &Triple = getToolChain().getTriple();
7324   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
7325 
7326   CmdArgs.push_back("-target-abi");
7327   CmdArgs.push_back(ABIName.data());
7328 }
7329 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7330 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
7331                            const InputInfo &Output, const InputInfoList &Inputs,
7332                            const ArgList &Args,
7333                            const char *LinkingOutput) const {
7334   ArgStringList CmdArgs;
7335 
7336   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7337   const InputInfo &Input = Inputs[0];
7338 
7339   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7340   const std::string &TripleStr = Triple.getTriple();
7341   const auto &D = getToolChain().getDriver();
7342 
7343   // Don't warn about "clang -w -c foo.s"
7344   Args.ClaimAllArgs(options::OPT_w);
7345   // and "clang -emit-llvm -c foo.s"
7346   Args.ClaimAllArgs(options::OPT_emit_llvm);
7347 
7348   claimNoWarnArgs(Args);
7349 
7350   // Invoke ourselves in -cc1as mode.
7351   //
7352   // FIXME: Implement custom jobs for internal actions.
7353   CmdArgs.push_back("-cc1as");
7354 
7355   // Add the "effective" target triple.
7356   CmdArgs.push_back("-triple");
7357   CmdArgs.push_back(Args.MakeArgString(TripleStr));
7358 
7359   // Set the output mode, we currently only expect to be used as a real
7360   // assembler.
7361   CmdArgs.push_back("-filetype");
7362   CmdArgs.push_back("obj");
7363 
7364   // Set the main file name, so that debug info works even with
7365   // -save-temps or preprocessed assembly.
7366   CmdArgs.push_back("-main-file-name");
7367   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
7368 
7369   // Add the target cpu
7370   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
7371   if (!CPU.empty()) {
7372     CmdArgs.push_back("-target-cpu");
7373     CmdArgs.push_back(Args.MakeArgString(CPU));
7374   }
7375 
7376   // Add the target features
7377   getTargetFeatures(D, Triple, Args, CmdArgs, true);
7378 
7379   // Ignore explicit -force_cpusubtype_ALL option.
7380   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
7381 
7382   // Pass along any -I options so we get proper .include search paths.
7383   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
7384 
7385   // Determine the original source input.
7386   const Action *SourceAction = &JA;
7387   while (SourceAction->getKind() != Action::InputClass) {
7388     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7389     SourceAction = SourceAction->getInputs()[0];
7390   }
7391 
7392   // Forward -g and handle debug info related flags, assuming we are dealing
7393   // with an actual assembly file.
7394   bool WantDebug = false;
7395   Args.ClaimAllArgs(options::OPT_g_Group);
7396   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
7397     WantDebug = !A->getOption().matches(options::OPT_g0) &&
7398                 !A->getOption().matches(options::OPT_ggdb0);
7399 
7400   unsigned DwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args);
7401   if (const Arg *GDwarfN = getDwarfNArg(Args))
7402     DwarfVersion = DwarfVersionNum(GDwarfN->getSpelling());
7403 
7404   if (DwarfVersion == 0)
7405     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
7406 
7407   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
7408 
7409   if (SourceAction->getType() == types::TY_Asm ||
7410       SourceAction->getType() == types::TY_PP_Asm) {
7411     // You might think that it would be ok to set DebugInfoKind outside of
7412     // the guard for source type, however there is a test which asserts
7413     // that some assembler invocation receives no -debug-info-kind,
7414     // and it's not clear whether that test is just overly restrictive.
7415     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
7416                                : codegenoptions::NoDebugInfo);
7417     // Add the -fdebug-compilation-dir flag if needed.
7418     addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
7419 
7420     addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
7421 
7422     // Set the AT_producer to the clang version when using the integrated
7423     // assembler on assembly source files.
7424     CmdArgs.push_back("-dwarf-debug-producer");
7425     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
7426 
7427     // And pass along -I options
7428     Args.AddAllArgs(CmdArgs, options::OPT_I);
7429   }
7430   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
7431                           llvm::DebuggerKind::Default);
7432   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
7433   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
7434 
7435 
7436   // Handle -fPIC et al -- the relocation-model affects the assembler
7437   // for some targets.
7438   llvm::Reloc::Model RelocationModel;
7439   unsigned PICLevel;
7440   bool IsPIE;
7441   std::tie(RelocationModel, PICLevel, IsPIE) =
7442       ParsePICArgs(getToolChain(), Args);
7443 
7444   const char *RMName = RelocationModelName(RelocationModel);
7445   if (RMName) {
7446     CmdArgs.push_back("-mrelocation-model");
7447     CmdArgs.push_back(RMName);
7448   }
7449 
7450   // Optionally embed the -cc1as level arguments into the debug info, for build
7451   // analysis.
7452   if (getToolChain().UseDwarfDebugFlags()) {
7453     ArgStringList OriginalArgs;
7454     for (const auto &Arg : Args)
7455       Arg->render(Args, OriginalArgs);
7456 
7457     SmallString<256> Flags;
7458     const char *Exec = getToolChain().getDriver().getClangProgramPath();
7459     EscapeSpacesAndBackslashes(Exec, Flags);
7460     for (const char *OriginalArg : OriginalArgs) {
7461       SmallString<128> EscapedArg;
7462       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7463       Flags += " ";
7464       Flags += EscapedArg;
7465     }
7466     CmdArgs.push_back("-dwarf-debug-flags");
7467     CmdArgs.push_back(Args.MakeArgString(Flags));
7468   }
7469 
7470   // FIXME: Add -static support, once we have it.
7471 
7472   // Add target specific flags.
7473   switch (getToolChain().getArch()) {
7474   default:
7475     break;
7476 
7477   case llvm::Triple::mips:
7478   case llvm::Triple::mipsel:
7479   case llvm::Triple::mips64:
7480   case llvm::Triple::mips64el:
7481     AddMIPSTargetArgs(Args, CmdArgs);
7482     break;
7483 
7484   case llvm::Triple::x86:
7485   case llvm::Triple::x86_64:
7486     AddX86TargetArgs(Args, CmdArgs);
7487     break;
7488 
7489   case llvm::Triple::arm:
7490   case llvm::Triple::armeb:
7491   case llvm::Triple::thumb:
7492   case llvm::Triple::thumbeb:
7493     // This isn't in AddARMTargetArgs because we want to do this for assembly
7494     // only, not C/C++.
7495     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
7496                      options::OPT_mno_default_build_attributes, true)) {
7497         CmdArgs.push_back("-mllvm");
7498         CmdArgs.push_back("-arm-add-build-attributes");
7499     }
7500     break;
7501 
7502   case llvm::Triple::aarch64:
7503   case llvm::Triple::aarch64_32:
7504   case llvm::Triple::aarch64_be:
7505     if (Args.hasArg(options::OPT_mmark_bti_property)) {
7506       CmdArgs.push_back("-mllvm");
7507       CmdArgs.push_back("-aarch64-mark-bti-property");
7508     }
7509     break;
7510 
7511   case llvm::Triple::riscv32:
7512   case llvm::Triple::riscv64:
7513     AddRISCVTargetArgs(Args, CmdArgs);
7514     break;
7515   }
7516 
7517   // Consume all the warning flags. Usually this would be handled more
7518   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
7519   // doesn't handle that so rather than warning about unused flags that are
7520   // actually used, we'll lie by omission instead.
7521   // FIXME: Stop lying and consume only the appropriate driver flags
7522   Args.ClaimAllArgs(options::OPT_W_Group);
7523 
7524   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
7525                                     getToolChain().getDriver());
7526 
7527   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
7528 
7529   assert(Output.isFilename() && "Unexpected lipo output.");
7530   CmdArgs.push_back("-o");
7531   CmdArgs.push_back(Output.getFilename());
7532 
7533   const llvm::Triple &T = getToolChain().getTriple();
7534   Arg *A;
7535   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
7536       T.isOSBinFormatELF()) {
7537     CmdArgs.push_back("-split-dwarf-output");
7538     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
7539   }
7540 
7541   if (Triple.isAMDGPU())
7542     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7543 
7544   assert(Input.isFilename() && "Invalid input.");
7545   CmdArgs.push_back(Input.getFilename());
7546 
7547   const char *Exec = getToolChain().getDriver().getClangProgramPath();
7548   if (D.CC1Main && !D.CCGenDiagnostics) {
7549     // Invoke cc1as directly in this process.
7550     C.addCommand(std::make_unique<CC1Command>(JA, *this,
7551                                               ResponseFileSupport::AtFileUTF8(),
7552                                               Exec, CmdArgs, Inputs, Output));
7553   } else {
7554     C.addCommand(std::make_unique<Command>(JA, *this,
7555                                            ResponseFileSupport::AtFileUTF8(),
7556                                            Exec, CmdArgs, Inputs, Output));
7557   }
7558 }
7559 
7560 // Begin OffloadBundler
7561 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const7562 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
7563                                   const InputInfo &Output,
7564                                   const InputInfoList &Inputs,
7565                                   const llvm::opt::ArgList &TCArgs,
7566                                   const char *LinkingOutput) const {
7567   // The version with only one output is expected to refer to a bundling job.
7568   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
7569 
7570   // The bundling command looks like this:
7571   // clang-offload-bundler -type=bc
7572   //   -targets=host-triple,openmp-triple1,openmp-triple2
7573   //   -outputs=input_file
7574   //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7575 
7576   ArgStringList CmdArgs;
7577 
7578   // Get the type.
7579   CmdArgs.push_back(TCArgs.MakeArgString(
7580       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
7581 
7582   assert(JA.getInputs().size() == Inputs.size() &&
7583          "Not have inputs for all dependence actions??");
7584 
7585   // Get the targets.
7586   SmallString<128> Triples;
7587   Triples += "-targets=";
7588   for (unsigned I = 0; I < Inputs.size(); ++I) {
7589     if (I)
7590       Triples += ',';
7591 
7592     // Find ToolChain for this input.
7593     Action::OffloadKind CurKind = Action::OFK_Host;
7594     const ToolChain *CurTC = &getToolChain();
7595     const Action *CurDep = JA.getInputs()[I];
7596 
7597     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
7598       CurTC = nullptr;
7599       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
7600         assert(CurTC == nullptr && "Expected one dependence!");
7601         CurKind = A->getOffloadingDeviceKind();
7602         CurTC = TC;
7603       });
7604     }
7605     Triples += Action::GetOffloadKindName(CurKind);
7606     Triples += '-';
7607     Triples += CurTC->getTriple().normalize();
7608     if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
7609       Triples += '-';
7610       Triples += CurDep->getOffloadingArch();
7611     }
7612   }
7613   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7614 
7615   // Get bundled file command.
7616   CmdArgs.push_back(
7617       TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
7618 
7619   // Get unbundled files command.
7620   SmallString<128> UB;
7621   UB += "-inputs=";
7622   for (unsigned I = 0; I < Inputs.size(); ++I) {
7623     if (I)
7624       UB += ',';
7625 
7626     // Find ToolChain for this input.
7627     const ToolChain *CurTC = &getToolChain();
7628     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
7629       CurTC = nullptr;
7630       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
7631         assert(CurTC == nullptr && "Expected one dependence!");
7632         CurTC = TC;
7633       });
7634     }
7635     UB += CurTC->getInputFilename(Inputs[I]);
7636   }
7637   CmdArgs.push_back(TCArgs.MakeArgString(UB));
7638 
7639   // All the inputs are encoded as commands.
7640   C.addCommand(std::make_unique<Command>(
7641       JA, *this, ResponseFileSupport::None(),
7642       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7643       CmdArgs, None, Output));
7644 }
7645 
ConstructJobMultipleOutputs(Compilation & C,const JobAction & JA,const InputInfoList & Outputs,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const7646 void OffloadBundler::ConstructJobMultipleOutputs(
7647     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
7648     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
7649     const char *LinkingOutput) const {
7650   // The version with multiple outputs is expected to refer to a unbundling job.
7651   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
7652 
7653   // The unbundling command looks like this:
7654   // clang-offload-bundler -type=bc
7655   //   -targets=host-triple,openmp-triple1,openmp-triple2
7656   //   -inputs=input_file
7657   //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7658   //   -unbundle
7659 
7660   ArgStringList CmdArgs;
7661 
7662   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
7663   InputInfo Input = Inputs.front();
7664 
7665   // Get the type.
7666   CmdArgs.push_back(TCArgs.MakeArgString(
7667       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
7668 
7669   // Get the targets.
7670   SmallString<128> Triples;
7671   Triples += "-targets=";
7672   auto DepInfo = UA.getDependentActionsInfo();
7673   for (unsigned I = 0; I < DepInfo.size(); ++I) {
7674     if (I)
7675       Triples += ',';
7676 
7677     auto &Dep = DepInfo[I];
7678     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
7679     Triples += '-';
7680     Triples += Dep.DependentToolChain->getTriple().normalize();
7681     if (Dep.DependentOffloadKind == Action::OFK_HIP &&
7682         !Dep.DependentBoundArch.empty()) {
7683       Triples += '-';
7684       Triples += Dep.DependentBoundArch;
7685     }
7686   }
7687 
7688   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7689 
7690   // Get bundled file command.
7691   CmdArgs.push_back(
7692       TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
7693 
7694   // Get unbundled files command.
7695   SmallString<128> UB;
7696   UB += "-outputs=";
7697   for (unsigned I = 0; I < Outputs.size(); ++I) {
7698     if (I)
7699       UB += ',';
7700     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
7701   }
7702   CmdArgs.push_back(TCArgs.MakeArgString(UB));
7703   CmdArgs.push_back("-unbundle");
7704   CmdArgs.push_back("-allow-missing-bundles");
7705 
7706   // All the inputs are encoded as commands.
7707   C.addCommand(std::make_unique<Command>(
7708       JA, *this, ResponseFileSupport::None(),
7709       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7710       CmdArgs, None, Outputs));
7711 }
7712 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7713 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA,
7714                                   const InputInfo &Output,
7715                                   const InputInfoList &Inputs,
7716                                   const ArgList &Args,
7717                                   const char *LinkingOutput) const {
7718   ArgStringList CmdArgs;
7719 
7720   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7721 
7722   // Add the "effective" target triple.
7723   CmdArgs.push_back("-target");
7724   CmdArgs.push_back(Args.MakeArgString(Triple.getTriple()));
7725 
7726   // Add the output file name.
7727   assert(Output.isFilename() && "Invalid output.");
7728   CmdArgs.push_back("-o");
7729   CmdArgs.push_back(Output.getFilename());
7730 
7731   // Add inputs.
7732   for (const InputInfo &I : Inputs) {
7733     assert(I.isFilename() && "Invalid input.");
7734     CmdArgs.push_back(I.getFilename());
7735   }
7736 
7737   C.addCommand(std::make_unique<Command>(
7738       JA, *this, ResponseFileSupport::None(),
7739       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7740       CmdArgs, Inputs, Output));
7741 }
7742