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