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