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