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