xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp (revision 6e516c87b6d779911edde7481d8aef165b837a03)
10b57cec5SDimitry Andric //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Clang.h"
105ffd83dbSDimitry Andric #include "AMDGPU.h"
110b57cec5SDimitry Andric #include "Arch/AArch64.h"
120b57cec5SDimitry Andric #include "Arch/ARM.h"
1381ad6265SDimitry Andric #include "Arch/CSKY.h"
14bdd1243dSDimitry Andric #include "Arch/LoongArch.h"
15fe6060f1SDimitry Andric #include "Arch/M68k.h"
160b57cec5SDimitry Andric #include "Arch/Mips.h"
170b57cec5SDimitry Andric #include "Arch/PPC.h"
180b57cec5SDimitry Andric #include "Arch/RISCV.h"
190b57cec5SDimitry Andric #include "Arch/Sparc.h"
200b57cec5SDimitry Andric #include "Arch/SystemZ.h"
215ffd83dbSDimitry Andric #include "Arch/VE.h"
220b57cec5SDimitry Andric #include "Arch/X86.h"
230b57cec5SDimitry Andric #include "CommonArgs.h"
240b57cec5SDimitry Andric #include "Hexagon.h"
255ffd83dbSDimitry Andric #include "MSP430.h"
260b57cec5SDimitry Andric #include "PS4CPU.h"
27349cc55cSDimitry Andric #include "clang/Basic/CLWarnings.h"
280b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
29a7dea167SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
30bdd1243dSDimitry Andric #include "clang/Basic/HeaderInclude.h"
310b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
32753f127fSDimitry Andric #include "clang/Basic/MakeSupport.h"
330b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
340b57cec5SDimitry Andric #include "clang/Basic/Version.h"
3581ad6265SDimitry Andric #include "clang/Config/config.h"
3681ad6265SDimitry Andric #include "clang/Driver/Action.h"
370b57cec5SDimitry Andric #include "clang/Driver/Distro.h"
380b57cec5SDimitry Andric #include "clang/Driver/DriverDiagnostic.h"
39fe6060f1SDimitry Andric #include "clang/Driver/InputInfo.h"
400b57cec5SDimitry Andric #include "clang/Driver/Options.h"
410b57cec5SDimitry Andric #include "clang/Driver/SanitizerArgs.h"
4204eeddc0SDimitry Andric #include "clang/Driver/Types.h"
430b57cec5SDimitry Andric #include "clang/Driver/XRayArgs.h"
4481ad6265SDimitry Andric #include "llvm/ADT/SmallSet.h"
450b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
467a6dacacSDimitry Andric #include "llvm/BinaryFormat/Magic.h"
470b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
480fca6ea1SDimitry Andric #include "llvm/Frontend/Debug/Options.h"
497a6dacacSDimitry Andric #include "llvm/Object/ObjectFile.h"
500b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
510b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
525ffd83dbSDimitry Andric #include "llvm/Support/Compiler.h"
530b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
5406c3fb27SDimitry Andric #include "llvm/Support/Error.h"
550b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
560b57cec5SDimitry Andric #include "llvm/Support/Path.h"
570b57cec5SDimitry Andric #include "llvm/Support/Process.h"
580b57cec5SDimitry Andric #include "llvm/Support/YAMLParser.h"
590fca6ea1SDimitry Andric #include "llvm/TargetParser/AArch64TargetParser.h"
6006c3fb27SDimitry Andric #include "llvm/TargetParser/ARMTargetParserCommon.h"
6106c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
628a4dda33SDimitry Andric #include "llvm/TargetParser/LoongArchTargetParser.h"
630fca6ea1SDimitry Andric #include "llvm/TargetParser/RISCVISAInfo.h"
6406c3fb27SDimitry Andric #include "llvm/TargetParser/RISCVTargetParser.h"
65753f127fSDimitry Andric #include <cctype>
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric using namespace clang::driver;
680b57cec5SDimitry Andric using namespace clang::driver::tools;
690b57cec5SDimitry Andric using namespace clang;
700b57cec5SDimitry Andric using namespace llvm::opt;
710b57cec5SDimitry Andric 
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)720b57cec5SDimitry Andric static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
73349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
74349cc55cSDimitry Andric                                options::OPT_fminimize_whitespace,
755f757f3fSDimitry Andric                                options::OPT_fno_minimize_whitespace,
765f757f3fSDimitry Andric                                options::OPT_fkeep_system_includes,
775f757f3fSDimitry Andric                                options::OPT_fno_keep_system_includes)) {
780b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
790b57cec5SDimitry Andric         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
800b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
810b57cec5SDimitry Andric           << A->getBaseArg().getAsString(Args)
820b57cec5SDimitry Andric           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
830b57cec5SDimitry Andric     }
840b57cec5SDimitry Andric   }
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)870b57cec5SDimitry Andric static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
880b57cec5SDimitry Andric   // In gcc, only ARM checks this, but it seems reasonable to check universally.
890b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
900b57cec5SDimitry Andric     if (const Arg *A =
910b57cec5SDimitry Andric             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
920b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
930b57cec5SDimitry Andric                                                       << "-static";
940b57cec5SDimitry Andric }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric // Add backslashes to escape spaces and other backslashes.
970b57cec5SDimitry Andric // This is used for the space-separated argument list specified with
980b57cec5SDimitry Andric // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)990b57cec5SDimitry Andric static void EscapeSpacesAndBackslashes(const char *Arg,
1000b57cec5SDimitry Andric                                        SmallVectorImpl<char> &Res) {
1010b57cec5SDimitry Andric   for (; *Arg; ++Arg) {
1020b57cec5SDimitry Andric     switch (*Arg) {
1030b57cec5SDimitry Andric     default:
1040b57cec5SDimitry Andric       break;
1050b57cec5SDimitry Andric     case ' ':
1060b57cec5SDimitry Andric     case '\\':
1070b57cec5SDimitry Andric       Res.push_back('\\');
1080b57cec5SDimitry Andric       break;
1090b57cec5SDimitry Andric     }
1100b57cec5SDimitry Andric     Res.push_back(*Arg);
1110b57cec5SDimitry Andric   }
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric /// Apply \a Work on the current tool chain \a RegularToolChain and any other
1150b57cec5SDimitry Andric /// offloading tool chain that is associated with the current action \a JA.
1160b57cec5SDimitry Andric static void
forAllAssociatedToolChains(Compilation & C,const JobAction & JA,const ToolChain & RegularToolChain,llvm::function_ref<void (const ToolChain &)> Work)1170b57cec5SDimitry Andric forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
1180b57cec5SDimitry Andric                            const ToolChain &RegularToolChain,
1190b57cec5SDimitry Andric                            llvm::function_ref<void(const ToolChain &)> Work) {
1200b57cec5SDimitry Andric   // Apply Work on the current/regular tool chain.
1210b57cec5SDimitry Andric   Work(RegularToolChain);
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // Apply Work on all the offloading tool chains associated with the current
1240b57cec5SDimitry Andric   // action.
1250b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_Cuda))
1260b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1270b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
1280b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1290b57cec5SDimitry Andric   else if (JA.isHostOffloading(Action::OFK_HIP))
1300b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
1310b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_HIP))
1320b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
1350b57cec5SDimitry Andric     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
1360b57cec5SDimitry Andric     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
1370b57cec5SDimitry Andric       Work(*II->second);
1380b57cec5SDimitry Andric   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
1390b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   //
1420b57cec5SDimitry Andric   // TODO: Add support for other offloading programming models here.
1430b57cec5SDimitry Andric   //
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric /// This is a helper function for validating the optional refinement step
1470b57cec5SDimitry Andric /// parameter in reciprocal argument strings. Return false if there is an error
1480b57cec5SDimitry Andric /// parsing the refinement step. Otherwise, return true and set the Position
1490b57cec5SDimitry Andric /// of the refinement step in the input string.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)1500b57cec5SDimitry Andric static bool getRefinementStep(StringRef In, const Driver &D,
1510b57cec5SDimitry Andric                               const Arg &A, size_t &Position) {
1520b57cec5SDimitry Andric   const char RefinementStepToken = ':';
1530b57cec5SDimitry Andric   Position = In.find(RefinementStepToken);
1540b57cec5SDimitry Andric   if (Position != StringRef::npos) {
1550b57cec5SDimitry Andric     StringRef Option = A.getOption().getName();
1560b57cec5SDimitry Andric     StringRef RefStep = In.substr(Position + 1);
1570b57cec5SDimitry Andric     // Allow exactly one numeric character for the additional refinement
1580b57cec5SDimitry Andric     // step parameter. This is reasonable for all currently-supported
1590b57cec5SDimitry Andric     // operations and architectures because we would expect that a larger value
1600b57cec5SDimitry Andric     // of refinement steps would cause the estimate "optimization" to
1610b57cec5SDimitry Andric     // under-perform the native operation. Also, if the estimate does not
1620b57cec5SDimitry Andric     // converge quickly, it probably will not ever converge, so further
1630b57cec5SDimitry Andric     // refinement steps will not produce a better answer.
1640b57cec5SDimitry Andric     if (RefStep.size() != 1) {
1650b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1660b57cec5SDimitry Andric       return false;
1670b57cec5SDimitry Andric     }
1680b57cec5SDimitry Andric     char RefStepChar = RefStep[0];
1690b57cec5SDimitry Andric     if (RefStepChar < '0' || RefStepChar > '9') {
1700b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1710b57cec5SDimitry Andric       return false;
1720b57cec5SDimitry Andric     }
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric   return true;
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)1780b57cec5SDimitry Andric static void ParseMRecip(const Driver &D, const ArgList &Args,
1790b57cec5SDimitry Andric                         ArgStringList &OutStrings) {
1800b57cec5SDimitry Andric   StringRef DisabledPrefixIn = "!";
1810b57cec5SDimitry Andric   StringRef DisabledPrefixOut = "!";
1820b57cec5SDimitry Andric   StringRef EnabledPrefixOut = "";
1830b57cec5SDimitry Andric   StringRef Out = "-mrecip=";
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1860b57cec5SDimitry Andric   if (!A)
1870b57cec5SDimitry Andric     return;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   unsigned NumOptions = A->getNumValues();
1900b57cec5SDimitry Andric   if (NumOptions == 0) {
1910b57cec5SDimitry Andric     // No option is the same as "all".
1920b57cec5SDimitry Andric     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1930b57cec5SDimitry Andric     return;
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   // Pass through "all", "none", or "default" with an optional refinement step.
1970b57cec5SDimitry Andric   if (NumOptions == 1) {
1980b57cec5SDimitry Andric     StringRef Val = A->getValue(0);
1990b57cec5SDimitry Andric     size_t RefStepLoc;
2000b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStepLoc))
2010b57cec5SDimitry Andric       return;
2020b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStepLoc);
2030b57cec5SDimitry Andric     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2040b57cec5SDimitry Andric       OutStrings.push_back(Args.MakeArgString(Out + Val));
2050b57cec5SDimitry Andric       return;
2060b57cec5SDimitry Andric     }
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // Each reciprocal type may be enabled or disabled individually.
2100b57cec5SDimitry Andric   // Check each input value for validity, concatenate them all back together,
2110b57cec5SDimitry Andric   // and pass through.
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   llvm::StringMap<bool> OptionStrings;
2140b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divd", false));
2150b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divf", false));
21681ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("divh", false));
2170b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divd", false));
2180b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divf", false));
21981ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divh", false));
2200b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtd", false));
2210b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtf", false));
22281ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("sqrth", false));
2230b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2240b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
22581ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrth", false));
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOptions; ++i) {
2280b57cec5SDimitry Andric     StringRef Val = A->getValue(i);
2290b57cec5SDimitry Andric 
2305f757f3fSDimitry Andric     bool IsDisabled = Val.starts_with(DisabledPrefixIn);
2310b57cec5SDimitry Andric     // Ignore the disablement token for string matching.
2320b57cec5SDimitry Andric     if (IsDisabled)
2330b57cec5SDimitry Andric       Val = Val.substr(1);
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     size_t RefStep;
2360b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStep))
2370b57cec5SDimitry Andric       return;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStep);
2400b57cec5SDimitry Andric     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2410b57cec5SDimitry Andric     if (OptionIter == OptionStrings.end()) {
2420b57cec5SDimitry Andric       // Try again specifying float suffix.
2430b57cec5SDimitry Andric       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2440b57cec5SDimitry Andric       if (OptionIter == OptionStrings.end()) {
2450b57cec5SDimitry Andric         // The input name did not match any known option string.
2460b57cec5SDimitry Andric         D.Diag(diag::err_drv_unknown_argument) << Val;
2470b57cec5SDimitry Andric         return;
2480b57cec5SDimitry Andric       }
24981ad6265SDimitry Andric       // The option was specified without a half or float or double suffix.
25081ad6265SDimitry Andric       // Make sure that the double or half entry was not already specified.
2510b57cec5SDimitry Andric       // The float entry will be checked below.
25281ad6265SDimitry Andric       if (OptionStrings[ValBase.str() + 'd'] ||
25381ad6265SDimitry Andric           OptionStrings[ValBase.str() + 'h']) {
2540b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2550b57cec5SDimitry Andric         return;
2560b57cec5SDimitry Andric       }
2570b57cec5SDimitry Andric     }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric     if (OptionIter->second == true) {
2600b57cec5SDimitry Andric       // Duplicate option specified.
2610b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2620b57cec5SDimitry Andric       return;
2630b57cec5SDimitry Andric     }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric     // Mark the matched option as found. Do not allow duplicate specifiers.
2660b57cec5SDimitry Andric     OptionIter->second = true;
2670b57cec5SDimitry Andric 
26881ad6265SDimitry Andric     // If the precision was not specified, also mark the double and half entry
26981ad6265SDimitry Andric     // as found.
27081ad6265SDimitry Andric     if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
2710b57cec5SDimitry Andric       OptionStrings[ValBase.str() + 'd'] = true;
27281ad6265SDimitry Andric       OptionStrings[ValBase.str() + 'h'] = true;
27381ad6265SDimitry Andric     }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric     // Build the output string.
2760b57cec5SDimitry Andric     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2770b57cec5SDimitry Andric     Out = Args.MakeArgString(Out + Prefix + Val);
2780b57cec5SDimitry Andric     if (i != NumOptions - 1)
2790b57cec5SDimitry Andric       Out = Args.MakeArgString(Out + ",");
2800b57cec5SDimitry Andric   }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   OutStrings.push_back(Args.MakeArgString(Out));
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric /// The -mprefer-vector-width option accepts either a positive integer
2860b57cec5SDimitry Andric /// or the string "none".
ParseMPreferVectorWidth(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)2870b57cec5SDimitry Andric static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
2880b57cec5SDimitry Andric                                     ArgStringList &CmdArgs) {
2890b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
2900b57cec5SDimitry Andric   if (!A)
2910b57cec5SDimitry Andric     return;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   StringRef Value = A->getValue();
2940b57cec5SDimitry Andric   if (Value == "none") {
2950b57cec5SDimitry Andric     CmdArgs.push_back("-mprefer-vector-width=none");
2960b57cec5SDimitry Andric   } else {
2970b57cec5SDimitry Andric     unsigned Width;
2980b57cec5SDimitry Andric     if (Value.getAsInteger(10, Width)) {
2990b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3000b57cec5SDimitry Andric       return;
3010b57cec5SDimitry Andric     }
3020b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
3030b57cec5SDimitry Andric   }
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)3070b57cec5SDimitry Andric shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
3080b57cec5SDimitry Andric                                           const llvm::Triple &Triple) {
3090b57cec5SDimitry Andric   // We use the zero-cost exception tables for Objective-C if the non-fragile
3100b57cec5SDimitry Andric   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
3110b57cec5SDimitry Andric   // later.
3120b57cec5SDimitry Andric   if (runtime.isNonFragile())
3130b57cec5SDimitry Andric     return true;
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   if (!Triple.isMacOSX())
3160b57cec5SDimitry Andric     return false;
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   return (!Triple.isMacOSXVersionLT(10, 5) &&
3190b57cec5SDimitry Andric           (Triple.getArch() == llvm::Triple::x86_64 ||
3200b57cec5SDimitry Andric            Triple.getArch() == llvm::Triple::arm));
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric /// Adds exception related arguments to the driver command arguments. There's a
3244824e7fdSDimitry Andric /// main flag, -fexceptions and also language specific flags to enable/disable
3250b57cec5SDimitry Andric /// C++ and Objective-C exceptions. This makes it possible to for example
3260b57cec5SDimitry Andric /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)327fe6060f1SDimitry Andric static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
3280b57cec5SDimitry Andric                              const ToolChain &TC, bool KernelOrKext,
3290b57cec5SDimitry Andric                              const ObjCRuntime &objcRuntime,
3300b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
3310b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   if (KernelOrKext) {
3340b57cec5SDimitry Andric     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
3350b57cec5SDimitry Andric     // arguments now to avoid warnings about unused arguments.
3360b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fexceptions);
3370b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_exceptions);
3380b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
3390b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
3400b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
3410b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
342fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
343fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
344fe6060f1SDimitry Andric     return false;
3450b57cec5SDimitry Andric   }
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   // See if the user explicitly enabled exceptions.
3480b57cec5SDimitry Andric   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3490b57cec5SDimitry Andric                          false);
3500b57cec5SDimitry Andric 
3510fca6ea1SDimitry Andric   // Async exceptions are Windows MSVC only.
3520fca6ea1SDimitry Andric   if (Triple.isWindowsMSVCEnvironment()) {
353fe6060f1SDimitry Andric     bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
354fe6060f1SDimitry Andric                             options::OPT_fno_async_exceptions, false);
355fe6060f1SDimitry Andric     if (EHa) {
356fe6060f1SDimitry Andric       CmdArgs.push_back("-fasync-exceptions");
357fe6060f1SDimitry Andric       EH = true;
358fe6060f1SDimitry Andric     }
3590fca6ea1SDimitry Andric   }
360fe6060f1SDimitry Andric 
3610b57cec5SDimitry Andric   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
3620b57cec5SDimitry Andric   // is not necessarily sensible, but follows GCC.
3630b57cec5SDimitry Andric   if (types::isObjC(InputType) &&
3640b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fobjc_exceptions,
3650b57cec5SDimitry Andric                    options::OPT_fno_objc_exceptions, true)) {
3660b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-exceptions");
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   if (types::isCXX(InputType)) {
37281ad6265SDimitry Andric     // Disable C++ EH by default on XCore and PS4/PS5.
37381ad6265SDimitry Andric     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
37481ad6265SDimitry Andric                                 !Triple.isPS() && !Triple.isDriverKit();
3750b57cec5SDimitry Andric     Arg *ExceptionArg = Args.getLastArg(
3760b57cec5SDimitry Andric         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
3770b57cec5SDimitry Andric         options::OPT_fexceptions, options::OPT_fno_exceptions);
3780b57cec5SDimitry Andric     if (ExceptionArg)
3790b57cec5SDimitry Andric       CXXExceptionsEnabled =
3800b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
3810b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fexceptions);
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     if (CXXExceptionsEnabled) {
3840b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric       EH = true;
3870b57cec5SDimitry Andric     }
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3905ffd83dbSDimitry Andric   // OPT_fignore_exceptions means exception could still be thrown,
3915ffd83dbSDimitry Andric   // but no clean up or catch would happen in current module.
3925ffd83dbSDimitry Andric   // So we do not set EH to false.
3935ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
3945ffd83dbSDimitry Andric 
3955f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
3965f757f3fSDimitry Andric                     options::OPT_fno_assume_nothrow_exception_dtor);
3975f757f3fSDimitry Andric 
3980b57cec5SDimitry Andric   if (EH)
3990b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
400fe6060f1SDimitry Andric   return EH;
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
ShouldEnableAutolink(const ArgList & Args,const ToolChain & TC,const JobAction & JA)403480093f4SDimitry Andric static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
404480093f4SDimitry Andric                                  const JobAction &JA) {
4050b57cec5SDimitry Andric   bool Default = true;
4060b57cec5SDimitry Andric   if (TC.getTriple().isOSDarwin()) {
4070b57cec5SDimitry Andric     // The native darwin assembler doesn't support the linker_option directives,
4080b57cec5SDimitry Andric     // so we disable them if we think the .s file will be passed to it.
4090b57cec5SDimitry Andric     Default = TC.useIntegratedAs();
4100b57cec5SDimitry Andric   }
411480093f4SDimitry Andric   // The linker_option directives are intended for host compilation.
412480093f4SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
413480093f4SDimitry Andric       JA.isDeviceOffloading(Action::OFK_HIP))
414480093f4SDimitry Andric     Default = false;
415480093f4SDimitry Andric   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
4160b57cec5SDimitry Andric                       Default);
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs,const llvm::vfs::FileSystem & VFS)4200eae32dcSDimitry Andric static const char *addDebugCompDirArg(const ArgList &Args,
4210eae32dcSDimitry Andric                                       ArgStringList &CmdArgs,
422a7dea167SDimitry Andric                                       const llvm::vfs::FileSystem &VFS) {
423fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
424fe6060f1SDimitry Andric                                options::OPT_fdebug_compilation_dir_EQ)) {
425fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
426fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
427fe6060f1SDimitry Andric                                            A->getValue()));
428fe6060f1SDimitry Andric     else
429fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
430a7dea167SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
431a7dea167SDimitry Andric                  VFS.getCurrentWorkingDirectory()) {
432fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
4330b57cec5SDimitry Andric   }
4340eae32dcSDimitry Andric   StringRef Path(CmdArgs.back());
4350eae32dcSDimitry Andric   return Path.substr(Path.find('=') + 1).data();
4360eae32dcSDimitry Andric }
4370eae32dcSDimitry Andric 
addDebugObjectName(const ArgList & Args,ArgStringList & CmdArgs,const char * DebugCompilationDir,const char * OutputFileName)4380eae32dcSDimitry Andric static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
4390eae32dcSDimitry Andric                                const char *DebugCompilationDir,
4400eae32dcSDimitry Andric                                const char *OutputFileName) {
4410eae32dcSDimitry Andric   // No need to generate a value for -object-file-name if it was provided.
4420eae32dcSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
4435f757f3fSDimitry Andric     if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
4440eae32dcSDimitry Andric       return;
4450eae32dcSDimitry Andric 
4460eae32dcSDimitry Andric   if (Args.hasArg(options::OPT_object_file_name_EQ))
4470eae32dcSDimitry Andric     return;
4480eae32dcSDimitry Andric 
4490eae32dcSDimitry Andric   SmallString<128> ObjFileNameForDebug(OutputFileName);
4500eae32dcSDimitry Andric   if (ObjFileNameForDebug != "-" &&
4510eae32dcSDimitry Andric       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
4520eae32dcSDimitry Andric       (!DebugCompilationDir ||
4530eae32dcSDimitry Andric        llvm::sys::path::is_absolute(DebugCompilationDir))) {
4540eae32dcSDimitry Andric     // Make the path absolute in the debug infos like MSVC does.
4550eae32dcSDimitry Andric     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
4560eae32dcSDimitry Andric   }
45706c3fb27SDimitry Andric   // If the object file name is a relative path, then always use Windows
45806c3fb27SDimitry Andric   // backslash style as -object-file-name is used for embedding object file path
45906c3fb27SDimitry Andric   // in codeview and it can only be generated when targeting on Windows.
46006c3fb27SDimitry Andric   // Otherwise, just use native absolute path.
46106c3fb27SDimitry Andric   llvm::sys::path::Style Style =
46206c3fb27SDimitry Andric       llvm::sys::path::is_absolute(ObjFileNameForDebug)
46306c3fb27SDimitry Andric           ? llvm::sys::path::Style::native
46406c3fb27SDimitry Andric           : llvm::sys::path::Style::windows_backslash;
46506c3fb27SDimitry Andric   llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
46606c3fb27SDimitry Andric                                Style);
4670eae32dcSDimitry Andric   CmdArgs.push_back(
4680eae32dcSDimitry Andric       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
addDebugPrefixMapArg(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)47281ad6265SDimitry Andric static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
47381ad6265SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
47481ad6265SDimitry Andric   auto AddOneArg = [&](StringRef Map, StringRef Name) {
475349cc55cSDimitry Andric     if (!Map.contains('='))
47681ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
4770b57cec5SDimitry Andric     else
4780b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
47981ad6265SDimitry Andric   };
48081ad6265SDimitry Andric 
48181ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
48281ad6265SDimitry Andric                                     options::OPT_fdebug_prefix_map_EQ)) {
48381ad6265SDimitry Andric     AddOneArg(A->getValue(), A->getOption().getName());
4840b57cec5SDimitry Andric     A->claim();
4850b57cec5SDimitry Andric   }
48681ad6265SDimitry Andric   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
48781ad6265SDimitry Andric   if (GlobalRemapEntry.empty())
48881ad6265SDimitry Andric     return;
48981ad6265SDimitry Andric   AddOneArg(GlobalRemapEntry, "environment");
4900b57cec5SDimitry Andric }
4910b57cec5SDimitry Andric 
492480093f4SDimitry Andric /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
addMacroPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)493480093f4SDimitry Andric static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
494480093f4SDimitry Andric                                  ArgStringList &CmdArgs) {
495480093f4SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
496480093f4SDimitry Andric                                     options::OPT_fmacro_prefix_map_EQ)) {
497480093f4SDimitry Andric     StringRef Map = A->getValue();
498349cc55cSDimitry Andric     if (!Map.contains('='))
499480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
500480093f4SDimitry Andric           << Map << A->getOption().getName();
501480093f4SDimitry Andric     else
502480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
503480093f4SDimitry Andric     A->claim();
504480093f4SDimitry Andric   }
505480093f4SDimitry Andric }
506480093f4SDimitry Andric 
507e8d8bef9SDimitry Andric /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
addCoveragePrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)508fe6060f1SDimitry Andric static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
509e8d8bef9SDimitry Andric                                    ArgStringList &CmdArgs) {
510e8d8bef9SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
511fe6060f1SDimitry Andric                                     options::OPT_fcoverage_prefix_map_EQ)) {
512e8d8bef9SDimitry Andric     StringRef Map = A->getValue();
513349cc55cSDimitry Andric     if (!Map.contains('='))
514e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
515e8d8bef9SDimitry Andric           << Map << A->getOption().getName();
516e8d8bef9SDimitry Andric     else
517fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
518e8d8bef9SDimitry Andric     A->claim();
519e8d8bef9SDimitry Andric   }
520e8d8bef9SDimitry Andric }
521e8d8bef9SDimitry Andric 
5220b57cec5SDimitry Andric /// Vectorize at all optimization levels greater than 1 except for -Oz.
5230b57cec5SDimitry Andric /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
5240b57cec5SDimitry Andric /// enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)5250b57cec5SDimitry Andric static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
5260b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5270b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
5280b57cec5SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
5290b57cec5SDimitry Andric       return true;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O0))
5320b57cec5SDimitry Andric       return false;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     // Vectorize -Os.
5370b57cec5SDimitry Andric     StringRef S(A->getValue());
5380b57cec5SDimitry Andric     if (S == "s")
5390b57cec5SDimitry Andric       return true;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric     // Don't vectorize -Oz, unless it's the slp vectorizer.
5420b57cec5SDimitry Andric     if (S == "z")
5430b57cec5SDimitry Andric       return isSlpVec;
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric     unsigned OptLevel = 0;
5460b57cec5SDimitry Andric     if (S.getAsInteger(10, OptLevel))
5470b57cec5SDimitry Andric       return false;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     return OptLevel > 1;
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   return false;
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)5560b57cec5SDimitry Andric static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
5570b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
5580b57cec5SDimitry Andric   // When using -verify-pch, we don't want to provide the type
5590b57cec5SDimitry Andric   // 'precompiled-header' if it was inferred from the file extension
5600b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
5610b57cec5SDimitry Andric     return;
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   CmdArgs.push_back("-x");
5640b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_rewrite_objc))
5650b57cec5SDimitry Andric     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
5660b57cec5SDimitry Andric   else {
5670b57cec5SDimitry Andric     // Map the driver type to the frontend type. This is mostly an identity
5680b57cec5SDimitry Andric     // mapping, except that the distinction between module interface units
5690b57cec5SDimitry Andric     // and other source files does not exist at the frontend layer.
5700b57cec5SDimitry Andric     const char *ClangType;
5710b57cec5SDimitry Andric     switch (Input.getType()) {
5720b57cec5SDimitry Andric     case types::TY_CXXModule:
5730b57cec5SDimitry Andric       ClangType = "c++";
5740b57cec5SDimitry Andric       break;
5750b57cec5SDimitry Andric     case types::TY_PP_CXXModule:
5760b57cec5SDimitry Andric       ClangType = "c++-cpp-output";
5770b57cec5SDimitry Andric       break;
5780b57cec5SDimitry Andric     default:
5790b57cec5SDimitry Andric       ClangType = types::getTypeName(Input.getType());
5800b57cec5SDimitry Andric       break;
5810b57cec5SDimitry Andric     }
5820b57cec5SDimitry Andric     CmdArgs.push_back(ClangType);
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
addPGOAndCoverageFlags(const ToolChain & TC,Compilation & C,const JobAction & JA,const InputInfo & Output,const ArgList & Args,SanitizerArgs & SanArgs,ArgStringList & CmdArgs)5860b57cec5SDimitry Andric static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
58706c3fb27SDimitry Andric                                    const JobAction &JA, const InputInfo &Output,
588349cc55cSDimitry Andric                                    const ArgList &Args, SanitizerArgs &SanArgs,
5890b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
59006c3fb27SDimitry Andric   const Driver &D = TC.getDriver();
5910b57cec5SDimitry Andric   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
5920b57cec5SDimitry Andric                                          options::OPT_fprofile_generate_EQ,
5930b57cec5SDimitry Andric                                          options::OPT_fno_profile_generate);
5940b57cec5SDimitry Andric   if (PGOGenerateArg &&
5950b57cec5SDimitry Andric       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
5960b57cec5SDimitry Andric     PGOGenerateArg = nullptr;
5970b57cec5SDimitry Andric 
59806c3fb27SDimitry Andric   auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   auto *ProfileGenerateArg = Args.getLastArg(
6010b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate,
6020b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate_EQ,
6030b57cec5SDimitry Andric       options::OPT_fno_profile_instr_generate);
6040b57cec5SDimitry Andric   if (ProfileGenerateArg &&
6050b57cec5SDimitry Andric       ProfileGenerateArg->getOption().matches(
6060b57cec5SDimitry Andric           options::OPT_fno_profile_instr_generate))
6070b57cec5SDimitry Andric     ProfileGenerateArg = nullptr;
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileGenerateArg)
6100b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6110b57cec5SDimitry Andric         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   auto *ProfileUseArg = getLastProfileUseArg(Args);
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileUseArg)
6160b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6170b57cec5SDimitry Andric         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   if (ProfileGenerateArg && ProfileUseArg)
6200b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6210b57cec5SDimitry Andric         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
6220b57cec5SDimitry Andric 
623e8d8bef9SDimitry Andric   if (CSPGOGenerateArg && PGOGenerateArg) {
6240b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6250b57cec5SDimitry Andric         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
626e8d8bef9SDimitry Andric     PGOGenerateArg = nullptr;
627e8d8bef9SDimitry Andric   }
6280b57cec5SDimitry Andric 
629fe6060f1SDimitry Andric   if (TC.getTriple().isOSAIX()) {
630fe6060f1SDimitry Andric     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
631fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
632fe6060f1SDimitry Andric           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
633fe6060f1SDimitry Andric   }
634fe6060f1SDimitry Andric 
6350b57cec5SDimitry Andric   if (ProfileGenerateArg) {
6360b57cec5SDimitry Andric     if (ProfileGenerateArg->getOption().matches(
6370b57cec5SDimitry Andric             options::OPT_fprofile_instr_generate_EQ))
6380b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
6390b57cec5SDimitry Andric                                            ProfileGenerateArg->getValue()));
6400b57cec5SDimitry Andric     // The default is to use Clang Instrumentation.
6410b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=clang");
6420fca6ea1SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment() &&
6430fca6ea1SDimitry Andric         Args.hasFlag(options::OPT_frtlib_defaultlib,
6440fca6ea1SDimitry Andric                      options::OPT_fno_rtlib_defaultlib, true)) {
6450b57cec5SDimitry Andric       // Add dependent lib for clang_rt.profile
6465ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6475ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric   }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   Arg *PGOGenArg = nullptr;
6520b57cec5SDimitry Andric   if (PGOGenerateArg) {
6530b57cec5SDimitry Andric     assert(!CSPGOGenerateArg);
6540b57cec5SDimitry Andric     PGOGenArg = PGOGenerateArg;
6550b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=llvm");
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric   if (CSPGOGenerateArg) {
6580b57cec5SDimitry Andric     assert(!PGOGenerateArg);
6590b57cec5SDimitry Andric     PGOGenArg = CSPGOGenerateArg;
6600b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=csllvm");
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric   if (PGOGenArg) {
6630fca6ea1SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment() &&
6640fca6ea1SDimitry Andric         Args.hasFlag(options::OPT_frtlib_defaultlib,
6650fca6ea1SDimitry Andric                      options::OPT_fno_rtlib_defaultlib, true)) {
6665ffd83dbSDimitry Andric       // Add dependent lib for clang_rt.profile
6675ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6685ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6690b57cec5SDimitry Andric     }
6700b57cec5SDimitry Andric     if (PGOGenArg->getOption().matches(
6710b57cec5SDimitry Andric             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
6720b57cec5SDimitry Andric                            : options::OPT_fcs_profile_generate_EQ)) {
6730b57cec5SDimitry Andric       SmallString<128> Path(PGOGenArg->getValue());
6740b57cec5SDimitry Andric       llvm::sys::path::append(Path, "default_%m.profraw");
6750b57cec5SDimitry Andric       CmdArgs.push_back(
6760b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
6770b57cec5SDimitry Andric     }
6780b57cec5SDimitry Andric   }
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   if (ProfileUseArg) {
6810b57cec5SDimitry Andric     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
6820b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6830b57cec5SDimitry Andric           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
6840b57cec5SDimitry Andric     else if ((ProfileUseArg->getOption().matches(
6850b57cec5SDimitry Andric                   options::OPT_fprofile_use_EQ) ||
6860b57cec5SDimitry Andric               ProfileUseArg->getOption().matches(
6870b57cec5SDimitry Andric                   options::OPT_fprofile_instr_use))) {
6880b57cec5SDimitry Andric       SmallString<128> Path(
6890b57cec5SDimitry Andric           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
6900b57cec5SDimitry Andric       if (Path.empty() || llvm::sys::fs::is_directory(Path))
6910b57cec5SDimitry Andric         llvm::sys::path::append(Path, "default.profdata");
6920b57cec5SDimitry Andric       CmdArgs.push_back(
6930b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
6940b57cec5SDimitry Andric     }
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6975ffd83dbSDimitry Andric   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
6985ffd83dbSDimitry Andric                                    options::OPT_fno_test_coverage, false) ||
699a7dea167SDimitry Andric                       Args.hasArg(options::OPT_coverage);
7005ffd83dbSDimitry Andric   bool EmitCovData = TC.needsGCovInstrumentation(Args);
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fcoverage_mapping,
7030b57cec5SDimitry Andric                    options::OPT_fno_coverage_mapping, false)) {
7040b57cec5SDimitry Andric     if (!ProfileGenerateArg)
7050b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7060b57cec5SDimitry Andric           << "-fcoverage-mapping"
7070b57cec5SDimitry Andric           << "-fprofile-instr-generate";
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric     CmdArgs.push_back("-fcoverage-mapping");
7100b57cec5SDimitry Andric   }
7110b57cec5SDimitry Andric 
7121db9f3b2SDimitry Andric   if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
7131db9f3b2SDimitry Andric                    false)) {
7141db9f3b2SDimitry Andric     if (!Args.hasFlag(options::OPT_fcoverage_mapping,
7151db9f3b2SDimitry Andric                       options::OPT_fno_coverage_mapping, false))
7161db9f3b2SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7171db9f3b2SDimitry Andric           << "-fcoverage-mcdc"
7181db9f3b2SDimitry Andric           << "-fcoverage-mapping";
7191db9f3b2SDimitry Andric 
7201db9f3b2SDimitry Andric     CmdArgs.push_back("-fcoverage-mcdc");
7211db9f3b2SDimitry Andric   }
7221db9f3b2SDimitry Andric 
723fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
724fe6060f1SDimitry Andric                                options::OPT_fcoverage_compilation_dir_EQ)) {
725fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
726fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
727fe6060f1SDimitry Andric           Twine("-fcoverage-compilation-dir=") + A->getValue()));
728fe6060f1SDimitry Andric     else
729fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
730fe6060f1SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
731fe6060f1SDimitry Andric                  D.getVFS().getCurrentWorkingDirectory()) {
732fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
733fe6060f1SDimitry Andric   }
734fe6060f1SDimitry Andric 
7350b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
7360b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
7370b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7380b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7390b57cec5SDimitry Andric           << "-fprofile-exclude-files="
7400b57cec5SDimitry Andric           << "--coverage";
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7430b57cec5SDimitry Andric     CmdArgs.push_back(
7440b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
7450b57cec5SDimitry Andric   }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
7480b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
7490b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7500b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7510b57cec5SDimitry Andric           << "-fprofile-filter-files="
7520b57cec5SDimitry Andric           << "--coverage";
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7550b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
7560b57cec5SDimitry Andric   }
7570b57cec5SDimitry Andric 
758e8d8bef9SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
759e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
760e8d8bef9SDimitry Andric     if (Val == "atomic" || Val == "prefer-atomic")
761e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprofile-update=atomic");
762e8d8bef9SDimitry Andric     else if (Val != "single")
763e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
764bdd1243dSDimitry Andric           << A->getSpelling() << Val;
765e8d8bef9SDimitry Andric   }
766e8d8bef9SDimitry Andric 
767fcaf7f86SDimitry Andric   int FunctionGroups = 1;
768fcaf7f86SDimitry Andric   int SelectedFunctionGroup = 0;
769fcaf7f86SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
770fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
771fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
772fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
773fcaf7f86SDimitry Andric   }
774fcaf7f86SDimitry Andric   if (const auto *A =
775fcaf7f86SDimitry Andric           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
776fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
777fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
778fcaf7f86SDimitry Andric         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
779fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
780fcaf7f86SDimitry Andric   }
781fcaf7f86SDimitry Andric   if (FunctionGroups != 1)
782fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
783fcaf7f86SDimitry Andric                                          Twine(FunctionGroups)));
784fcaf7f86SDimitry Andric   if (SelectedFunctionGroup != 0)
785fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
786fcaf7f86SDimitry Andric                                          Twine(SelectedFunctionGroup)));
787fcaf7f86SDimitry Andric 
788a7dea167SDimitry Andric   // Leave -fprofile-dir= an unused argument unless .gcda emission is
789a7dea167SDimitry Andric   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
790a7dea167SDimitry Andric   // the flag used. There is no -fno-profile-dir, so the user has no
791a7dea167SDimitry Andric   // targeted way to suppress the warning.
792a7dea167SDimitry Andric   Arg *FProfileDir = nullptr;
793a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_arcs) ||
794a7dea167SDimitry Andric       Args.hasArg(options::OPT_coverage))
795a7dea167SDimitry Andric     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
796a7dea167SDimitry Andric 
79706c3fb27SDimitry Andric   // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
79806c3fb27SDimitry Andric   // like we warn about -fsyntax-only -E.
79906c3fb27SDimitry Andric   (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
80006c3fb27SDimitry Andric 
80106c3fb27SDimitry Andric   // Put the .gcno and .gcda files (if needed) next to the primary output file,
80206c3fb27SDimitry Andric   // or fall back to a file in the current directory for `clang -c --coverage
80306c3fb27SDimitry Andric   // d/a.c` in the absence of -o.
80406c3fb27SDimitry Andric   if (EmitCovNotes || EmitCovData) {
80506c3fb27SDimitry Andric     SmallString<128> CoverageFilename;
80606c3fb27SDimitry Andric     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
80706c3fb27SDimitry Andric       // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
80806c3fb27SDimitry Andric       // path separator.
80906c3fb27SDimitry Andric       CoverageFilename = DumpDir->getValue();
81006c3fb27SDimitry Andric       CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
81106c3fb27SDimitry Andric     } else if (Arg *FinalOutput =
81206c3fb27SDimitry Andric                    C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
81306c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
81406c3fb27SDimitry Andric     } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
81506c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
81606c3fb27SDimitry Andric     } else {
81706c3fb27SDimitry Andric       CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
81806c3fb27SDimitry Andric     }
819a7dea167SDimitry Andric     if (llvm::sys::path::is_relative(CoverageFilename))
820a7dea167SDimitry Andric       (void)D.getVFS().makeAbsolute(CoverageFilename);
8210b57cec5SDimitry Andric     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
82206c3fb27SDimitry Andric     if (EmitCovNotes) {
8235f757f3fSDimitry Andric       CmdArgs.push_back(
8245f757f3fSDimitry Andric           Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
82506c3fb27SDimitry Andric     }
8260b57cec5SDimitry Andric 
827a7dea167SDimitry Andric     if (EmitCovData) {
828a7dea167SDimitry Andric       if (FProfileDir) {
82906c3fb27SDimitry Andric         SmallString<128> Gcno = std::move(CoverageFilename);
8300b57cec5SDimitry Andric         CoverageFilename = FProfileDir->getValue();
83106c3fb27SDimitry Andric         llvm::sys::path::append(CoverageFilename, Gcno);
8320b57cec5SDimitry Andric       }
8330b57cec5SDimitry Andric       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
8345f757f3fSDimitry Andric       CmdArgs.push_back(
8355f757f3fSDimitry Andric           Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
8360b57cec5SDimitry Andric     }
8370b57cec5SDimitry Andric   }
8380b57cec5SDimitry Andric }
8390b57cec5SDimitry Andric 
84006c3fb27SDimitry Andric static void
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,llvm::codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)84106c3fb27SDimitry Andric RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
84206c3fb27SDimitry Andric                         llvm::codegenoptions::DebugInfoKind DebugInfoKind,
8430b57cec5SDimitry Andric                         unsigned DwarfVersion,
8440b57cec5SDimitry Andric                         llvm::DebuggerKind DebuggerTuning) {
84506c3fb27SDimitry Andric   addDebugInfoKind(CmdArgs, DebugInfoKind);
8460b57cec5SDimitry Andric   if (DwarfVersion > 0)
8470b57cec5SDimitry Andric     CmdArgs.push_back(
8480b57cec5SDimitry Andric         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
8490b57cec5SDimitry Andric   switch (DebuggerTuning) {
8500b57cec5SDimitry Andric   case llvm::DebuggerKind::GDB:
8510b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=gdb");
8520b57cec5SDimitry Andric     break;
8530b57cec5SDimitry Andric   case llvm::DebuggerKind::LLDB:
8540b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=lldb");
8550b57cec5SDimitry Andric     break;
8560b57cec5SDimitry Andric   case llvm::DebuggerKind::SCE:
8570b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=sce");
8580b57cec5SDimitry Andric     break;
859fe6060f1SDimitry Andric   case llvm::DebuggerKind::DBX:
860fe6060f1SDimitry Andric     CmdArgs.push_back("-debugger-tuning=dbx");
861fe6060f1SDimitry Andric     break;
8620b57cec5SDimitry Andric   default:
8630b57cec5SDimitry Andric     break;
8640b57cec5SDimitry Andric   }
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric 
checkDebugInfoOption(const Arg * A,const ArgList & Args,const Driver & D,const ToolChain & TC)8670b57cec5SDimitry Andric static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
8680b57cec5SDimitry Andric                                  const Driver &D, const ToolChain &TC) {
8690b57cec5SDimitry Andric   assert(A && "Expected non-nullptr argument.");
8700b57cec5SDimitry Andric   if (TC.supportsDebugInfoOption(A))
8710b57cec5SDimitry Andric     return true;
8720b57cec5SDimitry Andric   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
8730b57cec5SDimitry Andric       << A->getAsString(Args) << TC.getTripleString();
8740b57cec5SDimitry Andric   return false;
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric 
RenderDebugInfoCompressionArgs(const ArgList & Args,ArgStringList & CmdArgs,const Driver & D,const ToolChain & TC)8770b57cec5SDimitry Andric static void RenderDebugInfoCompressionArgs(const ArgList &Args,
8780b57cec5SDimitry Andric                                            ArgStringList &CmdArgs,
8790b57cec5SDimitry Andric                                            const Driver &D,
8800b57cec5SDimitry Andric                                            const ToolChain &TC) {
881e8d8bef9SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
8820b57cec5SDimitry Andric   if (!A)
8830b57cec5SDimitry Andric     return;
8840b57cec5SDimitry Andric   if (checkDebugInfoOption(A, Args, D, TC)) {
8850b57cec5SDimitry Andric     StringRef Value = A->getValue();
8860b57cec5SDimitry Andric     if (Value == "none") {
8870b57cec5SDimitry Andric       CmdArgs.push_back("--compress-debug-sections=none");
88804eeddc0SDimitry Andric     } else if (Value == "zlib") {
889753f127fSDimitry Andric       if (llvm::compression::zlib::isAvailable()) {
8900b57cec5SDimitry Andric         CmdArgs.push_back(
8910b57cec5SDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
8920b57cec5SDimitry Andric       } else {
893bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
894bdd1243dSDimitry Andric       }
895bdd1243dSDimitry Andric     } else if (Value == "zstd") {
896bdd1243dSDimitry Andric       if (llvm::compression::zstd::isAvailable()) {
897bdd1243dSDimitry Andric         CmdArgs.push_back(
898bdd1243dSDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
899bdd1243dSDimitry Andric       } else {
900bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
9010b57cec5SDimitry Andric       }
9020b57cec5SDimitry Andric     } else {
9030b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
904bdd1243dSDimitry Andric           << A->getSpelling() << Value;
9050b57cec5SDimitry Andric     }
9060b57cec5SDimitry Andric   }
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
handleAMDGPUCodeObjectVersionOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsCC1As=false)909e8d8bef9SDimitry Andric static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
910e8d8bef9SDimitry Andric                                                  const ArgList &Args,
91181ad6265SDimitry Andric                                                  ArgStringList &CmdArgs,
91281ad6265SDimitry Andric                                                  bool IsCC1As = false) {
913fe6060f1SDimitry Andric   // If no version was requested by the user, use the default value from the
914fe6060f1SDimitry Andric   // back end. This is consistent with the value returned from
915fe6060f1SDimitry Andric   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
916fe6060f1SDimitry Andric   // requiring the corresponding llvm to have the AMDGPU target enabled,
917fe6060f1SDimitry Andric   // provided the user (e.g. front end tests) can use the default.
918fe6060f1SDimitry Andric   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
919fe6060f1SDimitry Andric     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
920e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1,
921e8d8bef9SDimitry Andric                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
922e8d8bef9SDimitry Andric                                       Twine(CodeObjVer)));
923e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
92481ad6265SDimitry Andric     // -cc1as does not accept -mcode-object-version option.
92581ad6265SDimitry Andric     if (!IsCC1As)
92681ad6265SDimitry Andric       CmdArgs.insert(CmdArgs.begin() + 1,
92781ad6265SDimitry Andric                      Args.MakeArgString(Twine("-mcode-object-version=") +
92881ad6265SDimitry Andric                                         Twine(CodeObjVer)));
929e8d8bef9SDimitry Andric   }
930fe6060f1SDimitry Andric }
9310b57cec5SDimitry Andric 
maybeHasClangPchSignature(const Driver & D,StringRef Path)9327a6dacacSDimitry Andric static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
9337a6dacacSDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
9347a6dacacSDimitry Andric       D.getVFS().getBufferForFile(Path);
9357a6dacacSDimitry Andric   if (!MemBuf)
9365f757f3fSDimitry Andric     return false;
9377a6dacacSDimitry Andric   llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
9387a6dacacSDimitry Andric   if (Magic == llvm::file_magic::unknown)
9397a6dacacSDimitry Andric     return false;
9407a6dacacSDimitry Andric   // Return true for both raw Clang AST files and object files which may
9417a6dacacSDimitry Andric   // contain a __clangast section.
9427a6dacacSDimitry Andric   if (Magic == llvm::file_magic::clang_ast)
9437a6dacacSDimitry Andric     return true;
9447a6dacacSDimitry Andric   Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
9457a6dacacSDimitry Andric       llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
9467a6dacacSDimitry Andric   return !Obj.takeError();
9475f757f3fSDimitry Andric }
9485f757f3fSDimitry Andric 
gchProbe(const Driver & D,StringRef Path)9495f757f3fSDimitry Andric static bool gchProbe(const Driver &D, StringRef Path) {
9505f757f3fSDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
9515f757f3fSDimitry Andric   if (!Status)
9525f757f3fSDimitry Andric     return false;
9535f757f3fSDimitry Andric 
9545f757f3fSDimitry Andric   if (Status->isDirectory()) {
9555f757f3fSDimitry Andric     std::error_code EC;
9565f757f3fSDimitry Andric     for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
9575f757f3fSDimitry Andric          !EC && DI != DE; DI = DI.increment(EC)) {
9587a6dacacSDimitry Andric       if (maybeHasClangPchSignature(D, DI->path()))
9595f757f3fSDimitry Andric         return true;
9605f757f3fSDimitry Andric     }
9615f757f3fSDimitry Andric     D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
9625f757f3fSDimitry Andric     return false;
9635f757f3fSDimitry Andric   }
9645f757f3fSDimitry Andric 
9657a6dacacSDimitry Andric   if (maybeHasClangPchSignature(D, Path))
9665f757f3fSDimitry Andric     return true;
9675f757f3fSDimitry Andric   D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
9685f757f3fSDimitry Andric   return false;
9695f757f3fSDimitry Andric }
9705f757f3fSDimitry Andric 
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const9710b57cec5SDimitry Andric void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
9720b57cec5SDimitry Andric                                     const Driver &D, const ArgList &Args,
9730b57cec5SDimitry Andric                                     ArgStringList &CmdArgs,
9740b57cec5SDimitry Andric                                     const InputInfo &Output,
9750b57cec5SDimitry Andric                                     const InputInfoList &Inputs) const {
9760b57cec5SDimitry Andric   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   CheckPreprocessingOptions(D, Args);
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_C);
9810b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_CC);
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   // Handle dependency file generation.
984a7dea167SDimitry Andric   Arg *ArgM = Args.getLastArg(options::OPT_MM);
985a7dea167SDimitry Andric   if (!ArgM)
986a7dea167SDimitry Andric     ArgM = Args.getLastArg(options::OPT_M);
987a7dea167SDimitry Andric   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
988a7dea167SDimitry Andric   if (!ArgMD)
989a7dea167SDimitry Andric     ArgMD = Args.getLastArg(options::OPT_MD);
990a7dea167SDimitry Andric 
991a7dea167SDimitry Andric   // -M and -MM imply -w.
992a7dea167SDimitry Andric   if (ArgM)
993a7dea167SDimitry Andric     CmdArgs.push_back("-w");
994a7dea167SDimitry Andric   else
995a7dea167SDimitry Andric     ArgM = ArgMD;
996a7dea167SDimitry Andric 
997a7dea167SDimitry Andric   if (ArgM) {
9980b57cec5SDimitry Andric     // Determine the output location.
9990b57cec5SDimitry Andric     const char *DepFile;
10000b57cec5SDimitry Andric     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
10010b57cec5SDimitry Andric       DepFile = MF->getValue();
10020b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10030b57cec5SDimitry Andric     } else if (Output.getType() == types::TY_Dependencies) {
10040b57cec5SDimitry Andric       DepFile = Output.getFilename();
1005a7dea167SDimitry Andric     } else if (!ArgMD) {
10060b57cec5SDimitry Andric       DepFile = "-";
10070b57cec5SDimitry Andric     } else {
10080b57cec5SDimitry Andric       DepFile = getDependencyFileName(Args, Inputs);
10090b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10100b57cec5SDimitry Andric     }
10110b57cec5SDimitry Andric     CmdArgs.push_back("-dependency-file");
10120b57cec5SDimitry Andric     CmdArgs.push_back(DepFile);
10130b57cec5SDimitry Andric 
1014a7dea167SDimitry Andric     bool HasTarget = false;
1015a7dea167SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1016a7dea167SDimitry Andric       HasTarget = true;
1017a7dea167SDimitry Andric       A->claim();
1018a7dea167SDimitry Andric       if (A->getOption().matches(options::OPT_MT)) {
1019a7dea167SDimitry Andric         A->render(Args, CmdArgs);
1020a7dea167SDimitry Andric       } else {
1021a7dea167SDimitry Andric         CmdArgs.push_back("-MT");
1022a7dea167SDimitry Andric         SmallString<128> Quoted;
1023753f127fSDimitry Andric         quoteMakeTarget(A->getValue(), Quoted);
1024a7dea167SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Quoted));
1025a7dea167SDimitry Andric       }
1026a7dea167SDimitry Andric     }
1027a7dea167SDimitry Andric 
10280b57cec5SDimitry Andric     // Add a default target if one wasn't specified.
1029a7dea167SDimitry Andric     if (!HasTarget) {
10300b57cec5SDimitry Andric       const char *DepTarget;
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric       // If user provided -o, that is the dependency target, except
10330b57cec5SDimitry Andric       // when we are only generating a dependency file.
10340fca6ea1SDimitry Andric       Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
10350b57cec5SDimitry Andric       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
10360b57cec5SDimitry Andric         DepTarget = OutputOpt->getValue();
10370b57cec5SDimitry Andric       } else {
10380b57cec5SDimitry Andric         // Otherwise derive from the base input.
10390b57cec5SDimitry Andric         //
10400b57cec5SDimitry Andric         // FIXME: This should use the computed output file location.
10410b57cec5SDimitry Andric         SmallString<128> P(Inputs[0].getBaseInput());
10420b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "o");
10430b57cec5SDimitry Andric         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
10440b57cec5SDimitry Andric       }
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric       CmdArgs.push_back("-MT");
10470b57cec5SDimitry Andric       SmallString<128> Quoted;
1048753f127fSDimitry Andric       quoteMakeTarget(DepTarget, Quoted);
10490b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Quoted));
10500b57cec5SDimitry Andric     }
10510b57cec5SDimitry Andric 
1052a7dea167SDimitry Andric     if (ArgM->getOption().matches(options::OPT_M) ||
1053a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MD))
10540b57cec5SDimitry Andric       CmdArgs.push_back("-sys-header-deps");
10550b57cec5SDimitry Andric     if ((isa<PrecompileJobAction>(JA) &&
10560b57cec5SDimitry Andric          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
10570b57cec5SDimitry Andric         Args.hasArg(options::OPT_fmodule_file_deps))
10580b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-deps");
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_MG)) {
1062a7dea167SDimitry Andric     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1063a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MMD))
10640b57cec5SDimitry Andric       D.Diag(diag::err_drv_mg_requires_m_or_mm);
10650b57cec5SDimitry Andric     CmdArgs.push_back("-MG");
10660b57cec5SDimitry Andric   }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MP);
10690b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MV);
10700b57cec5SDimitry Andric 
10715ffd83dbSDimitry Andric   // Add offload include arguments specific for CUDA/HIP.  This must happen
10725ffd83dbSDimitry Andric   // before we -I or -include anything else, because we must pick up the
10735ffd83dbSDimitry Andric   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
10745ffd83dbSDimitry Andric   // from e.g. /usr/local/include.
10750b57cec5SDimitry Andric   if (JA.isOffloading(Action::OFK_Cuda))
10760b57cec5SDimitry Andric     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
10775ffd83dbSDimitry Andric   if (JA.isOffloading(Action::OFK_HIP))
10785ffd83dbSDimitry Andric     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // If we are offloading to a target via OpenMP we need to include the
10810b57cec5SDimitry Andric   // openmp_wrappers folder which contains alternative system headers.
10820b57cec5SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
108381ad6265SDimitry Andric       !Args.hasArg(options::OPT_nostdinc) &&
1084bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
108569ade1e0SDimitry Andric       (getToolChain().getTriple().isNVPTX() ||
108669ade1e0SDimitry Andric        getToolChain().getTriple().isAMDGCN())) {
10870b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_nobuiltininc)) {
10880b57cec5SDimitry Andric       // Add openmp_wrappers/* to our system include path.  This lets us wrap
10890b57cec5SDimitry Andric       // standard library headers.
10900b57cec5SDimitry Andric       SmallString<128> P(D.ResourceDir);
10910b57cec5SDimitry Andric       llvm::sys::path::append(P, "include");
10920b57cec5SDimitry Andric       llvm::sys::path::append(P, "openmp_wrappers");
10930b57cec5SDimitry Andric       CmdArgs.push_back("-internal-isystem");
10940b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
10950b57cec5SDimitry Andric     }
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     CmdArgs.push_back("-include");
10985ffd83dbSDimitry Andric     CmdArgs.push_back("__clang_openmp_device_functions.h");
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   // Add -i* options, and automatically translate to
11020b57cec5SDimitry Andric   // -include-pch/-include-pth for transparent PCH support. It's
11030b57cec5SDimitry Andric   // wonky, but we include looking for .gch so we can support seamless
11040b57cec5SDimitry Andric   // replacement into a build system already set up to be generating
11050b57cec5SDimitry Andric   // .gch files.
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   if (getToolChain().getDriver().IsCLMode()) {
11080b57cec5SDimitry Andric     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
11090b57cec5SDimitry Andric     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
11100b57cec5SDimitry Andric     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
11110b57cec5SDimitry Andric         JA.getKind() <= Action::AssembleJobClass) {
11120b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1113f91b0c1cSDimitry Andric       // -fpch-instantiate-templates is the default when creating
1114f91b0c1cSDimitry Andric       // precomp using /Yc
1115f91b0c1cSDimitry Andric       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1116f91b0c1cSDimitry Andric                        options::OPT_fno_pch_instantiate_templates, true))
11175ffd83dbSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
11180b57cec5SDimitry Andric     }
11190b57cec5SDimitry Andric     if (YcArg || YuArg) {
11200b57cec5SDimitry Andric       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
11210b57cec5SDimitry Andric       if (!isa<PrecompileJobAction>(JA)) {
11220b57cec5SDimitry Andric         CmdArgs.push_back("-include-pch");
11230b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
11240b57cec5SDimitry Andric             C, !ThroughHeader.empty()
11250b57cec5SDimitry Andric                    ? ThroughHeader
11260b57cec5SDimitry Andric                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
11270b57cec5SDimitry Andric       }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric       if (ThroughHeader.empty()) {
11300b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
11310b57cec5SDimitry Andric             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
11320b57cec5SDimitry Andric       } else {
11330b57cec5SDimitry Andric         CmdArgs.push_back(
11340b57cec5SDimitry Andric             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
11350b57cec5SDimitry Andric       }
11360b57cec5SDimitry Andric     }
11370b57cec5SDimitry Andric   }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric   bool RenderedImplicitInclude = false;
11400b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
114181ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_include) &&
114281ad6265SDimitry Andric         D.getProbePrecompiled()) {
11430b57cec5SDimitry Andric       // Handling of gcc-style gch precompiled headers.
11440b57cec5SDimitry Andric       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
11450b57cec5SDimitry Andric       RenderedImplicitInclude = true;
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric       bool FoundPCH = false;
11480b57cec5SDimitry Andric       SmallString<128> P(A->getValue());
11490b57cec5SDimitry Andric       // We want the files to have a name like foo.h.pch. Add a dummy extension
11500b57cec5SDimitry Andric       // so that replace_extension does the right thing.
11510b57cec5SDimitry Andric       P += ".dummy";
11520b57cec5SDimitry Andric       llvm::sys::path::replace_extension(P, "pch");
115381ad6265SDimitry Andric       if (D.getVFS().exists(P))
11540b57cec5SDimitry Andric         FoundPCH = true;
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric       if (!FoundPCH) {
11575f757f3fSDimitry Andric         // For GCC compat, probe for a file or directory ending in .gch instead.
11580b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "gch");
11595f757f3fSDimitry Andric         FoundPCH = gchProbe(D, P.str());
11600b57cec5SDimitry Andric       }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric       if (FoundPCH) {
11630b57cec5SDimitry Andric         if (IsFirstImplicitInclude) {
11640b57cec5SDimitry Andric           A->claim();
11650b57cec5SDimitry Andric           CmdArgs.push_back("-include-pch");
11660b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(P));
11670b57cec5SDimitry Andric           continue;
11680b57cec5SDimitry Andric         } else {
11690b57cec5SDimitry Andric           // Ignore the PCH if not first on command line and emit warning.
11700b57cec5SDimitry Andric           D.Diag(diag::warn_drv_pch_not_first_include) << P
11710b57cec5SDimitry Andric                                                        << A->getAsString(Args);
11720b57cec5SDimitry Andric         }
11730b57cec5SDimitry Andric       }
11740b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_isystem_after)) {
11750b57cec5SDimitry Andric       // Handling of paths which must come late.  These entries are handled by
11760b57cec5SDimitry Andric       // the toolchain itself after the resource dir is inserted in the right
11770b57cec5SDimitry Andric       // search order.
11780b57cec5SDimitry Andric       // Do not claim the argument so that the use of the argument does not
11790b57cec5SDimitry Andric       // silently go unnoticed on toolchains which do not honour the option.
11800b57cec5SDimitry Andric       continue;
1181a7dea167SDimitry Andric     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1182a7dea167SDimitry Andric       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1183a7dea167SDimitry Andric       continue;
118406c3fb27SDimitry Andric     } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
118506c3fb27SDimitry Andric       // This is used only by the driver. No need to pass to cc1.
118606c3fb27SDimitry Andric       continue;
11870b57cec5SDimitry Andric     }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric     // Not translated, render as usual.
11900b57cec5SDimitry Andric     A->claim();
11910b57cec5SDimitry Andric     A->render(Args, CmdArgs);
11920b57cec5SDimitry Andric   }
11930b57cec5SDimitry Andric 
11945f757f3fSDimitry Andric   Args.addAllArgs(CmdArgs,
11950b57cec5SDimitry Andric                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
11960fca6ea1SDimitry Andric                    options::OPT_F, options::OPT_index_header_map,
11970fca6ea1SDimitry Andric                    options::OPT_embed_dir_EQ});
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   // Add -Wp, and -Xpreprocessor if using the preprocessor.
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   // FIXME: There is a very unfortunate problem here, some troubled
12020b57cec5SDimitry Andric   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
12030b57cec5SDimitry Andric   // really support that we would have to parse and then translate
12040b57cec5SDimitry Andric   // those options. :(
12050b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
12060b57cec5SDimitry Andric                        options::OPT_Xpreprocessor);
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   // -I- is a deprecated GCC feature, reject it.
12090b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_I_))
12100b57cec5SDimitry Andric     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
12130b57cec5SDimitry Andric   // -isysroot to the CC1 invocation.
12140b57cec5SDimitry Andric   StringRef sysroot = C.getSysRoot();
12150b57cec5SDimitry Andric   if (sysroot != "") {
12160b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_isysroot)) {
12170b57cec5SDimitry Andric       CmdArgs.push_back("-isysroot");
12180b57cec5SDimitry Andric       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
12190b57cec5SDimitry Andric     }
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   // Parse additional include paths from environment variables.
12230b57cec5SDimitry Andric   // FIXME: We should probably sink the logic for handling these from the
12240b57cec5SDimitry Andric   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
12250b57cec5SDimitry Andric   // CPATH - included following the user specified includes (but prior to
12260b57cec5SDimitry Andric   // builtin and standard includes).
12270b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
12280b57cec5SDimitry Andric   // C_INCLUDE_PATH - system includes enabled when compiling C.
12290b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
12300b57cec5SDimitry Andric   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
12310b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
12320b57cec5SDimitry Andric   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
12330b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
12340b57cec5SDimitry Andric   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
12350b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric   // While adding the include arguments, we also attempt to retrieve the
12380b57cec5SDimitry Andric   // arguments of related offloading toolchains or arguments that are specific
12390b57cec5SDimitry Andric   // of an offloading programming model.
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric   // Add C++ include arguments, if needed.
1242a7dea167SDimitry Andric   if (types::isCXX(Inputs[0].getType())) {
1243a7dea167SDimitry Andric     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1244a7dea167SDimitry Andric     forAllAssociatedToolChains(
1245a7dea167SDimitry Andric         C, JA, getToolChain(),
1246a7dea167SDimitry Andric         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1247a7dea167SDimitry Andric           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1248a7dea167SDimitry Andric                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
12490b57cec5SDimitry Andric         });
1250a7dea167SDimitry Andric   }
12510b57cec5SDimitry Andric 
12520fca6ea1SDimitry Andric   // If we are compiling for a GPU target we want to override the system headers
12530fca6ea1SDimitry Andric   // with ones created by the 'libc' project if present.
12540fca6ea1SDimitry Andric   // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
12550fca6ea1SDimitry Andric   //       OffloadKind as an argument.
12560fca6ea1SDimitry Andric   if (!Args.hasArg(options::OPT_nostdinc) &&
12570fca6ea1SDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
12580fca6ea1SDimitry Andric       !Args.hasArg(options::OPT_nobuiltininc)) {
12590fca6ea1SDimitry Andric     // Without an offloading language we will include these headers directly.
12600fca6ea1SDimitry Andric     // Offloading languages will instead only use the declarations stored in
12610fca6ea1SDimitry Andric     // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
12620fca6ea1SDimitry Andric     if ((getToolChain().getTriple().isNVPTX() ||
12630fca6ea1SDimitry Andric          getToolChain().getTriple().isAMDGCN()) &&
12640fca6ea1SDimitry Andric         C.getActiveOffloadKinds() == Action::OFK_None) {
12650fca6ea1SDimitry Andric       SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
12660fca6ea1SDimitry Andric       llvm::sys::path::append(P, "include");
12670fca6ea1SDimitry Andric       llvm::sys::path::append(P, getToolChain().getTripleString());
12680fca6ea1SDimitry Andric       CmdArgs.push_back("-internal-isystem");
12690fca6ea1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
12700fca6ea1SDimitry Andric     } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
12710fca6ea1SDimitry Andric       // TODO: CUDA / HIP include their own headers for some common functions
12720fca6ea1SDimitry Andric       // implemented here. We'll need to clean those up so they do not conflict.
12730fca6ea1SDimitry Andric       SmallString<128> P(D.ResourceDir);
12740fca6ea1SDimitry Andric       llvm::sys::path::append(P, "include");
12750fca6ea1SDimitry Andric       llvm::sys::path::append(P, "llvm_libc_wrappers");
12760fca6ea1SDimitry Andric       CmdArgs.push_back("-internal-isystem");
12770fca6ea1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
12780fca6ea1SDimitry Andric     }
12790fca6ea1SDimitry Andric   }
12800fca6ea1SDimitry Andric 
12810b57cec5SDimitry Andric   // Add system include arguments for all targets but IAMCU.
12820b57cec5SDimitry Andric   if (!IsIAMCU)
12830b57cec5SDimitry Andric     forAllAssociatedToolChains(C, JA, getToolChain(),
12840b57cec5SDimitry Andric                                [&Args, &CmdArgs](const ToolChain &TC) {
12850b57cec5SDimitry Andric                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
12860b57cec5SDimitry Andric                                });
12870b57cec5SDimitry Andric   else {
12880b57cec5SDimitry Andric     // For IAMCU add special include arguments.
12890b57cec5SDimitry Andric     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
12900b57cec5SDimitry Andric   }
1291480093f4SDimitry Andric 
1292480093f4SDimitry Andric   addMacroPrefixMapArg(D, Args, CmdArgs);
1293fe6060f1SDimitry Andric   addCoveragePrefixMapArg(D, Args, CmdArgs);
129481ad6265SDimitry Andric 
129581ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
129681ad6265SDimitry Andric                   options::OPT_fno_file_reproducible);
1297bdd1243dSDimitry Andric 
1298bdd1243dSDimitry Andric   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1299bdd1243dSDimitry Andric     CmdArgs.push_back("-source-date-epoch");
1300bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Epoch));
1301bdd1243dSDimitry Andric   }
13025f757f3fSDimitry Andric 
13035f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
13045f757f3fSDimitry Andric                     options::OPT_fno_define_target_os_macros);
13050b57cec5SDimitry Andric }
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)13080b57cec5SDimitry Andric static bool isSignedCharDefault(const llvm::Triple &Triple) {
13090b57cec5SDimitry Andric   switch (Triple.getArch()) {
13100b57cec5SDimitry Andric   default:
13110b57cec5SDimitry Andric     return true;
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1314480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
13150b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
13160b57cec5SDimitry Andric   case llvm::Triple::arm:
13170b57cec5SDimitry Andric   case llvm::Triple::armeb:
13180b57cec5SDimitry Andric   case llvm::Triple::thumb:
13190b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
13200b57cec5SDimitry Andric     if (Triple.isOSDarwin() || Triple.isOSWindows())
13210b57cec5SDimitry Andric       return true;
13220b57cec5SDimitry Andric     return false;
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric   case llvm::Triple::ppc:
13250b57cec5SDimitry Andric   case llvm::Triple::ppc64:
13260b57cec5SDimitry Andric     if (Triple.isOSDarwin())
13270b57cec5SDimitry Andric       return true;
13280b57cec5SDimitry Andric     return false;
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric   case llvm::Triple::hexagon:
1331e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
13320b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
13330b57cec5SDimitry Andric   case llvm::Triple::riscv32:
13340b57cec5SDimitry Andric   case llvm::Triple::riscv64:
13350b57cec5SDimitry Andric   case llvm::Triple::systemz:
13360b57cec5SDimitry Andric   case llvm::Triple::xcore:
13370b57cec5SDimitry Andric     return false;
13380b57cec5SDimitry Andric   }
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric 
hasMultipleInvocations(const llvm::Triple & Triple,const ArgList & Args)1341480093f4SDimitry Andric static bool hasMultipleInvocations(const llvm::Triple &Triple,
1342480093f4SDimitry Andric                                    const ArgList &Args) {
1343480093f4SDimitry Andric   // Supported only on Darwin where we invoke the compiler multiple times
1344480093f4SDimitry Andric   // followed by an invocation to lipo.
1345480093f4SDimitry Andric   if (!Triple.isOSDarwin())
1346480093f4SDimitry Andric     return false;
1347480093f4SDimitry Andric   // If more than one "-arch <arch>" is specified, we're targeting multiple
1348480093f4SDimitry Andric   // architectures resulting in a fat binary.
1349480093f4SDimitry Andric   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1350480093f4SDimitry Andric }
1351480093f4SDimitry Andric 
checkRemarksOptions(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)1352480093f4SDimitry Andric static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1353480093f4SDimitry Andric                                 const llvm::Triple &Triple) {
1354480093f4SDimitry Andric   // When enabling remarks, we need to error if:
1355480093f4SDimitry Andric   // * The remark file is specified but we're targeting multiple architectures,
1356480093f4SDimitry Andric   // which means more than one remark file is being generated.
1357480093f4SDimitry Andric   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1358480093f4SDimitry Andric   bool hasExplicitOutputFile =
1359480093f4SDimitry Andric       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1360480093f4SDimitry Andric   if (hasMultipleInvocations && hasExplicitOutputFile) {
1361480093f4SDimitry Andric     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1362480093f4SDimitry Andric         << "-foptimization-record-file";
1363480093f4SDimitry Andric     return false;
1364480093f4SDimitry Andric   }
1365480093f4SDimitry Andric   return true;
1366480093f4SDimitry Andric }
1367480093f4SDimitry Andric 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const JobAction & JA)1368480093f4SDimitry Andric static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1369480093f4SDimitry Andric                                  const llvm::Triple &Triple,
1370480093f4SDimitry Andric                                  const InputInfo &Input,
1371480093f4SDimitry Andric                                  const InputInfo &Output, const JobAction &JA) {
1372480093f4SDimitry Andric   StringRef Format = "yaml";
1373480093f4SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1374480093f4SDimitry Andric     Format = A->getValue();
1375480093f4SDimitry Andric 
1376480093f4SDimitry Andric   CmdArgs.push_back("-opt-record-file");
1377480093f4SDimitry Andric 
1378480093f4SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1379480093f4SDimitry Andric   if (A) {
1380480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1381480093f4SDimitry Andric   } else {
1382480093f4SDimitry Andric     bool hasMultipleArchs =
1383480093f4SDimitry Andric         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1384480093f4SDimitry Andric         Args.getAllArgValues(options::OPT_arch).size() > 1;
1385480093f4SDimitry Andric 
1386480093f4SDimitry Andric     SmallString<128> F;
1387480093f4SDimitry Andric 
1388480093f4SDimitry Andric     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1389480093f4SDimitry Andric       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1390480093f4SDimitry Andric         F = FinalOutput->getValue();
1391480093f4SDimitry Andric     } else {
1392480093f4SDimitry Andric       if (Format != "yaml" && // For YAML, keep the original behavior.
1393480093f4SDimitry Andric           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1394480093f4SDimitry Andric           Output.isFilename())
1395480093f4SDimitry Andric         F = Output.getFilename();
1396480093f4SDimitry Andric     }
1397480093f4SDimitry Andric 
1398480093f4SDimitry Andric     if (F.empty()) {
1399480093f4SDimitry Andric       // Use the input filename.
1400480093f4SDimitry Andric       F = llvm::sys::path::stem(Input.getBaseInput());
1401480093f4SDimitry Andric 
1402480093f4SDimitry Andric       // If we're compiling for an offload architecture (i.e. a CUDA device),
1403480093f4SDimitry Andric       // we need to make the file name for the device compilation different
1404480093f4SDimitry Andric       // from the host compilation.
1405480093f4SDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1406480093f4SDimitry Andric           !JA.isDeviceOffloading(Action::OFK_Host)) {
1407480093f4SDimitry Andric         llvm::sys::path::replace_extension(F, "");
1408480093f4SDimitry Andric         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1409480093f4SDimitry Andric                                                  Triple.normalize());
1410480093f4SDimitry Andric         F += "-";
1411480093f4SDimitry Andric         F += JA.getOffloadingArch();
1412480093f4SDimitry Andric       }
1413480093f4SDimitry Andric     }
1414480093f4SDimitry Andric 
1415480093f4SDimitry Andric     // If we're having more than one "-arch", we should name the files
1416480093f4SDimitry Andric     // differently so that every cc1 invocation writes to a different file.
1417480093f4SDimitry Andric     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1418480093f4SDimitry Andric     // name from the triple.
1419480093f4SDimitry Andric     if (hasMultipleArchs) {
1420480093f4SDimitry Andric       // First, remember the extension.
1421480093f4SDimitry Andric       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1422480093f4SDimitry Andric       // then, remove it.
1423480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, "");
1424480093f4SDimitry Andric       // attach -<arch> to it.
1425480093f4SDimitry Andric       F += "-";
1426480093f4SDimitry Andric       F += Triple.getArchName();
1427480093f4SDimitry Andric       // put back the extension.
1428480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, OldExtension);
1429480093f4SDimitry Andric     }
1430480093f4SDimitry Andric 
1431480093f4SDimitry Andric     SmallString<32> Extension;
1432480093f4SDimitry Andric     Extension += "opt.";
1433480093f4SDimitry Andric     Extension += Format;
1434480093f4SDimitry Andric 
1435480093f4SDimitry Andric     llvm::sys::path::replace_extension(F, Extension);
1436480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(F));
1437480093f4SDimitry Andric   }
1438480093f4SDimitry Andric 
1439480093f4SDimitry Andric   if (const Arg *A =
1440480093f4SDimitry Andric           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1441480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-passes");
1442480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1443480093f4SDimitry Andric   }
1444480093f4SDimitry Andric 
1445480093f4SDimitry Andric   if (!Format.empty()) {
1446480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-format");
1447480093f4SDimitry Andric     CmdArgs.push_back(Format.data());
1448480093f4SDimitry Andric   }
1449480093f4SDimitry Andric }
1450480093f4SDimitry Andric 
AddAAPCSVolatileBitfieldArgs(const ArgList & Args,ArgStringList & CmdArgs)1451fe6060f1SDimitry Andric void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1452fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1453fe6060f1SDimitry Andric                     options::OPT_fno_aapcs_bitfield_width, true))
1454fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1455fe6060f1SDimitry Andric 
1456fe6060f1SDimitry Andric   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1457fe6060f1SDimitry Andric     CmdArgs.push_back("-faapcs-bitfield-load");
1458fe6060f1SDimitry Andric }
1459fe6060f1SDimitry Andric 
14600b57cec5SDimitry Andric namespace {
RenderARMABI(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1461349cc55cSDimitry Andric void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1462349cc55cSDimitry Andric                   const ArgList &Args, ArgStringList &CmdArgs) {
14630b57cec5SDimitry Andric   // Select the ABI to use.
14640b57cec5SDimitry Andric   // FIXME: Support -meabi.
14650b57cec5SDimitry Andric   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
14660b57cec5SDimitry Andric   const char *ABIName = nullptr;
14670b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
14680b57cec5SDimitry Andric     ABIName = A->getValue();
14690b57cec5SDimitry Andric   } else {
1470349cc55cSDimitry Andric     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
14710b57cec5SDimitry Andric     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
14720b57cec5SDimitry Andric   }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
14750b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
14760b57cec5SDimitry Andric }
147781ad6265SDimitry Andric 
AddUnalignedAccessWarning(ArgStringList & CmdArgs)147881ad6265SDimitry Andric void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
147981ad6265SDimitry Andric   auto StrictAlignIter =
1480bdd1243dSDimitry Andric       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
148181ad6265SDimitry Andric         return Arg == "+strict-align" || Arg == "-strict-align";
148281ad6265SDimitry Andric       });
148381ad6265SDimitry Andric   if (StrictAlignIter != CmdArgs.rend() &&
148481ad6265SDimitry Andric       StringRef(*StrictAlignIter) == "+strict-align")
148581ad6265SDimitry Andric     CmdArgs.push_back("-Wunaligned-access");
148681ad6265SDimitry Andric }
14870b57cec5SDimitry Andric }
14880b57cec5SDimitry Andric 
14890fca6ea1SDimitry Andric // Each combination of options here forms a signing schema, and in most cases
14900fca6ea1SDimitry Andric // each signing schema is its own incompatible ABI. The default values of the
14910fca6ea1SDimitry Andric // options represent the default signing schema.
handlePAuthABI(const ArgList & DriverArgs,ArgStringList & CC1Args)14920fca6ea1SDimitry Andric static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args) {
14930fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
14940fca6ea1SDimitry Andric                          options::OPT_fno_ptrauth_intrinsics))
14950fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-intrinsics");
14960fca6ea1SDimitry Andric 
14970fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
14980fca6ea1SDimitry Andric                          options::OPT_fno_ptrauth_calls))
14990fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-calls");
15000fca6ea1SDimitry Andric 
15010fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
15020fca6ea1SDimitry Andric                          options::OPT_fno_ptrauth_returns))
15030fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-returns");
15040fca6ea1SDimitry Andric 
15050fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
15060fca6ea1SDimitry Andric                          options::OPT_fno_ptrauth_auth_traps))
15070fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-auth-traps");
15080fca6ea1SDimitry Andric 
15090fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(
15100fca6ea1SDimitry Andric           options::OPT_fptrauth_vtable_pointer_address_discrimination,
15110fca6ea1SDimitry Andric           options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
15120fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
15130fca6ea1SDimitry Andric 
15140fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(
15150fca6ea1SDimitry Andric           options::OPT_fptrauth_vtable_pointer_type_discrimination,
15160fca6ea1SDimitry Andric           options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
15170fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
15180fca6ea1SDimitry Andric 
151936b606aeSDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
152036b606aeSDimitry Andric                          options::OPT_fno_ptrauth_indirect_gotos))
152136b606aeSDimitry Andric     CC1Args.push_back("-fptrauth-indirect-gotos");
152236b606aeSDimitry Andric 
15230fca6ea1SDimitry Andric   if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
15240fca6ea1SDimitry Andric                          options::OPT_fno_ptrauth_init_fini))
15250fca6ea1SDimitry Andric     CC1Args.push_back("-fptrauth-init-fini");
15260fca6ea1SDimitry Andric }
15270fca6ea1SDimitry Andric 
CollectARMPACBTIOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool isAArch64)15281fd87a68SDimitry Andric static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
15294824e7fdSDimitry Andric                                     ArgStringList &CmdArgs, bool isAArch64) {
15304824e7fdSDimitry Andric   const Arg *A = isAArch64
15314824e7fdSDimitry Andric                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
15324824e7fdSDimitry Andric                                        options::OPT_mbranch_protection_EQ)
15334824e7fdSDimitry Andric                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
15344824e7fdSDimitry Andric   if (!A)
15354824e7fdSDimitry Andric     return;
15364824e7fdSDimitry Andric 
15371fd87a68SDimitry Andric   const Driver &D = TC.getDriver();
15381fd87a68SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
15391fd87a68SDimitry Andric   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1540d56accc7SDimitry Andric     D.Diag(diag::warn_incompatible_branch_protection_option)
15411fd87a68SDimitry Andric         << Triple.getArchName();
15421fd87a68SDimitry Andric 
15434824e7fdSDimitry Andric   StringRef Scope, Key;
1544297eecfbSDimitry Andric   bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
15454824e7fdSDimitry Andric 
15464824e7fdSDimitry Andric   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
15474824e7fdSDimitry Andric     Scope = A->getValue();
154881ad6265SDimitry Andric     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
154981ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1550bdd1243dSDimitry Andric           << A->getSpelling() << Scope;
15514824e7fdSDimitry Andric     Key = "a_key";
15524824e7fdSDimitry Andric     IndirectBranches = false;
1553cb14a3feSDimitry Andric     BranchProtectionPAuthLR = false;
1554297eecfbSDimitry Andric     GuardedControlStack = false;
15554824e7fdSDimitry Andric   } else {
15564824e7fdSDimitry Andric     StringRef DiagMsg;
15574824e7fdSDimitry Andric     llvm::ARM::ParsedBranchProtection PBP;
15580fca6ea1SDimitry Andric     bool EnablePAuthLR = false;
15590fca6ea1SDimitry Andric 
15600fca6ea1SDimitry Andric     // To know if we need to enable PAuth-LR As part of the standard branch
15610fca6ea1SDimitry Andric     // protection option, it needs to be determined if the feature has been
15620fca6ea1SDimitry Andric     // activated in the `march` argument. This information is stored within the
15630fca6ea1SDimitry Andric     // CmdArgs variable and can be found using a search.
15640fca6ea1SDimitry Andric     if (isAArch64) {
15650fca6ea1SDimitry Andric       auto isPAuthLR = [](const char *member) {
15660fca6ea1SDimitry Andric         llvm::AArch64::ExtensionInfo pauthlr_extension =
15670fca6ea1SDimitry Andric             llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
15680fca6ea1SDimitry Andric         return pauthlr_extension.PosTargetFeature == member;
15690fca6ea1SDimitry Andric       };
15700fca6ea1SDimitry Andric 
15710fca6ea1SDimitry Andric       if (std::any_of(CmdArgs.begin(), CmdArgs.end(), isPAuthLR))
15720fca6ea1SDimitry Andric         EnablePAuthLR = true;
15730fca6ea1SDimitry Andric     }
15740fca6ea1SDimitry Andric     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
15750fca6ea1SDimitry Andric                                           EnablePAuthLR))
157681ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1577bdd1243dSDimitry Andric           << A->getSpelling() << DiagMsg;
15784824e7fdSDimitry Andric     if (!isAArch64 && PBP.Key == "b_key")
15794824e7fdSDimitry Andric       D.Diag(diag::warn_unsupported_branch_protection)
15804824e7fdSDimitry Andric           << "b-key" << A->getAsString(Args);
15814824e7fdSDimitry Andric     Scope = PBP.Scope;
15824824e7fdSDimitry Andric     Key = PBP.Key;
1583cb14a3feSDimitry Andric     BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
15844824e7fdSDimitry Andric     IndirectBranches = PBP.BranchTargetEnforcement;
1585297eecfbSDimitry Andric     GuardedControlStack = PBP.GuardedControlStack;
15864824e7fdSDimitry Andric   }
15874824e7fdSDimitry Andric 
15884824e7fdSDimitry Andric   CmdArgs.push_back(
15894824e7fdSDimitry Andric       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
15900fca6ea1SDimitry Andric   if (Scope != "none") {
15910fca6ea1SDimitry Andric     if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
15920fca6ea1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
15930fca6ea1SDimitry Andric           << A->getAsString(Args) << Triple.getTriple();
15944824e7fdSDimitry Andric     CmdArgs.push_back(
15954824e7fdSDimitry Andric         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
15960fca6ea1SDimitry Andric   }
15970fca6ea1SDimitry Andric   if (BranchProtectionPAuthLR) {
15980fca6ea1SDimitry Andric     if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
15990fca6ea1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
16000fca6ea1SDimitry Andric           << A->getAsString(Args) << Triple.getTriple();
1601cb14a3feSDimitry Andric     CmdArgs.push_back(
1602cb14a3feSDimitry Andric         Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
16030fca6ea1SDimitry Andric   }
16044824e7fdSDimitry Andric   if (IndirectBranches)
16054824e7fdSDimitry Andric     CmdArgs.push_back("-mbranch-target-enforce");
16060fca6ea1SDimitry Andric   // GCS is currently untested with PAuthABI, but enabling this could be allowed
16070fca6ea1SDimitry Andric   // in future after testing with a suitable system.
16080fca6ea1SDimitry Andric   if (GuardedControlStack) {
16090fca6ea1SDimitry Andric     if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
16100fca6ea1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
16110fca6ea1SDimitry Andric           << A->getAsString(Args) << Triple.getTriple();
1612297eecfbSDimitry Andric     CmdArgs.push_back("-mguarded-control-stack");
16134824e7fdSDimitry Andric   }
16140fca6ea1SDimitry Andric }
16154824e7fdSDimitry Andric 
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const16160b57cec5SDimitry Andric void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
16170b57cec5SDimitry Andric                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1618349cc55cSDimitry Andric   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric   // Determine floating point ABI from the options & target defaults.
16210b57cec5SDimitry Andric   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
16220b57cec5SDimitry Andric   if (ABI == arm::FloatABI::Soft) {
16230b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
16240b57cec5SDimitry Andric     // FIXME: This changes CPP defines, we need -target-soft-float.
16250b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
16260b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
16270b57cec5SDimitry Andric     CmdArgs.push_back("soft");
16280b57cec5SDimitry Andric   } else if (ABI == arm::FloatABI::SoftFP) {
16290b57cec5SDimitry Andric     // Floating point operations are hard, but argument passing is soft.
16300b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
16310b57cec5SDimitry Andric     CmdArgs.push_back("soft");
16320b57cec5SDimitry Andric   } else {
16330b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
16340b57cec5SDimitry Andric     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
16350b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
16360b57cec5SDimitry Andric     CmdArgs.push_back("hard");
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
16400b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
16410b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
16420b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
16430b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
16440b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=false");
16450b57cec5SDimitry Andric     else
16460b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=true");
16470b57cec5SDimitry Andric   }
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
16500b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
16510b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mcmse))
16540b57cec5SDimitry Andric     CmdArgs.push_back("-mcmse");
1655fe6060f1SDimitry Andric 
1656fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
16574824e7fdSDimitry Andric 
16584824e7fdSDimitry Andric   // Enable/disable return address signing and indirect branch targets.
16591fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
166081ad6265SDimitry Andric 
166181ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
16620b57cec5SDimitry Andric }
16630b57cec5SDimitry Andric 
RenderTargetOptions(const llvm::Triple & EffectiveTriple,const ArgList & Args,bool KernelOrKext,ArgStringList & CmdArgs) const16640b57cec5SDimitry Andric void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
16650b57cec5SDimitry Andric                                 const ArgList &Args, bool KernelOrKext,
16660b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
16670b57cec5SDimitry Andric   const ToolChain &TC = getToolChain();
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   // Add the target features
16705ffd83dbSDimitry Andric   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   // Add target specific flags.
16730b57cec5SDimitry Andric   switch (TC.getArch()) {
16740b57cec5SDimitry Andric   default:
16750b57cec5SDimitry Andric     break;
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   case llvm::Triple::arm:
16780b57cec5SDimitry Andric   case llvm::Triple::armeb:
16790b57cec5SDimitry Andric   case llvm::Triple::thumb:
16800b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
16810b57cec5SDimitry Andric     // Use the effective triple, which takes into account the deployment target.
16820b57cec5SDimitry Andric     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
16830b57cec5SDimitry Andric     break;
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1686480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
16870b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
16880b57cec5SDimitry Andric     AddAArch64TargetArgs(Args, CmdArgs);
1689bdd1243dSDimitry Andric     break;
1690bdd1243dSDimitry Andric 
1691bdd1243dSDimitry Andric   case llvm::Triple::loongarch32:
1692bdd1243dSDimitry Andric   case llvm::Triple::loongarch64:
1693bdd1243dSDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
16940b57cec5SDimitry Andric     break;
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   case llvm::Triple::mips:
16970b57cec5SDimitry Andric   case llvm::Triple::mipsel:
16980b57cec5SDimitry Andric   case llvm::Triple::mips64:
16990b57cec5SDimitry Andric   case llvm::Triple::mips64el:
17000b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
17010b57cec5SDimitry Andric     break;
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   case llvm::Triple::ppc:
1704e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
17050b57cec5SDimitry Andric   case llvm::Triple::ppc64:
17060b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
17070b57cec5SDimitry Andric     AddPPCTargetArgs(Args, CmdArgs);
17080b57cec5SDimitry Andric     break;
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric   case llvm::Triple::riscv32:
17110b57cec5SDimitry Andric   case llvm::Triple::riscv64:
17120b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
17130b57cec5SDimitry Andric     break;
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   case llvm::Triple::sparc:
17160b57cec5SDimitry Andric   case llvm::Triple::sparcel:
17170b57cec5SDimitry Andric   case llvm::Triple::sparcv9:
17180b57cec5SDimitry Andric     AddSparcTargetArgs(Args, CmdArgs);
17190b57cec5SDimitry Andric     break;
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   case llvm::Triple::systemz:
17220b57cec5SDimitry Andric     AddSystemZTargetArgs(Args, CmdArgs);
17230b57cec5SDimitry Andric     break;
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric   case llvm::Triple::x86:
17260b57cec5SDimitry Andric   case llvm::Triple::x86_64:
17270b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
17280b57cec5SDimitry Andric     break;
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric   case llvm::Triple::lanai:
17310b57cec5SDimitry Andric     AddLanaiTargetArgs(Args, CmdArgs);
17320b57cec5SDimitry Andric     break;
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric   case llvm::Triple::hexagon:
17350b57cec5SDimitry Andric     AddHexagonTargetArgs(Args, CmdArgs);
17360b57cec5SDimitry Andric     break;
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   case llvm::Triple::wasm32:
17390b57cec5SDimitry Andric   case llvm::Triple::wasm64:
17400b57cec5SDimitry Andric     AddWebAssemblyTargetArgs(Args, CmdArgs);
17410b57cec5SDimitry Andric     break;
17425ffd83dbSDimitry Andric 
17435ffd83dbSDimitry Andric   case llvm::Triple::ve:
17445ffd83dbSDimitry Andric     AddVETargetArgs(Args, CmdArgs);
17455ffd83dbSDimitry Andric     break;
17460b57cec5SDimitry Andric   }
17470b57cec5SDimitry Andric }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric namespace {
RenderAArch64ABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)17500b57cec5SDimitry Andric void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
17510b57cec5SDimitry Andric                       ArgStringList &CmdArgs) {
17520b57cec5SDimitry Andric   const char *ABIName = nullptr;
17530b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
17540b57cec5SDimitry Andric     ABIName = A->getValue();
17550b57cec5SDimitry Andric   else if (Triple.isOSDarwin())
17560b57cec5SDimitry Andric     ABIName = "darwinpcs";
17570fca6ea1SDimitry Andric   else if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
17580fca6ea1SDimitry Andric     ABIName = "pauthtest";
17590b57cec5SDimitry Andric   else
17600b57cec5SDimitry Andric     ABIName = "aapcs";
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
17630b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric }
17660b57cec5SDimitry Andric 
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const17670b57cec5SDimitry Andric void Clang::AddAArch64TargetArgs(const ArgList &Args,
17680b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
17690b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
17720b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
17730b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
17740b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
17770b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
17780b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   RenderAArch64ABI(Triple, Args, CmdArgs);
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
17830b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
17840b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
17850b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
17860b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
17870b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=false");
17880b57cec5SDimitry Andric     else
17890b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=true");
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Enable/disable return address signing and indirect branch targets.
17931fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1794e8d8bef9SDimitry Andric 
17950fca6ea1SDimitry Andric   if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
17960fca6ea1SDimitry Andric     handlePAuthABI(Args, CmdArgs);
17970fca6ea1SDimitry Andric 
1798e8d8bef9SDimitry Andric   // Handle -msve_vector_bits=<bits>
1799e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1800e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
1801e8d8bef9SDimitry Andric     const Driver &D = getToolChain().getDriver();
18020fca6ea1SDimitry Andric     if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
18030fca6ea1SDimitry Andric         Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
18040fca6ea1SDimitry Andric         Val == "1024+" || Val == "2048+") {
1805349cc55cSDimitry Andric       unsigned Bits = 0;
18060fca6ea1SDimitry Andric       if (!Val.consume_back("+")) {
1807349cc55cSDimitry Andric         bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1808349cc55cSDimitry Andric         assert(!Invalid && "Failed to parse value");
1809e8d8bef9SDimitry Andric         CmdArgs.push_back(
1810349cc55cSDimitry Andric             Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1811349cc55cSDimitry Andric       }
1812349cc55cSDimitry Andric 
1813349cc55cSDimitry Andric       bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1814349cc55cSDimitry Andric       assert(!Invalid && "Failed to parse value");
1815349cc55cSDimitry Andric       CmdArgs.push_back(
1816349cc55cSDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1817e8d8bef9SDimitry Andric     // Silently drop requests for vector-length agnostic code as it's implied.
18180fca6ea1SDimitry Andric     } else if (Val != "scalable")
1819e8d8bef9SDimitry Andric       // Handle the unsupported values passed to msve-vector-bits.
1820e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1821bdd1243dSDimitry Andric           << A->getSpelling() << Val;
1822e8d8bef9SDimitry Andric   }
1823fe6060f1SDimitry Andric 
1824fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1825349cc55cSDimitry Andric 
1826349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1827349cc55cSDimitry Andric     CmdArgs.push_back("-tune-cpu");
1828fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
1829fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1830fcaf7f86SDimitry Andric     else
1831fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
1832349cc55cSDimitry Andric   }
183381ad6265SDimitry Andric 
183481ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
18350fca6ea1SDimitry Andric 
18360fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
18370fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_intrinsics);
18380fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
18390fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_calls);
18400fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
18410fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_returns);
18420fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
18430fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_auth_traps);
18440fca6ea1SDimitry Andric   Args.addOptInFlag(
18450fca6ea1SDimitry Andric       CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
18460fca6ea1SDimitry Andric       options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
18470fca6ea1SDimitry Andric   Args.addOptInFlag(
18480fca6ea1SDimitry Andric       CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
18490fca6ea1SDimitry Andric       options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
185052418fc2SDimitry Andric   Args.addOptInFlag(
185152418fc2SDimitry Andric       CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
185252418fc2SDimitry Andric       options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
18530fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
18540fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_init_fini);
18550fca6ea1SDimitry Andric   Args.addOptInFlag(
18560fca6ea1SDimitry Andric       CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
18570fca6ea1SDimitry Andric       options::OPT_fno_ptrauth_function_pointer_type_discrimination);
18580fca6ea1SDimitry Andric 
18590fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
18600fca6ea1SDimitry Andric                     options::OPT_fno_ptrauth_indirect_gotos);
18610b57cec5SDimitry Andric }
18620b57cec5SDimitry Andric 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1863bdd1243dSDimitry Andric void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1864bdd1243dSDimitry Andric                                    ArgStringList &CmdArgs) const {
18658a4dda33SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
18668a4dda33SDimitry Andric 
1867bdd1243dSDimitry Andric   CmdArgs.push_back("-target-abi");
18688a4dda33SDimitry Andric   CmdArgs.push_back(
18698a4dda33SDimitry Andric       loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1870bdd1243dSDimitry Andric           .data());
18718a4dda33SDimitry Andric 
18728a4dda33SDimitry Andric   // Handle -mtune.
18738a4dda33SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
18748a4dda33SDimitry Andric     std::string TuneCPU = A->getValue();
18758a4dda33SDimitry Andric     TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
18768a4dda33SDimitry Andric     CmdArgs.push_back("-tune-cpu");
18778a4dda33SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
18788a4dda33SDimitry Andric   }
1879bdd1243dSDimitry Andric }
1880bdd1243dSDimitry Andric 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const18810b57cec5SDimitry Andric void Clang::AddMIPSTargetArgs(const ArgList &Args,
18820b57cec5SDimitry Andric                               ArgStringList &CmdArgs) const {
18830b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
18840b57cec5SDimitry Andric   StringRef CPUName;
18850b57cec5SDimitry Andric   StringRef ABIName;
18860b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
18870b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
18900b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
18930b57cec5SDimitry Andric   if (ABI == mips::FloatABI::Soft) {
18940b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
18950b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
18960b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
18970b57cec5SDimitry Andric     CmdArgs.push_back("soft");
18980b57cec5SDimitry Andric   } else {
18990b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
19000b57cec5SDimitry Andric     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
19010b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
19020b57cec5SDimitry Andric     CmdArgs.push_back("hard");
19030b57cec5SDimitry Andric   }
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
19060b57cec5SDimitry Andric                                options::OPT_mno_ldc1_sdc1)) {
19070b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
19080b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19090b57cec5SDimitry Andric       CmdArgs.push_back("-mno-ldc1-sdc1");
19100b57cec5SDimitry Andric     }
19110b57cec5SDimitry Andric   }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
19140b57cec5SDimitry Andric                                options::OPT_mno_check_zero_division)) {
19150b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
19160b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19170b57cec5SDimitry Andric       CmdArgs.push_back("-mno-check-zero-division");
19180b57cec5SDimitry Andric     }
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric 
192104eeddc0SDimitry Andric   if (Args.getLastArg(options::OPT_mfix4300)) {
192204eeddc0SDimitry Andric     CmdArgs.push_back("-mllvm");
192304eeddc0SDimitry Andric     CmdArgs.push_back("-mfix4300");
192404eeddc0SDimitry Andric   }
192504eeddc0SDimitry Andric 
19260b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_G)) {
19270b57cec5SDimitry Andric     StringRef v = A->getValue();
19280b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
19290b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
19300b57cec5SDimitry Andric     A->claim();
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
19340b57cec5SDimitry Andric   Arg *ABICalls =
19350b57cec5SDimitry Andric       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
19380b57cec5SDimitry Andric   // -mgpopt is the default for static, -fno-pic environments but these two
19390b57cec5SDimitry Andric   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
19400b57cec5SDimitry Andric   // the only case where -mllvm -mgpopt is passed.
19410b57cec5SDimitry Andric   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
19420b57cec5SDimitry Andric   //       passed explicitly when compiling something with -mabicalls
19430b57cec5SDimitry Andric   //       (implictly) in affect. Currently the warning is in the backend.
19440b57cec5SDimitry Andric   //
19450b57cec5SDimitry Andric   // When the ABI in use is  N64, we also need to determine the PIC mode that
19460b57cec5SDimitry Andric   // is in use, as -fno-pic for N64 implies -mno-abicalls.
19470b57cec5SDimitry Andric   bool NoABICalls =
19480b57cec5SDimitry Andric       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
19510b57cec5SDimitry Andric   unsigned PICLevel;
19520b57cec5SDimitry Andric   bool IsPIE;
19530b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
19540b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric   NoABICalls = NoABICalls ||
19570b57cec5SDimitry Andric                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
19600b57cec5SDimitry Andric   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
19610b57cec5SDimitry Andric   if (NoABICalls && (!GPOpt || WantGPOpt)) {
19620b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
19630b57cec5SDimitry Andric     CmdArgs.push_back("-mgpopt");
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
19660b57cec5SDimitry Andric                                       options::OPT_mno_local_sdata);
19670b57cec5SDimitry Andric     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
19680b57cec5SDimitry Andric                                        options::OPT_mno_extern_sdata);
19690b57cec5SDimitry Andric     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
19700b57cec5SDimitry Andric                                         options::OPT_mno_embedded_data);
19710b57cec5SDimitry Andric     if (LocalSData) {
19720b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19730b57cec5SDimitry Andric       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
19740b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=1");
19750b57cec5SDimitry Andric       } else {
19760b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=0");
19770b57cec5SDimitry Andric       }
19780b57cec5SDimitry Andric       LocalSData->claim();
19790b57cec5SDimitry Andric     }
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric     if (ExternSData) {
19820b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19830b57cec5SDimitry Andric       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
19840b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=1");
19850b57cec5SDimitry Andric       } else {
19860b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=0");
19870b57cec5SDimitry Andric       }
19880b57cec5SDimitry Andric       ExternSData->claim();
19890b57cec5SDimitry Andric     }
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric     if (EmbeddedData) {
19920b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19930b57cec5SDimitry Andric       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
19940b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=1");
19950b57cec5SDimitry Andric       } else {
19960b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=0");
19970b57cec5SDimitry Andric       }
19980b57cec5SDimitry Andric       EmbeddedData->claim();
19990b57cec5SDimitry Andric     }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
20020b57cec5SDimitry Andric     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric   if (GPOpt)
20050b57cec5SDimitry Andric     GPOpt->claim();
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
20080b57cec5SDimitry Andric     StringRef Val = StringRef(A->getValue());
20090b57cec5SDimitry Andric     if (mips::hasCompactBranches(CPUName)) {
20100b57cec5SDimitry Andric       if (Val == "never" || Val == "always" || Val == "optimal") {
20110b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
20120b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
20130b57cec5SDimitry Andric       } else
20140b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2015bdd1243dSDimitry Andric             << A->getSpelling() << Val;
20160b57cec5SDimitry Andric     } else
20170b57cec5SDimitry Andric       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
20180b57cec5SDimitry Andric   }
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
20210b57cec5SDimitry Andric                                options::OPT_mno_relax_pic_calls)) {
20220b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
20230b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
20240b57cec5SDimitry Andric       CmdArgs.push_back("-mips-jalr-reloc=0");
20250b57cec5SDimitry Andric     }
20260b57cec5SDimitry Andric   }
20270b57cec5SDimitry Andric }
20280b57cec5SDimitry Andric 
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const20290b57cec5SDimitry Andric void Clang::AddPPCTargetArgs(const ArgList &Args,
20300b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
203106c3fb27SDimitry Andric   const Driver &D = getToolChain().getDriver();
20321ac55f4cSDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
203306c3fb27SDimitry Andric   if (Args.getLastArg(options::OPT_mtune_EQ)) {
2034bdd1243dSDimitry Andric     CmdArgs.push_back("-tune-cpu");
20351ac55f4cSDimitry Andric     std::string CPU = ppc::getPPCTuneCPU(Args, T);
20361ac55f4cSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
2037bdd1243dSDimitry Andric   }
2038bdd1243dSDimitry Andric 
20390b57cec5SDimitry Andric   // Select the ABI to use.
20400b57cec5SDimitry Andric   const char *ABIName = nullptr;
2041480093f4SDimitry Andric   if (T.isOSBinFormatELF()) {
20420b57cec5SDimitry Andric     switch (getToolChain().getArch()) {
20430b57cec5SDimitry Andric     case llvm::Triple::ppc64: {
20441ac55f4cSDimitry Andric       if (T.isPPC64ELFv2ABI())
2045480093f4SDimitry Andric         ABIName = "elfv2";
2046480093f4SDimitry Andric       else
20470b57cec5SDimitry Andric         ABIName = "elfv1";
20480b57cec5SDimitry Andric       break;
20490b57cec5SDimitry Andric     }
20500b57cec5SDimitry Andric     case llvm::Triple::ppc64le:
20510b57cec5SDimitry Andric       ABIName = "elfv2";
20520b57cec5SDimitry Andric       break;
20530b57cec5SDimitry Andric     default:
20540b57cec5SDimitry Andric       break;
20550b57cec5SDimitry Andric     }
2056480093f4SDimitry Andric   }
20570b57cec5SDimitry Andric 
205804eeddc0SDimitry Andric   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
205906c3fb27SDimitry Andric   bool VecExtabi = false;
20600b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
20610b57cec5SDimitry Andric     StringRef V = A->getValue();
206206c3fb27SDimitry Andric     if (V == "ieeelongdouble") {
20630b57cec5SDimitry Andric       IEEELongDouble = true;
206406c3fb27SDimitry Andric       A->claim();
206506c3fb27SDimitry Andric     } else if (V == "ibmlongdouble") {
20660b57cec5SDimitry Andric       IEEELongDouble = false;
206706c3fb27SDimitry Andric       A->claim();
206806c3fb27SDimitry Andric     } else if (V == "vec-default") {
206906c3fb27SDimitry Andric       VecExtabi = false;
207006c3fb27SDimitry Andric       A->claim();
207106c3fb27SDimitry Andric     } else if (V == "vec-extabi") {
207206c3fb27SDimitry Andric       VecExtabi = true;
207306c3fb27SDimitry Andric       A->claim();
20748a4dda33SDimitry Andric     } else if (V == "elfv1") {
20758a4dda33SDimitry Andric       ABIName = "elfv1";
20768a4dda33SDimitry Andric       A->claim();
20778a4dda33SDimitry Andric     } else if (V == "elfv2") {
20788a4dda33SDimitry Andric       ABIName = "elfv2";
20798a4dda33SDimitry Andric       A->claim();
208006c3fb27SDimitry Andric     } else if (V != "altivec")
20810b57cec5SDimitry Andric       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
20820b57cec5SDimitry Andric       // the option if given as we don't have backend support for any targets
20830b57cec5SDimitry Andric       // that don't use the altivec abi.
20840b57cec5SDimitry Andric       ABIName = A->getValue();
20850b57cec5SDimitry Andric   }
20860b57cec5SDimitry Andric   if (IEEELongDouble)
20870b57cec5SDimitry Andric     CmdArgs.push_back("-mabi=ieeelongdouble");
208806c3fb27SDimitry Andric   if (VecExtabi) {
208906c3fb27SDimitry Andric     if (!T.isOSAIX())
209006c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
209106c3fb27SDimitry Andric           << "-mabi=vec-extabi" << T.str();
209206c3fb27SDimitry Andric     CmdArgs.push_back("-mabi=vec-extabi");
209306c3fb27SDimitry Andric   }
20940b57cec5SDimitry Andric 
209506c3fb27SDimitry Andric   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
20960b57cec5SDimitry Andric   if (FloatABI == ppc::FloatABI::Soft) {
20970b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
20980b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
20990b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21000b57cec5SDimitry Andric     CmdArgs.push_back("soft");
21010b57cec5SDimitry Andric   } else {
21020b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
21030b57cec5SDimitry Andric     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
21040b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21050b57cec5SDimitry Andric     CmdArgs.push_back("hard");
21060b57cec5SDimitry Andric   }
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   if (ABIName) {
21090b57cec5SDimitry Andric     CmdArgs.push_back("-target-abi");
21100b57cec5SDimitry Andric     CmdArgs.push_back(ABIName);
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric }
21130b57cec5SDimitry Andric 
SetRISCVSmallDataLimit(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)21145ffd83dbSDimitry Andric static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
21155ffd83dbSDimitry Andric                                    ArgStringList &CmdArgs) {
21165ffd83dbSDimitry Andric   const Driver &D = TC.getDriver();
21175ffd83dbSDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
21185ffd83dbSDimitry Andric   // Default small data limitation is eight.
21195ffd83dbSDimitry Andric   const char *SmallDataLimit = "8";
21205ffd83dbSDimitry Andric   // Get small data limitation.
21215ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
21225ffd83dbSDimitry Andric                       options::OPT_fPIC)) {
21235ffd83dbSDimitry Andric     // Not support linker relaxation for PIC.
21245ffd83dbSDimitry Andric     SmallDataLimit = "0";
21255ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
21265ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
21275ffd83dbSDimitry Andric     }
21285ffd83dbSDimitry Andric   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2129fe6060f1SDimitry Andric                  .equals_insensitive("large") &&
21305ffd83dbSDimitry Andric              (Triple.getArch() == llvm::Triple::riscv64)) {
21315ffd83dbSDimitry Andric     // Not support linker relaxation for RV64 with large code model.
21325ffd83dbSDimitry Andric     SmallDataLimit = "0";
21335ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
21345ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
21355ffd83dbSDimitry Andric     }
213606c3fb27SDimitry Andric   } else if (Triple.isAndroid()) {
213706c3fb27SDimitry Andric     // GP relaxation is not supported on Android.
213806c3fb27SDimitry Andric     SmallDataLimit = "0";
213906c3fb27SDimitry Andric     if (Args.hasArg(options::OPT_G)) {
214006c3fb27SDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
214106c3fb27SDimitry Andric     }
21425ffd83dbSDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
21435ffd83dbSDimitry Andric     SmallDataLimit = A->getValue();
21445ffd83dbSDimitry Andric   }
21455ffd83dbSDimitry Andric   // Forward the -msmall-data-limit= option.
21465ffd83dbSDimitry Andric   CmdArgs.push_back("-msmall-data-limit");
21475ffd83dbSDimitry Andric   CmdArgs.push_back(SmallDataLimit);
21485ffd83dbSDimitry Andric }
21495ffd83dbSDimitry Andric 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const21500b57cec5SDimitry Andric void Clang::AddRISCVTargetArgs(const ArgList &Args,
21510b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
21520b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
2153a7dea167SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
2156a7dea167SDimitry Andric   CmdArgs.push_back(ABIName.data());
21575ffd83dbSDimitry Andric 
21585ffd83dbSDimitry Andric   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2159e8d8bef9SDimitry Andric 
2160bdd1243dSDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
2161bdd1243dSDimitry Andric                     options::OPT_mno_implicit_float, true))
2162bdd1243dSDimitry Andric     CmdArgs.push_back("-no-implicit-float");
2163bdd1243dSDimitry Andric 
2164fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2165e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2166bdd1243dSDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2167bdd1243dSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2168bdd1243dSDimitry Andric     else
2169bdd1243dSDimitry Andric       CmdArgs.push_back(A->getValue());
2170e8d8bef9SDimitry Andric   }
217106c3fb27SDimitry Andric 
217206c3fb27SDimitry Andric   // Handle -mrvv-vector-bits=<bits>
217306c3fb27SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
217406c3fb27SDimitry Andric     StringRef Val = A->getValue();
217506c3fb27SDimitry Andric     const Driver &D = getToolChain().getDriver();
217606c3fb27SDimitry Andric 
217706c3fb27SDimitry Andric     // Get minimum VLen from march.
217806c3fb27SDimitry Andric     unsigned MinVLen = 0;
21790fca6ea1SDimitry Andric     std::string Arch = riscv::getRISCVArch(Args, Triple);
218006c3fb27SDimitry Andric     auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
218106c3fb27SDimitry Andric         Arch, /*EnableExperimentalExtensions*/ true);
218206c3fb27SDimitry Andric     // Ignore parsing error.
2183647cbc5dSDimitry Andric     if (!errorToBool(ISAInfo.takeError()))
218406c3fb27SDimitry Andric       MinVLen = (*ISAInfo)->getMinVLen();
218506c3fb27SDimitry Andric 
218606c3fb27SDimitry Andric     // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
218706c3fb27SDimitry Andric     // as integer as long as we have a MinVLen.
218806c3fb27SDimitry Andric     unsigned Bits = 0;
21890fca6ea1SDimitry Andric     if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
219006c3fb27SDimitry Andric       Bits = MinVLen;
219106c3fb27SDimitry Andric     } else if (!Val.getAsInteger(10, Bits)) {
219206c3fb27SDimitry Andric       // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
219306c3fb27SDimitry Andric       // at least MinVLen.
219406c3fb27SDimitry Andric       if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
219506c3fb27SDimitry Andric           Bits > 65536 || !llvm::isPowerOf2_32(Bits))
219606c3fb27SDimitry Andric         Bits = 0;
219706c3fb27SDimitry Andric     }
219806c3fb27SDimitry Andric 
219906c3fb27SDimitry Andric     // If we got a valid value try to use it.
220006c3fb27SDimitry Andric     if (Bits != 0) {
220106c3fb27SDimitry Andric       unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
220206c3fb27SDimitry Andric       CmdArgs.push_back(
220306c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
220406c3fb27SDimitry Andric       CmdArgs.push_back(
220506c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
22060fca6ea1SDimitry Andric     } else if (Val != "scalable") {
220706c3fb27SDimitry Andric       // Handle the unsupported values passed to mrvv-vector-bits.
220806c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
220906c3fb27SDimitry Andric           << A->getSpelling() << Val;
221006c3fb27SDimitry Andric     }
221106c3fb27SDimitry Andric   }
22120b57cec5SDimitry Andric }
22130b57cec5SDimitry Andric 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const22140b57cec5SDimitry Andric void Clang::AddSparcTargetArgs(const ArgList &Args,
22150b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
22160b57cec5SDimitry Andric   sparc::FloatABI FloatABI =
22170b57cec5SDimitry Andric       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric   if (FloatABI == sparc::FloatABI::Soft) {
22200b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
22210b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
22220b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
22230b57cec5SDimitry Andric     CmdArgs.push_back("soft");
22240b57cec5SDimitry Andric   } else {
22250b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
22260b57cec5SDimitry Andric     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
22270b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
22280b57cec5SDimitry Andric     CmdArgs.push_back("hard");
22290b57cec5SDimitry Andric   }
223061cfbce3SDimitry Andric 
223161cfbce3SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
223261cfbce3SDimitry Andric     StringRef Name = A->getValue();
223361cfbce3SDimitry Andric     std::string TuneCPU;
223461cfbce3SDimitry Andric     if (Name == "native")
223561cfbce3SDimitry Andric       TuneCPU = std::string(llvm::sys::getHostCPUName());
223661cfbce3SDimitry Andric     else
223761cfbce3SDimitry Andric       TuneCPU = std::string(Name);
223861cfbce3SDimitry Andric 
223961cfbce3SDimitry Andric     CmdArgs.push_back("-tune-cpu");
224061cfbce3SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
224161cfbce3SDimitry Andric   }
22420b57cec5SDimitry Andric }
22430b57cec5SDimitry Andric 
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const22440b57cec5SDimitry Andric void Clang::AddSystemZTargetArgs(const ArgList &Args,
22450b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
2246fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2247753f127fSDimitry Andric     CmdArgs.push_back("-tune-cpu");
2248fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2249fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2250fcaf7f86SDimitry Andric     else
2251fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
2252753f127fSDimitry Andric   }
2253753f127fSDimitry Andric 
2254753f127fSDimitry Andric   bool HasBackchain =
2255753f127fSDimitry Andric       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2256480093f4SDimitry Andric   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2257480093f4SDimitry Andric                                      options::OPT_mno_packed_stack, false);
22585ffd83dbSDimitry Andric   systemz::FloatABI FloatABI =
22595ffd83dbSDimitry Andric       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
22605ffd83dbSDimitry Andric   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
22615ffd83dbSDimitry Andric   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2262480093f4SDimitry Andric     const Driver &D = getToolChain().getDriver();
2263480093f4SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt)
22645ffd83dbSDimitry Andric       << "-mpacked-stack -mbackchain -mhard-float";
2265480093f4SDimitry Andric   }
2266480093f4SDimitry Andric   if (HasBackchain)
22670b57cec5SDimitry Andric     CmdArgs.push_back("-mbackchain");
2268480093f4SDimitry Andric   if (HasPackedStack)
2269480093f4SDimitry Andric     CmdArgs.push_back("-mpacked-stack");
22705ffd83dbSDimitry Andric   if (HasSoftFloat) {
22715ffd83dbSDimitry Andric     // Floating point operations and argument passing are soft.
22725ffd83dbSDimitry Andric     CmdArgs.push_back("-msoft-float");
22735ffd83dbSDimitry Andric     CmdArgs.push_back("-mfloat-abi");
22745ffd83dbSDimitry Andric     CmdArgs.push_back("soft");
2275480093f4SDimitry Andric   }
22760b57cec5SDimitry Andric }
22770b57cec5SDimitry Andric 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const22780b57cec5SDimitry Andric void Clang::AddX86TargetArgs(const ArgList &Args,
22790b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
2280480093f4SDimitry Andric   const Driver &D = getToolChain().getDriver();
22815ffd83dbSDimitry Andric   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2282480093f4SDimitry Andric 
22830b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
22840b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
22850b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
22860b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
22890b57cec5SDimitry Andric                     options::OPT_mno_tls_direct_seg_refs, true))
22900b57cec5SDimitry Andric     CmdArgs.push_back("-mno-tls-direct-seg-refs");
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   // Default to avoid implicit floating-point for kernel/kext code, but allow
22930b57cec5SDimitry Andric   // that to be overridden with -mno-soft-float.
22940b57cec5SDimitry Andric   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
22950b57cec5SDimitry Andric                           Args.hasArg(options::OPT_fapple_kext));
22960b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(
22970b57cec5SDimitry Andric           options::OPT_msoft_float, options::OPT_mno_soft_float,
22980b57cec5SDimitry Andric           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
22990b57cec5SDimitry Andric     const Option &O = A->getOption();
23000b57cec5SDimitry Andric     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
23010b57cec5SDimitry Andric                        O.matches(options::OPT_msoft_float));
23020b57cec5SDimitry Andric   }
23030b57cec5SDimitry Andric   if (NoImplicitFloat)
23040b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
23070b57cec5SDimitry Andric     StringRef Value = A->getValue();
23080b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
23090b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
23100b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2311349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
23120b57cec5SDimitry Andric     } else {
2313480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
2314bdd1243dSDimitry Andric           << A->getSpelling() << Value;
23150b57cec5SDimitry Andric     }
2316480093f4SDimitry Andric   } else if (D.IsCLMode()) {
23170b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
23180b57cec5SDimitry Andric     CmdArgs.push_back("-x86-asm-syntax=intel");
23190b57cec5SDimitry Andric   }
23200b57cec5SDimitry Andric 
2321349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2322349cc55cSDimitry Andric                                options::OPT_mno_skip_rax_setup))
2323349cc55cSDimitry Andric     if (A->getOption().matches(options::OPT_mskip_rax_setup))
2324349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2325349cc55cSDimitry Andric 
23260b57cec5SDimitry Andric   // Set flags to support MCU ABI.
23270b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
23280b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
23290b57cec5SDimitry Andric     CmdArgs.push_back("soft");
23300b57cec5SDimitry Andric     CmdArgs.push_back("-mstack-alignment=4");
23310b57cec5SDimitry Andric   }
2332e8d8bef9SDimitry Andric 
2333e8d8bef9SDimitry Andric   // Handle -mtune.
2334e8d8bef9SDimitry Andric 
233581ad6265SDimitry Andric   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2336e8d8bef9SDimitry Andric   std::string TuneCPU;
2337e8d8bef9SDimitry Andric   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
233881ad6265SDimitry Andric       !getToolChain().getTriple().isPS())
2339e8d8bef9SDimitry Andric     TuneCPU = "generic";
2340e8d8bef9SDimitry Andric 
2341e8d8bef9SDimitry Andric   // Override based on -mtune.
2342e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2343e8d8bef9SDimitry Andric     StringRef Name = A->getValue();
2344e8d8bef9SDimitry Andric 
2345e8d8bef9SDimitry Andric     if (Name == "native") {
2346e8d8bef9SDimitry Andric       Name = llvm::sys::getHostCPUName();
2347e8d8bef9SDimitry Andric       if (!Name.empty())
2348e8d8bef9SDimitry Andric         TuneCPU = std::string(Name);
2349e8d8bef9SDimitry Andric     } else
2350e8d8bef9SDimitry Andric       TuneCPU = std::string(Name);
2351e8d8bef9SDimitry Andric   }
2352e8d8bef9SDimitry Andric 
2353e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2354e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2355e8d8bef9SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2356e8d8bef9SDimitry Andric   }
23570b57cec5SDimitry Andric }
23580b57cec5SDimitry Andric 
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const23590b57cec5SDimitry Andric void Clang::AddHexagonTargetArgs(const ArgList &Args,
23600b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
23610b57cec5SDimitry Andric   CmdArgs.push_back("-mqdsp6-compat");
23620b57cec5SDimitry Andric   CmdArgs.push_back("-Wreturn-type");
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
23650b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
2366bdd1243dSDimitry Andric     CmdArgs.push_back(
2367bdd1243dSDimitry Andric         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
23680b57cec5SDimitry Andric   }
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_short_enums))
23710b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
23720b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
23730b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
23740b57cec5SDimitry Andric     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
23750b57cec5SDimitry Andric   }
23760b57cec5SDimitry Andric   CmdArgs.push_back("-mllvm");
23770b57cec5SDimitry Andric   CmdArgs.push_back("-machine-sink-split=0");
23780b57cec5SDimitry Andric }
23790b57cec5SDimitry Andric 
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const23800b57cec5SDimitry Andric void Clang::AddLanaiTargetArgs(const ArgList &Args,
23810b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
23820b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
23830b57cec5SDimitry Andric     StringRef CPUName = A->getValue();
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
23860b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPUName));
23870b57cec5SDimitry Andric   }
23880b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
23890b57cec5SDimitry Andric     StringRef Value = A->getValue();
23900b57cec5SDimitry Andric     // Only support mregparm=4 to support old usage. Report error for all other
23910b57cec5SDimitry Andric     // cases.
23920b57cec5SDimitry Andric     int Mregparm;
23930b57cec5SDimitry Andric     if (Value.getAsInteger(10, Mregparm)) {
23940b57cec5SDimitry Andric       if (Mregparm != 4) {
23950b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
23960b57cec5SDimitry Andric             diag::err_drv_unsupported_option_argument)
2397bdd1243dSDimitry Andric             << A->getSpelling() << Value;
23980b57cec5SDimitry Andric       }
23990b57cec5SDimitry Andric     }
24000b57cec5SDimitry Andric   }
24010b57cec5SDimitry Andric }
24020b57cec5SDimitry Andric 
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const24030b57cec5SDimitry Andric void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
24040b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) const {
24050b57cec5SDimitry Andric   // Default to "hidden" visibility.
24060b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2407bdd1243dSDimitry Andric                    options::OPT_fvisibility_ms_compat))
2408bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=hidden");
24090b57cec5SDimitry Andric }
24100b57cec5SDimitry Andric 
AddVETargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const24115ffd83dbSDimitry Andric void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
24125ffd83dbSDimitry Andric   // Floating point operations and argument passing are hard.
24135ffd83dbSDimitry Andric   CmdArgs.push_back("-mfloat-abi");
24145ffd83dbSDimitry Andric   CmdArgs.push_back("hard");
24155ffd83dbSDimitry Andric }
24165ffd83dbSDimitry Andric 
DumpCompilationDatabase(Compilation & C,StringRef Filename,StringRef Target,const InputInfo & Output,const InputInfo & Input,const ArgList & Args) const24170b57cec5SDimitry Andric void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
24180b57cec5SDimitry Andric                                     StringRef Target, const InputInfo &Output,
24190b57cec5SDimitry Andric                                     const InputInfo &Input, const ArgList &Args) const {
24200b57cec5SDimitry Andric   // If this is a dry run, do not create the compilation database file.
24210b57cec5SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
24220b57cec5SDimitry Andric     return;
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric   using llvm::yaml::escape;
24250b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   if (!CompilationDatabase) {
24280b57cec5SDimitry Andric     std::error_code EC;
2429fe6060f1SDimitry Andric     auto File = std::make_unique<llvm::raw_fd_ostream>(
243081ad6265SDimitry Andric         Filename, EC,
243181ad6265SDimitry Andric         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
24320b57cec5SDimitry Andric     if (EC) {
24330b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
24340b57cec5SDimitry Andric                                                        << EC.message();
24350b57cec5SDimitry Andric       return;
24360b57cec5SDimitry Andric     }
24370b57cec5SDimitry Andric     CompilationDatabase = std::move(File);
24380b57cec5SDimitry Andric   }
24390b57cec5SDimitry Andric   auto &CDB = *CompilationDatabase;
2440a7dea167SDimitry Andric   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2441a7dea167SDimitry Andric   if (!CWD)
2442a7dea167SDimitry Andric     CWD = ".";
2443a7dea167SDimitry Andric   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
24440b57cec5SDimitry Andric   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
24455f757f3fSDimitry Andric   if (Output.isFilename())
24460b57cec5SDimitry Andric     CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
24470b57cec5SDimitry Andric   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2448a7dea167SDimitry Andric   SmallString<128> Buf;
24490b57cec5SDimitry Andric   Buf = "-x";
24500b57cec5SDimitry Andric   Buf += types::getTypeName(Input.getType());
24510b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"";
24520b57cec5SDimitry Andric   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
24530b57cec5SDimitry Andric     Buf = "--sysroot=";
24540b57cec5SDimitry Andric     Buf += D.SysRoot;
24550b57cec5SDimitry Andric     CDB << ", \"" << escape(Buf) << "\"";
24560b57cec5SDimitry Andric   }
24570b57cec5SDimitry Andric   CDB << ", \"" << escape(Input.getFilename()) << "\"";
24585f757f3fSDimitry Andric   if (Output.isFilename())
245981ad6265SDimitry Andric     CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
24600b57cec5SDimitry Andric   for (auto &A: Args) {
24610b57cec5SDimitry Andric     auto &O = A->getOption();
24620b57cec5SDimitry Andric     // Skip language selection, which is positional.
24630b57cec5SDimitry Andric     if (O.getID() == options::OPT_x)
24640b57cec5SDimitry Andric       continue;
24650b57cec5SDimitry Andric     // Skip writing dependency output and the compilation database itself.
24660b57cec5SDimitry Andric     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
24670b57cec5SDimitry Andric       continue;
2468a7dea167SDimitry Andric     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2469a7dea167SDimitry Andric       continue;
24700b57cec5SDimitry Andric     // Skip inputs.
24710b57cec5SDimitry Andric     if (O.getKind() == Option::InputClass)
24720b57cec5SDimitry Andric       continue;
247381ad6265SDimitry Andric     // Skip output.
247481ad6265SDimitry Andric     if (O.getID() == options::OPT_o)
247581ad6265SDimitry Andric       continue;
24760b57cec5SDimitry Andric     // All other arguments are quoted and appended.
24770b57cec5SDimitry Andric     ArgStringList ASL;
24780b57cec5SDimitry Andric     A->render(Args, ASL);
24790b57cec5SDimitry Andric     for (auto &it: ASL)
24800b57cec5SDimitry Andric       CDB << ", \"" << escape(it) << "\"";
24810b57cec5SDimitry Andric   }
24820b57cec5SDimitry Andric   Buf = "--target=";
24830b57cec5SDimitry Andric   Buf += Target;
24840b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"]},\n";
24850b57cec5SDimitry Andric }
24860b57cec5SDimitry Andric 
DumpCompilationDatabaseFragmentToDir(StringRef Dir,Compilation & C,StringRef Target,const InputInfo & Output,const InputInfo & Input,const llvm::opt::ArgList & Args) const2487a7dea167SDimitry Andric void Clang::DumpCompilationDatabaseFragmentToDir(
2488a7dea167SDimitry Andric     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2489a7dea167SDimitry Andric     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2490a7dea167SDimitry Andric   // If this is a dry run, do not create the compilation database file.
2491a7dea167SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2492a7dea167SDimitry Andric     return;
2493a7dea167SDimitry Andric 
2494a7dea167SDimitry Andric   if (CompilationDatabase)
2495a7dea167SDimitry Andric     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2496a7dea167SDimitry Andric 
2497a7dea167SDimitry Andric   SmallString<256> Path = Dir;
2498a7dea167SDimitry Andric   const auto &Driver = C.getDriver();
2499a7dea167SDimitry Andric   Driver.getVFS().makeAbsolute(Path);
2500a7dea167SDimitry Andric   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2501a7dea167SDimitry Andric   if (Err) {
2502a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2503a7dea167SDimitry Andric     return;
2504a7dea167SDimitry Andric   }
2505a7dea167SDimitry Andric 
2506a7dea167SDimitry Andric   llvm::sys::path::append(
2507a7dea167SDimitry Andric       Path,
2508a7dea167SDimitry Andric       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2509a7dea167SDimitry Andric   int FD;
2510a7dea167SDimitry Andric   SmallString<256> TempPath;
2511fe6060f1SDimitry Andric   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2512fe6060f1SDimitry Andric                                         llvm::sys::fs::OF_Text);
2513a7dea167SDimitry Andric   if (Err) {
2514a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2515a7dea167SDimitry Andric     return;
2516a7dea167SDimitry Andric   }
2517a7dea167SDimitry Andric   CompilationDatabase =
2518a7dea167SDimitry Andric       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2519a7dea167SDimitry Andric   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2520a7dea167SDimitry Andric }
2521a7dea167SDimitry Andric 
CheckARMImplicitITArg(StringRef Value)2522fe6060f1SDimitry Andric static bool CheckARMImplicitITArg(StringRef Value) {
2523fe6060f1SDimitry Andric   return Value == "always" || Value == "never" || Value == "arm" ||
2524fe6060f1SDimitry Andric          Value == "thumb";
2525fe6060f1SDimitry Andric }
2526fe6060f1SDimitry Andric 
AddARMImplicitITArgs(const ArgList & Args,ArgStringList & CmdArgs,StringRef Value)2527fe6060f1SDimitry Andric static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2528fe6060f1SDimitry Andric                                  StringRef Value) {
2529fe6060f1SDimitry Andric   CmdArgs.push_back("-mllvm");
2530fe6060f1SDimitry Andric   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2531fe6060f1SDimitry Andric }
2532fe6060f1SDimitry Andric 
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)25330b57cec5SDimitry Andric static void CollectArgsForIntegratedAssembler(Compilation &C,
25340b57cec5SDimitry Andric                                               const ArgList &Args,
25350b57cec5SDimitry Andric                                               ArgStringList &CmdArgs,
25360b57cec5SDimitry Andric                                               const Driver &D) {
25370fca6ea1SDimitry Andric   // Default to -mno-relax-all.
25380fca6ea1SDimitry Andric   //
25390fca6ea1SDimitry Andric   // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
25400fca6ea1SDimitry Andric   // cannot be done by assembler branch relaxation as it needs a free temporary
25410fca6ea1SDimitry Andric   // register. Because of this, branch relaxation is handled by a MachineIR pass
25420fca6ea1SDimitry Andric   // before the assembler. Forcing assembler branch relaxation for -O0 makes the
25430fca6ea1SDimitry Andric   // MachineIR branch relaxation inaccurate and it will miss cases where an
25440fca6ea1SDimitry Andric   // indirect branch is necessary.
25450fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
25460fca6ea1SDimitry Andric                     options::OPT_mno_relax_all);
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric   // Only default to -mincremental-linker-compatible if we think we are
25490b57cec5SDimitry Andric   // targeting the MSVC linker.
25500b57cec5SDimitry Andric   bool DefaultIncrementalLinkerCompatible =
25510b57cec5SDimitry Andric       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
25520b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
25530b57cec5SDimitry Andric                    options::OPT_mno_incremental_linker_compatible,
25540b57cec5SDimitry Andric                    DefaultIncrementalLinkerCompatible))
25550b57cec5SDimitry Andric     CmdArgs.push_back("-mincremental-linker-compatible");
25560b57cec5SDimitry Andric 
255781ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
255881ad6265SDimitry Andric 
255906c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
256006c3fb27SDimitry Andric                     options::OPT_fno_emit_compact_unwind_non_canonical);
256106c3fb27SDimitry Andric 
2562a7dea167SDimitry Andric   // If you add more args here, also add them to the block below that
2563a7dea167SDimitry Andric   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2564a7dea167SDimitry Andric 
25650b57cec5SDimitry Andric   // When passing -I arguments to the assembler we sometimes need to
25660b57cec5SDimitry Andric   // unconditionally take the next argument.  For example, when parsing
25670b57cec5SDimitry Andric   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
25680b57cec5SDimitry Andric   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
25690b57cec5SDimitry Andric   // arg after parsing the '-I' arg.
25700b57cec5SDimitry Andric   bool TakeNextArg = false;
25710b57cec5SDimitry Andric 
25720fca6ea1SDimitry Andric   const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
25730fca6ea1SDimitry Andric   bool Crel = false, ExperimentalCrel = false;
25740b57cec5SDimitry Andric   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2575349cc55cSDimitry Andric   bool UseNoExecStack = false;
25760b57cec5SDimitry Andric   const char *MipsTargetFeature = nullptr;
2577fe6060f1SDimitry Andric   StringRef ImplicitIt;
25780b57cec5SDimitry Andric   for (const Arg *A :
2579fe6060f1SDimitry Andric        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2580fe6060f1SDimitry Andric                      options::OPT_mimplicit_it_EQ)) {
25810b57cec5SDimitry Andric     A->claim();
25820b57cec5SDimitry Andric 
2583fe6060f1SDimitry Andric     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2584fe6060f1SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
2585fe6060f1SDimitry Andric       case llvm::Triple::arm:
2586fe6060f1SDimitry Andric       case llvm::Triple::armeb:
2587fe6060f1SDimitry Andric       case llvm::Triple::thumb:
2588fe6060f1SDimitry Andric       case llvm::Triple::thumbeb:
2589fe6060f1SDimitry Andric         // Only store the value; the last value set takes effect.
2590fe6060f1SDimitry Andric         ImplicitIt = A->getValue();
2591fe6060f1SDimitry Andric         if (!CheckARMImplicitITArg(ImplicitIt))
2592fe6060f1SDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
2593bdd1243dSDimitry Andric               << A->getSpelling() << ImplicitIt;
2594fe6060f1SDimitry Andric         continue;
2595fe6060f1SDimitry Andric       default:
2596fe6060f1SDimitry Andric         break;
2597fe6060f1SDimitry Andric       }
2598fe6060f1SDimitry Andric     }
2599fe6060f1SDimitry Andric 
26000b57cec5SDimitry Andric     for (StringRef Value : A->getValues()) {
26010b57cec5SDimitry Andric       if (TakeNextArg) {
26020b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
26030b57cec5SDimitry Andric         TakeNextArg = false;
26040b57cec5SDimitry Andric         continue;
26050b57cec5SDimitry Andric       }
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
26080b57cec5SDimitry Andric           Value == "-mbig-obj")
26090b57cec5SDimitry Andric         continue; // LLVM handles bigobj automatically
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
26120b57cec5SDimitry Andric       default:
26130b57cec5SDimitry Andric         break;
26140fca6ea1SDimitry Andric       case llvm::Triple::x86:
26150fca6ea1SDimitry Andric       case llvm::Triple::x86_64:
26160fca6ea1SDimitry Andric         if (Value == "-msse2avx") {
26170fca6ea1SDimitry Andric           CmdArgs.push_back("-msse2avx");
26180fca6ea1SDimitry Andric           continue;
26190fca6ea1SDimitry Andric         }
26200fca6ea1SDimitry Andric         break;
2621bdd1243dSDimitry Andric       case llvm::Triple::wasm32:
2622bdd1243dSDimitry Andric       case llvm::Triple::wasm64:
2623bdd1243dSDimitry Andric         if (Value == "--no-type-check") {
2624bdd1243dSDimitry Andric           CmdArgs.push_back("-mno-type-check");
2625bdd1243dSDimitry Andric           continue;
2626bdd1243dSDimitry Andric         }
2627bdd1243dSDimitry Andric         break;
26280b57cec5SDimitry Andric       case llvm::Triple::thumb:
26290b57cec5SDimitry Andric       case llvm::Triple::thumbeb:
26300b57cec5SDimitry Andric       case llvm::Triple::arm:
26310b57cec5SDimitry Andric       case llvm::Triple::armeb:
26325f757f3fSDimitry Andric         if (Value.starts_with("-mimplicit-it=")) {
2633fe6060f1SDimitry Andric           // Only store the value; the last value set takes effect.
2634fe6060f1SDimitry Andric           ImplicitIt = Value.split("=").second;
2635fe6060f1SDimitry Andric           if (CheckARMImplicitITArg(ImplicitIt))
2636fe6060f1SDimitry Andric             continue;
2637fe6060f1SDimitry Andric         }
26380b57cec5SDimitry Andric         if (Value == "-mthumb")
26390b57cec5SDimitry Andric           // -mthumb has already been processed in ComputeLLVMTriple()
26400b57cec5SDimitry Andric           // recognize but skip over here.
26410b57cec5SDimitry Andric           continue;
26420b57cec5SDimitry Andric         break;
26430b57cec5SDimitry Andric       case llvm::Triple::mips:
26440b57cec5SDimitry Andric       case llvm::Triple::mipsel:
26450b57cec5SDimitry Andric       case llvm::Triple::mips64:
26460b57cec5SDimitry Andric       case llvm::Triple::mips64el:
26470b57cec5SDimitry Andric         if (Value == "--trap") {
26480b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
26490b57cec5SDimitry Andric           CmdArgs.push_back("+use-tcc-in-div");
26500b57cec5SDimitry Andric           continue;
26510b57cec5SDimitry Andric         }
26520b57cec5SDimitry Andric         if (Value == "--break") {
26530b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
26540b57cec5SDimitry Andric           CmdArgs.push_back("-use-tcc-in-div");
26550b57cec5SDimitry Andric           continue;
26560b57cec5SDimitry Andric         }
26575f757f3fSDimitry Andric         if (Value.starts_with("-msoft-float")) {
26580b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
26590b57cec5SDimitry Andric           CmdArgs.push_back("+soft-float");
26600b57cec5SDimitry Andric           continue;
26610b57cec5SDimitry Andric         }
26625f757f3fSDimitry Andric         if (Value.starts_with("-mhard-float")) {
26630b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
26640b57cec5SDimitry Andric           CmdArgs.push_back("-soft-float");
26650b57cec5SDimitry Andric           continue;
26660b57cec5SDimitry Andric         }
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
26690b57cec5SDimitry Andric                                 .Case("-mips1", "+mips1")
26700b57cec5SDimitry Andric                                 .Case("-mips2", "+mips2")
26710b57cec5SDimitry Andric                                 .Case("-mips3", "+mips3")
26720b57cec5SDimitry Andric                                 .Case("-mips4", "+mips4")
26730b57cec5SDimitry Andric                                 .Case("-mips5", "+mips5")
26740b57cec5SDimitry Andric                                 .Case("-mips32", "+mips32")
26750b57cec5SDimitry Andric                                 .Case("-mips32r2", "+mips32r2")
26760b57cec5SDimitry Andric                                 .Case("-mips32r3", "+mips32r3")
26770b57cec5SDimitry Andric                                 .Case("-mips32r5", "+mips32r5")
26780b57cec5SDimitry Andric                                 .Case("-mips32r6", "+mips32r6")
26790b57cec5SDimitry Andric                                 .Case("-mips64", "+mips64")
26800b57cec5SDimitry Andric                                 .Case("-mips64r2", "+mips64r2")
26810b57cec5SDimitry Andric                                 .Case("-mips64r3", "+mips64r3")
26820b57cec5SDimitry Andric                                 .Case("-mips64r5", "+mips64r5")
26830b57cec5SDimitry Andric                                 .Case("-mips64r6", "+mips64r6")
26840b57cec5SDimitry Andric                                 .Default(nullptr);
26850b57cec5SDimitry Andric         if (MipsTargetFeature)
26860b57cec5SDimitry Andric           continue;
26870b57cec5SDimitry Andric       }
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric       if (Value == "-force_cpusubtype_ALL") {
26900b57cec5SDimitry Andric         // Do nothing, this is the default and we don't support anything else.
26910b57cec5SDimitry Andric       } else if (Value == "-L") {
26920b57cec5SDimitry Andric         CmdArgs.push_back("-msave-temp-labels");
26930b57cec5SDimitry Andric       } else if (Value == "--fatal-warnings") {
26940b57cec5SDimitry Andric         CmdArgs.push_back("-massembler-fatal-warnings");
2695a7dea167SDimitry Andric       } else if (Value == "--no-warn" || Value == "-W") {
2696a7dea167SDimitry Andric         CmdArgs.push_back("-massembler-no-warn");
26970b57cec5SDimitry Andric       } else if (Value == "--noexecstack") {
26980b57cec5SDimitry Andric         UseNoExecStack = true;
26995f757f3fSDimitry Andric       } else if (Value.starts_with("-compress-debug-sections") ||
27005f757f3fSDimitry Andric                  Value.starts_with("--compress-debug-sections") ||
27010b57cec5SDimitry Andric                  Value == "-nocompress-debug-sections" ||
27020b57cec5SDimitry Andric                  Value == "--nocompress-debug-sections") {
27030b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
27040fca6ea1SDimitry Andric       } else if (Value == "--crel") {
27050fca6ea1SDimitry Andric         Crel = true;
27060fca6ea1SDimitry Andric       } else if (Value == "--no-crel") {
27070fca6ea1SDimitry Andric         Crel = false;
27080fca6ea1SDimitry Andric       } else if (Value == "--allow-experimental-crel") {
27090fca6ea1SDimitry Andric         ExperimentalCrel = true;
27100b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=yes" ||
27110b57cec5SDimitry Andric                  Value == "--mrelax-relocations=yes") {
27120b57cec5SDimitry Andric         UseRelaxRelocations = true;
27130b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=no" ||
27140b57cec5SDimitry Andric                  Value == "--mrelax-relocations=no") {
27150b57cec5SDimitry Andric         UseRelaxRelocations = false;
27165f757f3fSDimitry Andric       } else if (Value.starts_with("-I")) {
27170b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
27180b57cec5SDimitry Andric         // We need to consume the next argument if the current arg is a plain
27190b57cec5SDimitry Andric         // -I. The next arg will be the include directory.
27200b57cec5SDimitry Andric         if (Value == "-I")
27210b57cec5SDimitry Andric           TakeNextArg = true;
27225f757f3fSDimitry Andric       } else if (Value.starts_with("-gdwarf-")) {
27230b57cec5SDimitry Andric         // "-gdwarf-N" options are not cc1as options.
27240b57cec5SDimitry Andric         unsigned DwarfVersion = DwarfVersionNum(Value);
27250b57cec5SDimitry Andric         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
27260b57cec5SDimitry Andric           CmdArgs.push_back(Value.data());
27270b57cec5SDimitry Andric         } else {
27280b57cec5SDimitry Andric           RenderDebugEnablingArgs(Args, CmdArgs,
272906c3fb27SDimitry Andric                                   llvm::codegenoptions::DebugInfoConstructor,
27300b57cec5SDimitry Andric                                   DwarfVersion, llvm::DebuggerKind::Default);
27310b57cec5SDimitry Andric         }
27325f757f3fSDimitry Andric       } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
27335f757f3fSDimitry Andric                  Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
27340b57cec5SDimitry Andric         // Do nothing, we'll validate it later.
27350fca6ea1SDimitry Andric       } else if (Value == "-defsym" || Value == "--defsym") {
27360b57cec5SDimitry Andric         if (A->getNumValues() != 2) {
27370b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << Value;
27380b57cec5SDimitry Andric           break;
27390b57cec5SDimitry Andric         }
27400b57cec5SDimitry Andric         const char *S = A->getValue(1);
27410b57cec5SDimitry Andric         auto Pair = StringRef(S).split('=');
27420b57cec5SDimitry Andric         auto Sym = Pair.first;
27430b57cec5SDimitry Andric         auto SVal = Pair.second;
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric         if (Sym.empty() || SVal.empty()) {
27460b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << S;
27470b57cec5SDimitry Andric           break;
27480b57cec5SDimitry Andric         }
27490b57cec5SDimitry Andric         int64_t IVal;
27500b57cec5SDimitry Andric         if (SVal.getAsInteger(0, IVal)) {
27510b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
27520b57cec5SDimitry Andric           break;
27530b57cec5SDimitry Andric         }
27540fca6ea1SDimitry Andric         CmdArgs.push_back("--defsym");
27550b57cec5SDimitry Andric         TakeNextArg = true;
27560b57cec5SDimitry Andric       } else if (Value == "-fdebug-compilation-dir") {
27570b57cec5SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
27580b57cec5SDimitry Andric         TakeNextArg = true;
2759480093f4SDimitry Andric       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2760480093f4SDimitry Andric         // The flag is a -Wa / -Xassembler argument and Options doesn't
2761480093f4SDimitry Andric         // parse the argument, so this isn't automatically aliased to
2762480093f4SDimitry Andric         // -fdebug-compilation-dir (without '=') here.
2763480093f4SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
2764480093f4SDimitry Andric         CmdArgs.push_back(Value.data());
2765fe6060f1SDimitry Andric       } else if (Value == "--version") {
2766fe6060f1SDimitry Andric         D.PrintVersion(C, llvm::outs());
27670b57cec5SDimitry Andric       } else {
27680b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2769bdd1243dSDimitry Andric             << A->getSpelling() << Value;
27700b57cec5SDimitry Andric       }
27710b57cec5SDimitry Andric     }
27720b57cec5SDimitry Andric   }
2773fe6060f1SDimitry Andric   if (ImplicitIt.size())
2774fe6060f1SDimitry Andric     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
27750fca6ea1SDimitry Andric   if (Crel) {
27760fca6ea1SDimitry Andric     if (!ExperimentalCrel)
27770fca6ea1SDimitry Andric       D.Diag(diag::err_drv_experimental_crel);
27780fca6ea1SDimitry Andric     if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
27790fca6ea1SDimitry Andric       CmdArgs.push_back("--crel");
27800fca6ea1SDimitry Andric     } else {
27810fca6ea1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
27820fca6ea1SDimitry Andric           << "-Wa,--crel" << D.getTargetTriple();
27830fca6ea1SDimitry Andric     }
27840fca6ea1SDimitry Andric   }
2785bdd1243dSDimitry Andric   if (!UseRelaxRelocations)
2786bdd1243dSDimitry Andric     CmdArgs.push_back("-mrelax-relocations=no");
27870b57cec5SDimitry Andric   if (UseNoExecStack)
27880b57cec5SDimitry Andric     CmdArgs.push_back("-mnoexecstack");
27890b57cec5SDimitry Andric   if (MipsTargetFeature != nullptr) {
27900b57cec5SDimitry Andric     CmdArgs.push_back("-target-feature");
27910b57cec5SDimitry Andric     CmdArgs.push_back(MipsTargetFeature);
27920b57cec5SDimitry Andric   }
27930b57cec5SDimitry Andric 
27940b57cec5SDimitry Andric   // forward -fembed-bitcode to assmebler
27950b57cec5SDimitry Andric   if (C.getDriver().embedBitcodeEnabled() ||
27960b57cec5SDimitry Andric       C.getDriver().embedBitcodeMarkerOnly())
27970b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2798bdd1243dSDimitry Andric 
2799bdd1243dSDimitry Andric   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2800bdd1243dSDimitry Andric     CmdArgs.push_back("-as-secure-log-file");
2801bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2802bdd1243dSDimitry Andric   }
28030b57cec5SDimitry Andric }
28040b57cec5SDimitry Andric 
ComplexRangeKindToStr(LangOptions::ComplexRangeKind Range)28050fca6ea1SDimitry Andric static std::string ComplexRangeKindToStr(LangOptions::ComplexRangeKind Range) {
28065f757f3fSDimitry Andric   switch (Range) {
28070fca6ea1SDimitry Andric   case LangOptions::ComplexRangeKind::CX_Full:
28080fca6ea1SDimitry Andric     return "full";
28095f757f3fSDimitry Andric     break;
28100fca6ea1SDimitry Andric   case LangOptions::ComplexRangeKind::CX_Basic:
28110fca6ea1SDimitry Andric     return "basic";
28120fca6ea1SDimitry Andric     break;
28130fca6ea1SDimitry Andric   case LangOptions::ComplexRangeKind::CX_Improved:
28140fca6ea1SDimitry Andric     return "improved";
28150fca6ea1SDimitry Andric     break;
28160fca6ea1SDimitry Andric   case LangOptions::ComplexRangeKind::CX_Promoted:
28170fca6ea1SDimitry Andric     return "promoted";
28185f757f3fSDimitry Andric     break;
28195f757f3fSDimitry Andric   default:
28200fca6ea1SDimitry Andric     return "";
28215f757f3fSDimitry Andric   }
28225f757f3fSDimitry Andric }
28235f757f3fSDimitry Andric 
ComplexArithmeticStr(LangOptions::ComplexRangeKind Range)28240fca6ea1SDimitry Andric static std::string ComplexArithmeticStr(LangOptions::ComplexRangeKind Range) {
28250fca6ea1SDimitry Andric   return (Range == LangOptions::ComplexRangeKind::CX_None)
28260fca6ea1SDimitry Andric              ? ""
28270fca6ea1SDimitry Andric              : "-fcomplex-arithmetic=" + ComplexRangeKindToStr(Range);
28280fca6ea1SDimitry Andric }
28290fca6ea1SDimitry Andric 
EmitComplexRangeDiag(const Driver & D,std::string str1,std::string str2)28300fca6ea1SDimitry Andric static void EmitComplexRangeDiag(const Driver &D, std::string str1,
28310fca6ea1SDimitry Andric                                  std::string str2) {
28320fca6ea1SDimitry Andric   if ((str1.compare(str2) != 0) && !str2.empty() && !str1.empty()) {
28330fca6ea1SDimitry Andric     D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
28340fca6ea1SDimitry Andric   }
28355f757f3fSDimitry Andric }
28365f757f3fSDimitry Andric 
28377a6dacacSDimitry Andric static std::string
RenderComplexRangeOption(LangOptions::ComplexRangeKind Range)28387a6dacacSDimitry Andric RenderComplexRangeOption(LangOptions::ComplexRangeKind Range) {
28390fca6ea1SDimitry Andric   std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
28400fca6ea1SDimitry Andric   if (!ComplexRangeStr.empty())
28410fca6ea1SDimitry Andric     return "-complex-range=" + ComplexRangeStr;
28425f757f3fSDimitry Andric   return ComplexRangeStr;
28435f757f3fSDimitry Andric }
28445f757f3fSDimitry Andric 
RenderFloatingPointOptions(const ToolChain & TC,const Driver & D,bool OFastEnabled,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)28450b57cec5SDimitry Andric static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
28460b57cec5SDimitry Andric                                        bool OFastEnabled, const ArgList &Args,
28475ffd83dbSDimitry Andric                                        ArgStringList &CmdArgs,
28485ffd83dbSDimitry Andric                                        const JobAction &JA) {
28490b57cec5SDimitry Andric   // Handle various floating point optimization flags, mapping them to the
28500b57cec5SDimitry Andric   // appropriate LLVM code generation flags. This is complicated by several
28510b57cec5SDimitry Andric   // "umbrella" flags, so we do this by stepping through the flags incrementally
28520b57cec5SDimitry Andric   // adjusting what we think is enabled/disabled, then at the end setting the
28530b57cec5SDimitry Andric   // LLVM flags based on the final state.
28540b57cec5SDimitry Andric   bool HonorINFs = true;
28550b57cec5SDimitry Andric   bool HonorNaNs = true;
2856349cc55cSDimitry Andric   bool ApproxFunc = false;
28570b57cec5SDimitry Andric   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
28580b57cec5SDimitry Andric   bool MathErrno = TC.IsMathErrnoDefault();
28590b57cec5SDimitry Andric   bool AssociativeMath = false;
28600b57cec5SDimitry Andric   bool ReciprocalMath = false;
28610b57cec5SDimitry Andric   bool SignedZeros = true;
2862480093f4SDimitry Andric   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2863480093f4SDimitry Andric   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2864480093f4SDimitry Andric                                     // overriden by ffp-exception-behavior?
2865480093f4SDimitry Andric   bool RoundingFPMath = false;
2866480093f4SDimitry Andric   // -ffp-model values: strict, fast, precise
2867480093f4SDimitry Andric   StringRef FPModel = "";
2868480093f4SDimitry Andric   // -ffp-exception-behavior options: strict, maytrap, ignore
2869480093f4SDimitry Andric   StringRef FPExceptionBehavior = "";
287081ad6265SDimitry Andric   // -ffp-eval-method options: double, extended, source
287181ad6265SDimitry Andric   StringRef FPEvalMethod = "";
28720fca6ea1SDimitry Andric   llvm::DenormalMode DenormalFPMath =
28735ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA);
28740fca6ea1SDimitry Andric   llvm::DenormalMode DenormalFP32Math =
28755ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
28765ffd83dbSDimitry Andric 
2877349cc55cSDimitry Andric   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2878349cc55cSDimitry Andric   // If one wasn't given by the user, don't pass it here.
2879349cc55cSDimitry Andric   StringRef FPContract;
2880bdd1243dSDimitry Andric   StringRef LastSeenFfpContractOption;
2881bdd1243dSDimitry Andric   bool SeenUnsafeMathModeOption = false;
2882349cc55cSDimitry Andric   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2883349cc55cSDimitry Andric       !JA.isOffloading(Action::OFK_HIP))
2884349cc55cSDimitry Andric     FPContract = "on";
2885480093f4SDimitry Andric   bool StrictFPModel = false;
2886bdd1243dSDimitry Andric   StringRef Float16ExcessPrecision = "";
288706c3fb27SDimitry Andric   StringRef BFloat16ExcessPrecision = "";
28887a6dacacSDimitry Andric   LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
28897a6dacacSDimitry Andric   std::string ComplexRangeStr = "";
28900fca6ea1SDimitry Andric   std::string GccRangeComplexOption = "";
28910fca6ea1SDimitry Andric 
28920fca6ea1SDimitry Andric   // Lambda to set fast-math options. This is also used by -ffp-model=fast
28930fca6ea1SDimitry Andric   auto applyFastMath = [&]() {
28940fca6ea1SDimitry Andric     HonorINFs = false;
28950fca6ea1SDimitry Andric     HonorNaNs = false;
28960fca6ea1SDimitry Andric     MathErrno = false;
28970fca6ea1SDimitry Andric     AssociativeMath = true;
28980fca6ea1SDimitry Andric     ReciprocalMath = true;
28990fca6ea1SDimitry Andric     ApproxFunc = true;
29000fca6ea1SDimitry Andric     SignedZeros = false;
29010fca6ea1SDimitry Andric     TrappingMath = false;
29020fca6ea1SDimitry Andric     RoundingFPMath = false;
29030fca6ea1SDimitry Andric     FPExceptionBehavior = "";
29040fca6ea1SDimitry Andric     // If fast-math is set then set the fp-contract mode to fast.
29050fca6ea1SDimitry Andric     FPContract = "fast";
29060fca6ea1SDimitry Andric     // ffast-math enables basic range rules for complex multiplication and
29070fca6ea1SDimitry Andric     // division.
29080fca6ea1SDimitry Andric     // Warn if user expects to perform full implementation of complex
29090fca6ea1SDimitry Andric     // multiplication or division in the presence of nan or ninf flags.
29100fca6ea1SDimitry Andric     if (Range == LangOptions::ComplexRangeKind::CX_Full ||
29110fca6ea1SDimitry Andric         Range == LangOptions::ComplexRangeKind::CX_Improved ||
29120fca6ea1SDimitry Andric         Range == LangOptions::ComplexRangeKind::CX_Promoted)
29130fca6ea1SDimitry Andric       EmitComplexRangeDiag(
29140fca6ea1SDimitry Andric           D, ComplexArithmeticStr(Range),
29150fca6ea1SDimitry Andric           !GccRangeComplexOption.empty()
29160fca6ea1SDimitry Andric               ? GccRangeComplexOption
29170fca6ea1SDimitry Andric               : ComplexArithmeticStr(LangOptions::ComplexRangeKind::CX_Basic));
29180fca6ea1SDimitry Andric     Range = LangOptions::ComplexRangeKind::CX_Basic;
29190fca6ea1SDimitry Andric     SeenUnsafeMathModeOption = true;
29200fca6ea1SDimitry Andric   };
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
29230b57cec5SDimitry Andric     CmdArgs.push_back("-mlimit-float-precision");
29240b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
29250b57cec5SDimitry Andric   }
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric   for (const Arg *A : Args) {
29280fca6ea1SDimitry Andric     switch (A->getOption().getID()) {
29290fca6ea1SDimitry Andric     // If this isn't an FP option skip the claim below
29300fca6ea1SDimitry Andric     default: continue;
29310fca6ea1SDimitry Andric 
29320fca6ea1SDimitry Andric     case options::OPT_fcx_limited_range:
29330fca6ea1SDimitry Andric       if (GccRangeComplexOption.empty()) {
29340fca6ea1SDimitry Andric         if (Range != LangOptions::ComplexRangeKind::CX_Basic)
29350fca6ea1SDimitry Andric           EmitComplexRangeDiag(D, RenderComplexRangeOption(Range),
29360fca6ea1SDimitry Andric                                "-fcx-limited-range");
29370fca6ea1SDimitry Andric       } else {
29380fca6ea1SDimitry Andric         if (GccRangeComplexOption != "-fno-cx-limited-range")
29390fca6ea1SDimitry Andric           EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-limited-range");
29405f757f3fSDimitry Andric       }
29410fca6ea1SDimitry Andric       GccRangeComplexOption = "-fcx-limited-range";
29420fca6ea1SDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Basic;
29430fca6ea1SDimitry Andric       break;
29445f757f3fSDimitry Andric     case options::OPT_fno_cx_limited_range:
29450fca6ea1SDimitry Andric       if (GccRangeComplexOption.empty()) {
29460fca6ea1SDimitry Andric         EmitComplexRangeDiag(D, RenderComplexRangeOption(Range),
29470fca6ea1SDimitry Andric                              "-fno-cx-limited-range");
29480fca6ea1SDimitry Andric       } else {
29490fca6ea1SDimitry Andric         if (GccRangeComplexOption.compare("-fcx-limited-range") != 0 &&
29500fca6ea1SDimitry Andric             GccRangeComplexOption.compare("-fno-cx-fortran-rules") != 0)
29510fca6ea1SDimitry Andric           EmitComplexRangeDiag(D, GccRangeComplexOption,
29520fca6ea1SDimitry Andric                                "-fno-cx-limited-range");
29530fca6ea1SDimitry Andric       }
29540fca6ea1SDimitry Andric       GccRangeComplexOption = "-fno-cx-limited-range";
29555f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
29565f757f3fSDimitry Andric       break;
29570fca6ea1SDimitry Andric     case options::OPT_fcx_fortran_rules:
29580fca6ea1SDimitry Andric       if (GccRangeComplexOption.empty())
29590fca6ea1SDimitry Andric         EmitComplexRangeDiag(D, RenderComplexRangeOption(Range),
29600fca6ea1SDimitry Andric                              "-fcx-fortran-rules");
29610fca6ea1SDimitry Andric       else
29620fca6ea1SDimitry Andric         EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-fortran-rules");
29630fca6ea1SDimitry Andric       GccRangeComplexOption = "-fcx-fortran-rules";
29640fca6ea1SDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Improved;
29650fca6ea1SDimitry Andric       break;
29660fca6ea1SDimitry Andric     case options::OPT_fno_cx_fortran_rules:
29670fca6ea1SDimitry Andric       if (GccRangeComplexOption.empty()) {
29680fca6ea1SDimitry Andric         EmitComplexRangeDiag(D, RenderComplexRangeOption(Range),
29690fca6ea1SDimitry Andric                              "-fno-cx-fortran-rules");
29700fca6ea1SDimitry Andric       } else {
29710fca6ea1SDimitry Andric         if (GccRangeComplexOption != "-fno-cx-limited-range")
29720fca6ea1SDimitry Andric           EmitComplexRangeDiag(D, GccRangeComplexOption,
29730fca6ea1SDimitry Andric                                "-fno-cx-fortran-rules");
29740fca6ea1SDimitry Andric       }
29750fca6ea1SDimitry Andric       GccRangeComplexOption = "-fno-cx-fortran-rules";
29760fca6ea1SDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
29770fca6ea1SDimitry Andric       break;
29780fca6ea1SDimitry Andric     case options::OPT_fcomplex_arithmetic_EQ: {
29790fca6ea1SDimitry Andric       LangOptions::ComplexRangeKind RangeVal;
29800fca6ea1SDimitry Andric       StringRef Val = A->getValue();
29810fca6ea1SDimitry Andric       if (Val == "full")
29820fca6ea1SDimitry Andric         RangeVal = LangOptions::ComplexRangeKind::CX_Full;
29830fca6ea1SDimitry Andric       else if (Val == "improved")
29840fca6ea1SDimitry Andric         RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
29850fca6ea1SDimitry Andric       else if (Val == "promoted")
29860fca6ea1SDimitry Andric         RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
29870fca6ea1SDimitry Andric       else if (Val == "basic")
29880fca6ea1SDimitry Andric         RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
29890fca6ea1SDimitry Andric       else {
29900fca6ea1SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
29910fca6ea1SDimitry Andric             << A->getSpelling() << Val;
29925f757f3fSDimitry Andric         break;
29935f757f3fSDimitry Andric       }
29940fca6ea1SDimitry Andric       if (!GccRangeComplexOption.empty()) {
29950fca6ea1SDimitry Andric         if (GccRangeComplexOption.compare("-fcx-limited-range") != 0) {
29960fca6ea1SDimitry Andric           if (GccRangeComplexOption.compare("-fcx-fortran-rules") != 0) {
29970fca6ea1SDimitry Andric             if (RangeVal != LangOptions::ComplexRangeKind::CX_Improved)
29980fca6ea1SDimitry Andric               EmitComplexRangeDiag(D, GccRangeComplexOption,
29990fca6ea1SDimitry Andric                                    ComplexArithmeticStr(RangeVal));
30000fca6ea1SDimitry Andric           } else {
30010fca6ea1SDimitry Andric             EmitComplexRangeDiag(D, GccRangeComplexOption,
30020fca6ea1SDimitry Andric                                  ComplexArithmeticStr(RangeVal));
30030fca6ea1SDimitry Andric           }
30040fca6ea1SDimitry Andric         } else {
30050fca6ea1SDimitry Andric           if (RangeVal != LangOptions::ComplexRangeKind::CX_Basic)
30060fca6ea1SDimitry Andric             EmitComplexRangeDiag(D, GccRangeComplexOption,
30070fca6ea1SDimitry Andric                                  ComplexArithmeticStr(RangeVal));
30080fca6ea1SDimitry Andric         }
30090fca6ea1SDimitry Andric       }
30100fca6ea1SDimitry Andric       Range = RangeVal;
30115f757f3fSDimitry Andric       break;
30120fca6ea1SDimitry Andric     }
3013480093f4SDimitry Andric     case options::OPT_ffp_model_EQ: {
3014480093f4SDimitry Andric       // If -ffp-model= is seen, reset to fno-fast-math
3015480093f4SDimitry Andric       HonorINFs = true;
3016480093f4SDimitry Andric       HonorNaNs = true;
3017bdd1243dSDimitry Andric       ApproxFunc = false;
3018480093f4SDimitry Andric       // Turning *off* -ffast-math restores the toolchain default.
3019480093f4SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
3020480093f4SDimitry Andric       AssociativeMath = false;
3021480093f4SDimitry Andric       ReciprocalMath = false;
3022480093f4SDimitry Andric       SignedZeros = true;
3023349cc55cSDimitry Andric       FPContract = "on";
30245ffd83dbSDimitry Andric 
3025480093f4SDimitry Andric       StringRef Val = A->getValue();
30260fca6ea1SDimitry Andric       if (OFastEnabled && Val != "fast") {
3027480093f4SDimitry Andric         // Only -ffp-model=fast is compatible with OFast, ignore.
30285f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
30295f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3030480093f4SDimitry Andric         break;
3031480093f4SDimitry Andric       }
3032480093f4SDimitry Andric       StrictFPModel = false;
30330fca6ea1SDimitry Andric       if (!FPModel.empty() && FPModel != Val)
30345f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
3035480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + FPModel)
3036480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val);
30370fca6ea1SDimitry Andric       if (Val == "fast") {
3038480093f4SDimitry Andric         FPModel = Val;
30390fca6ea1SDimitry Andric         applyFastMath();
30400fca6ea1SDimitry Andric       } else if (Val == "precise") {
3041480093f4SDimitry Andric         FPModel = Val;
3042349cc55cSDimitry Andric         FPContract = "on";
30430fca6ea1SDimitry Andric       } else if (Val == "strict") {
3044480093f4SDimitry Andric         StrictFPModel = true;
3045480093f4SDimitry Andric         FPExceptionBehavior = "strict";
3046480093f4SDimitry Andric         FPModel = Val;
30475ffd83dbSDimitry Andric         FPContract = "off";
3048480093f4SDimitry Andric         TrappingMath = true;
30490fca6ea1SDimitry Andric         RoundingFPMath = true;
3050480093f4SDimitry Andric       } else
3051480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3052bdd1243dSDimitry Andric             << A->getSpelling() << Val;
3053480093f4SDimitry Andric       break;
3054480093f4SDimitry Andric     }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric     // Options controlling individual features
30570b57cec5SDimitry Andric     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
30580b57cec5SDimitry Andric     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
30590b57cec5SDimitry Andric     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
30600b57cec5SDimitry Andric     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
3061349cc55cSDimitry Andric     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
3062349cc55cSDimitry Andric     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
30630b57cec5SDimitry Andric     case options::OPT_fmath_errno:          MathErrno = true;         break;
30640b57cec5SDimitry Andric     case options::OPT_fno_math_errno:       MathErrno = false;        break;
30650b57cec5SDimitry Andric     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
30660b57cec5SDimitry Andric     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
30670b57cec5SDimitry Andric     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
30680b57cec5SDimitry Andric     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
30690b57cec5SDimitry Andric     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
30700b57cec5SDimitry Andric     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
3071480093f4SDimitry Andric     case options::OPT_ftrapping_math:
3072480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
30730fca6ea1SDimitry Andric           FPExceptionBehavior != "strict")
3074480093f4SDimitry Andric         // Warn that previous value of option is overridden.
30755f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
30765f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
30775f757f3fSDimitry Andric                                   FPExceptionBehavior)
3078480093f4SDimitry Andric             << "-ftrapping-math";
3079480093f4SDimitry Andric       TrappingMath = true;
3080480093f4SDimitry Andric       TrappingMathPresent = true;
3081480093f4SDimitry Andric       FPExceptionBehavior = "strict";
3082480093f4SDimitry Andric       break;
3083480093f4SDimitry Andric     case options::OPT_fno_trapping_math:
3084480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
30850fca6ea1SDimitry Andric           FPExceptionBehavior != "ignore")
3086480093f4SDimitry Andric         // Warn that previous value of option is overridden.
30875f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
30885f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
30895f757f3fSDimitry Andric                                   FPExceptionBehavior)
3090480093f4SDimitry Andric             << "-fno-trapping-math";
3091480093f4SDimitry Andric       TrappingMath = false;
3092480093f4SDimitry Andric       TrappingMathPresent = true;
3093480093f4SDimitry Andric       FPExceptionBehavior = "ignore";
3094480093f4SDimitry Andric       break;
3095480093f4SDimitry Andric 
3096480093f4SDimitry Andric     case options::OPT_frounding_math:
3097480093f4SDimitry Andric       RoundingFPMath = true;
3098480093f4SDimitry Andric       break;
3099480093f4SDimitry Andric 
3100480093f4SDimitry Andric     case options::OPT_fno_rounding_math:
3101480093f4SDimitry Andric       RoundingFPMath = false;
3102480093f4SDimitry Andric       break;
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric     case options::OPT_fdenormal_fp_math_EQ:
31055ffd83dbSDimitry Andric       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
310681ad6265SDimitry Andric       DenormalFP32Math = DenormalFPMath;
31075ffd83dbSDimitry Andric       if (!DenormalFPMath.isValid()) {
31085ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
31095ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
31105ffd83dbSDimitry Andric       }
31115ffd83dbSDimitry Andric       break;
31125ffd83dbSDimitry Andric 
31135ffd83dbSDimitry Andric     case options::OPT_fdenormal_fp_math_f32_EQ:
31145ffd83dbSDimitry Andric       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
31155ffd83dbSDimitry Andric       if (!DenormalFP32Math.isValid()) {
31165ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
31175ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
31185ffd83dbSDimitry Andric       }
31190b57cec5SDimitry Andric       break;
31200b57cec5SDimitry Andric 
3121480093f4SDimitry Andric     // Validate and pass through -ffp-contract option.
31220b57cec5SDimitry Andric     case options::OPT_ffp_contract: {
31230b57cec5SDimitry Andric       StringRef Val = A->getValue();
31240fca6ea1SDimitry Andric       if (Val == "fast" || Val == "on" || Val == "off" ||
31250fca6ea1SDimitry Andric           Val == "fast-honor-pragmas") {
31260b57cec5SDimitry Andric         FPContract = Val;
3127bdd1243dSDimitry Andric         LastSeenFfpContractOption = Val;
3128bdd1243dSDimitry Andric       } else
31290b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3130bdd1243dSDimitry Andric             << A->getSpelling() << Val;
31310b57cec5SDimitry Andric       break;
31320b57cec5SDimitry Andric     }
31330b57cec5SDimitry Andric 
3134480093f4SDimitry Andric     // Validate and pass through -ffp-exception-behavior option.
3135480093f4SDimitry Andric     case options::OPT_ffp_exception_behavior_EQ: {
3136480093f4SDimitry Andric       StringRef Val = A->getValue();
3137480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
31380fca6ea1SDimitry Andric           FPExceptionBehavior != Val)
3139480093f4SDimitry Andric         // Warn that previous value of option is overridden.
31405f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
31415f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
31425f757f3fSDimitry Andric                                   FPExceptionBehavior)
3143480093f4SDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3144480093f4SDimitry Andric       TrappingMath = TrappingMathPresent = false;
31450fca6ea1SDimitry Andric       if (Val == "ignore" || Val == "maytrap")
3146480093f4SDimitry Andric         FPExceptionBehavior = Val;
31470fca6ea1SDimitry Andric       else if (Val == "strict") {
3148480093f4SDimitry Andric         FPExceptionBehavior = Val;
3149480093f4SDimitry Andric         TrappingMath = TrappingMathPresent = true;
3150480093f4SDimitry Andric       } else
3151480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3152bdd1243dSDimitry Andric             << A->getSpelling() << Val;
3153480093f4SDimitry Andric       break;
3154480093f4SDimitry Andric     }
3155480093f4SDimitry Andric 
315681ad6265SDimitry Andric     // Validate and pass through -ffp-eval-method option.
315781ad6265SDimitry Andric     case options::OPT_ffp_eval_method_EQ: {
315881ad6265SDimitry Andric       StringRef Val = A->getValue();
31590fca6ea1SDimitry Andric       if (Val == "double" || Val == "extended" || Val == "source")
316081ad6265SDimitry Andric         FPEvalMethod = Val;
316181ad6265SDimitry Andric       else
316281ad6265SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3163bdd1243dSDimitry Andric             << A->getSpelling() << Val;
316481ad6265SDimitry Andric       break;
316581ad6265SDimitry Andric     }
316681ad6265SDimitry Andric 
3167bdd1243dSDimitry Andric     case options::OPT_fexcess_precision_EQ: {
3168bdd1243dSDimitry Andric       StringRef Val = A->getValue();
3169bdd1243dSDimitry Andric       const llvm::Triple::ArchType Arch = TC.getArch();
3170bdd1243dSDimitry Andric       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
31710fca6ea1SDimitry Andric         if (Val == "standard" || Val == "fast")
3172bdd1243dSDimitry Andric           Float16ExcessPrecision = Val;
3173bdd1243dSDimitry Andric         // To make it GCC compatible, allow the value of "16" which
3174bdd1243dSDimitry Andric         // means disable excess precision, the same meaning than clang's
3175bdd1243dSDimitry Andric         // equivalent value "none".
31760fca6ea1SDimitry Andric         else if (Val == "16")
3177bdd1243dSDimitry Andric           Float16ExcessPrecision = "none";
3178bdd1243dSDimitry Andric         else
3179bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
3180bdd1243dSDimitry Andric               << A->getSpelling() << Val;
3181bdd1243dSDimitry Andric       } else {
31820fca6ea1SDimitry Andric         if (!(Val == "standard" || Val == "fast"))
3183bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
3184bdd1243dSDimitry Andric               << A->getSpelling() << Val;
3185bdd1243dSDimitry Andric       }
318606c3fb27SDimitry Andric       BFloat16ExcessPrecision = Float16ExcessPrecision;
3187bdd1243dSDimitry Andric       break;
3188bdd1243dSDimitry Andric     }
31890b57cec5SDimitry Andric     case options::OPT_ffinite_math_only:
31900b57cec5SDimitry Andric       HonorINFs = false;
31910b57cec5SDimitry Andric       HonorNaNs = false;
31920b57cec5SDimitry Andric       break;
31930b57cec5SDimitry Andric     case options::OPT_fno_finite_math_only:
31940b57cec5SDimitry Andric       HonorINFs = true;
31950b57cec5SDimitry Andric       HonorNaNs = true;
31960b57cec5SDimitry Andric       break;
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric     case options::OPT_funsafe_math_optimizations:
31990b57cec5SDimitry Andric       AssociativeMath = true;
32000b57cec5SDimitry Andric       ReciprocalMath = true;
32010b57cec5SDimitry Andric       SignedZeros = false;
320204eeddc0SDimitry Andric       ApproxFunc = true;
32030b57cec5SDimitry Andric       TrappingMath = false;
3204480093f4SDimitry Andric       FPExceptionBehavior = "";
3205bdd1243dSDimitry Andric       FPContract = "fast";
3206bdd1243dSDimitry Andric       SeenUnsafeMathModeOption = true;
32070b57cec5SDimitry Andric       break;
32080b57cec5SDimitry Andric     case options::OPT_fno_unsafe_math_optimizations:
32090b57cec5SDimitry Andric       AssociativeMath = false;
32100b57cec5SDimitry Andric       ReciprocalMath = false;
32110b57cec5SDimitry Andric       SignedZeros = true;
321204eeddc0SDimitry Andric       ApproxFunc = false;
32135ffd83dbSDimitry Andric 
3214bdd1243dSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3215bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3216bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3217bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3218bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3219bdd1243dSDimitry Andric           FPContract = "on";
3220bdd1243dSDimitry Andric       }
32210b57cec5SDimitry Andric       break;
32220b57cec5SDimitry Andric 
32230b57cec5SDimitry Andric     case options::OPT_Ofast:
32240b57cec5SDimitry Andric       // If -Ofast is the optimization level, then -ffast-math should be enabled
32250b57cec5SDimitry Andric       if (!OFastEnabled)
32260b57cec5SDimitry Andric         continue;
3227bdd1243dSDimitry Andric       [[fallthrough]];
32285f757f3fSDimitry Andric     case options::OPT_ffast_math: {
32290fca6ea1SDimitry Andric       applyFastMath();
32300b57cec5SDimitry Andric       break;
32315f757f3fSDimitry Andric     }
32320b57cec5SDimitry Andric     case options::OPT_fno_fast_math:
32330b57cec5SDimitry Andric       HonorINFs = true;
32340b57cec5SDimitry Andric       HonorNaNs = true;
32350b57cec5SDimitry Andric       // Turning on -ffast-math (with either flag) removes the need for
32360b57cec5SDimitry Andric       // MathErrno. However, turning *off* -ffast-math merely restores the
32370b57cec5SDimitry Andric       // toolchain default (which may be false).
32380b57cec5SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
32390b57cec5SDimitry Andric       AssociativeMath = false;
32400b57cec5SDimitry Andric       ReciprocalMath = false;
324104eeddc0SDimitry Andric       ApproxFunc = false;
32420b57cec5SDimitry Andric       SignedZeros = true;
32430fca6ea1SDimitry Andric       // -fno_fast_math restores default fpcontract handling
3244349cc55cSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3245bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3246bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3247bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3248bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3249349cc55cSDimitry Andric           FPContract = "on";
3250349cc55cSDimitry Andric       }
32510b57cec5SDimitry Andric       break;
32520b57cec5SDimitry Andric     }
32530fca6ea1SDimitry Andric     // The StrictFPModel local variable is needed to report warnings
32540fca6ea1SDimitry Andric     // in the way we intend. If -ffp-model=strict has been used, we
32550fca6ea1SDimitry Andric     // want to report a warning for the next option encountered that
32560fca6ea1SDimitry Andric     // takes us out of the settings described by fp-model=strict, but
32570fca6ea1SDimitry Andric     // we don't want to continue issuing warnings for other conflicting
32580fca6ea1SDimitry Andric     // options after that.
3259480093f4SDimitry Andric     if (StrictFPModel) {
3260480093f4SDimitry Andric       // If -ffp-model=strict has been specified on command line but
3261480093f4SDimitry Andric       // subsequent options conflict then emit warning diagnostic.
3262349cc55cSDimitry Andric       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
326304eeddc0SDimitry Andric           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
32640fca6ea1SDimitry Andric           FPContract == "off")
3265480093f4SDimitry Andric         // OK: Current Arg doesn't conflict with -ffp-model=strict
3266480093f4SDimitry Andric         ;
3267480093f4SDimitry Andric       else {
3268480093f4SDimitry Andric         StrictFPModel = false;
3269480093f4SDimitry Andric         FPModel = "";
3270bdd1243dSDimitry Andric         auto RHS = (A->getNumValues() == 0)
3271bdd1243dSDimitry Andric                        ? A->getSpelling()
3272bdd1243dSDimitry Andric                        : Args.MakeArgString(A->getSpelling() + A->getValue());
3273bdd1243dSDimitry Andric         if (RHS != "-ffp-model=strict")
32745f757f3fSDimitry Andric           D.Diag(clang::diag::warn_drv_overriding_option)
3275bdd1243dSDimitry Andric               << "-ffp-model=strict" << RHS;
3276480093f4SDimitry Andric       }
3277480093f4SDimitry Andric     }
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric     // If we handled this option claim it
32800b57cec5SDimitry Andric     A->claim();
32810b57cec5SDimitry Andric   }
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric   if (!HonorINFs)
32840b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-infs");
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric   if (!HonorNaNs)
32870b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-nans");
32880b57cec5SDimitry Andric 
3289349cc55cSDimitry Andric   if (ApproxFunc)
3290349cc55cSDimitry Andric     CmdArgs.push_back("-fapprox-func");
3291349cc55cSDimitry Andric 
32920b57cec5SDimitry Andric   if (MathErrno)
32930b57cec5SDimitry Andric     CmdArgs.push_back("-fmath-errno");
32940b57cec5SDimitry Andric 
3295bdd1243dSDimitry Andric  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3296bdd1243dSDimitry Andric      !TrappingMath)
3297bdd1243dSDimitry Andric     CmdArgs.push_back("-funsafe-math-optimizations");
32980b57cec5SDimitry Andric 
32990b57cec5SDimitry Andric   if (!SignedZeros)
33000b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-zeros");
33010b57cec5SDimitry Andric 
33020b57cec5SDimitry Andric   if (AssociativeMath && !SignedZeros && !TrappingMath)
33030b57cec5SDimitry Andric     CmdArgs.push_back("-mreassociate");
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric   if (ReciprocalMath)
33060b57cec5SDimitry Andric     CmdArgs.push_back("-freciprocal-math");
33070b57cec5SDimitry Andric 
3308480093f4SDimitry Andric   if (TrappingMath) {
3309480093f4SDimitry Andric     // FP Exception Behavior is also set to strict
33100fca6ea1SDimitry Andric     assert(FPExceptionBehavior == "strict");
3311e8d8bef9SDimitry Andric   }
33120b57cec5SDimitry Andric 
33135ffd83dbSDimitry Andric   // The default is IEEE.
33145ffd83dbSDimitry Andric   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
33155ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
33165ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
33175ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
33185ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
33195ffd83dbSDimitry Andric   }
33205ffd83dbSDimitry Andric 
33215ffd83dbSDimitry Andric   // Add f32 specific denormal mode flag if it's different.
33225ffd83dbSDimitry Andric   if (DenormalFP32Math != DenormalFPMath) {
33235ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
33245ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
33255ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
33265ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
33275ffd83dbSDimitry Andric   }
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric   if (!FPContract.empty())
33300b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
33310b57cec5SDimitry Andric 
33320fca6ea1SDimitry Andric   if (RoundingFPMath)
3333480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
33340fca6ea1SDimitry Andric   else
33350fca6ea1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3336480093f4SDimitry Andric 
3337480093f4SDimitry Andric   if (!FPExceptionBehavior.empty())
3338480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3339480093f4SDimitry Andric                       FPExceptionBehavior));
3340480093f4SDimitry Andric 
334181ad6265SDimitry Andric   if (!FPEvalMethod.empty())
334281ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
334381ad6265SDimitry Andric 
3344bdd1243dSDimitry Andric   if (!Float16ExcessPrecision.empty())
3345bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3346bdd1243dSDimitry Andric                                          Float16ExcessPrecision));
334706c3fb27SDimitry Andric   if (!BFloat16ExcessPrecision.empty())
334806c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
334906c3fb27SDimitry Andric                                          BFloat16ExcessPrecision));
3350bdd1243dSDimitry Andric 
33510b57cec5SDimitry Andric   ParseMRecip(D, Args, CmdArgs);
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
33540b57cec5SDimitry Andric   // individual features enabled by -ffast-math instead of the option itself as
33550b57cec5SDimitry Andric   // that's consistent with gcc's behaviour.
335604eeddc0SDimitry Andric   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3357480093f4SDimitry Andric       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
33580b57cec5SDimitry Andric     CmdArgs.push_back("-ffast-math");
33590fca6ea1SDimitry Andric     if (FPModel == "fast") {
33600fca6ea1SDimitry Andric       if (FPContract == "fast")
3361480093f4SDimitry Andric         // All set, do nothing.
3362480093f4SDimitry Andric         ;
3363480093f4SDimitry Andric       else if (FPContract.empty())
3364480093f4SDimitry Andric         // Enable -ffp-contract=fast
3365480093f4SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3366480093f4SDimitry Andric       else
33675f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
3368480093f4SDimitry Andric             << "-ffp-model=fast"
3369480093f4SDimitry Andric             << Args.MakeArgString("-ffp-contract=" + FPContract);
3370480093f4SDimitry Andric     }
3371480093f4SDimitry Andric   }
33720b57cec5SDimitry Andric 
33730b57cec5SDimitry Andric   // Handle __FINITE_MATH_ONLY__ similarly.
33740b57cec5SDimitry Andric   if (!HonorINFs && !HonorNaNs)
33750b57cec5SDimitry Andric     CmdArgs.push_back("-ffinite-math-only");
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
33780b57cec5SDimitry Andric     CmdArgs.push_back("-mfpmath");
33790b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
33800b57cec5SDimitry Andric   }
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric   // Disable a codegen optimization for floating-point casts.
33830b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
33840b57cec5SDimitry Andric                    options::OPT_fstrict_float_cast_overflow, false))
33850b57cec5SDimitry Andric     CmdArgs.push_back("-fno-strict-float-cast-overflow");
33865f757f3fSDimitry Andric 
33877a6dacacSDimitry Andric   if (Range != LangOptions::ComplexRangeKind::CX_None)
33887a6dacacSDimitry Andric     ComplexRangeStr = RenderComplexRangeOption(Range);
33890fca6ea1SDimitry Andric   if (!ComplexRangeStr.empty()) {
33907a6dacacSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
33910fca6ea1SDimitry Andric     if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
33920fca6ea1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
33930fca6ea1SDimitry Andric                                            ComplexRangeKindToStr(Range)));
33940fca6ea1SDimitry Andric   }
3395cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_limited_range))
33965f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-limited-range");
3397cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_fortran_rules))
33985f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-fortran-rules");
3399cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_limited_range))
34005f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-limited-range");
3401cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
34025f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-fortran-rules");
34030b57cec5SDimitry Andric }
34040b57cec5SDimitry Andric 
RenderAnalyzerOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input)34050b57cec5SDimitry Andric static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
34060b57cec5SDimitry Andric                                   const llvm::Triple &Triple,
34070b57cec5SDimitry Andric                                   const InputInfo &Input) {
34080b57cec5SDimitry Andric   // Add default argument set.
34090b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
34100b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=core");
34110b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=apiModeling");
34120b57cec5SDimitry Andric 
34130b57cec5SDimitry Andric     if (!Triple.isWindowsMSVCEnvironment()) {
34140b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix");
34150b57cec5SDimitry Andric     } else {
34160b57cec5SDimitry Andric       // Enable "unix" checkers that also work on Windows.
34170b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.API");
34180b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
34190b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
34200b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
34210b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
34220b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
34230b57cec5SDimitry Andric     }
34240b57cec5SDimitry Andric 
342581ad6265SDimitry Andric     // Disable some unix checkers for PS4/PS5.
342681ad6265SDimitry Andric     if (Triple.isPS()) {
34270b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
34280b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
34290b57cec5SDimitry Andric     }
34300b57cec5SDimitry Andric 
3431480093f4SDimitry Andric     if (Triple.isOSDarwin()) {
34320b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=osx");
3433480093f4SDimitry Andric       CmdArgs.push_back(
3434480093f4SDimitry Andric           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3435480093f4SDimitry Andric     }
3436480093f4SDimitry Andric     else if (Triple.isOSFuchsia())
3437480093f4SDimitry Andric       CmdArgs.push_back("-analyzer-checker=fuchsia");
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=deadcode");
34400b57cec5SDimitry Andric 
34410b57cec5SDimitry Andric     if (types::isCXX(Input.getType()))
34420b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=cplusplus");
34430b57cec5SDimitry Andric 
344481ad6265SDimitry Andric     if (!Triple.isPS()) {
34450b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
34460b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
34470b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
34480b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
34490b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
34500b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric     // Default nullability checks.
34540b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
34550b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
34560b57cec5SDimitry Andric   }
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric   // Set the output format. The default is plist, for (lame) historical reasons.
34590b57cec5SDimitry Andric   CmdArgs.push_back("-analyzer-output");
34600b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
34610b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
34620b57cec5SDimitry Andric   else
34630b57cec5SDimitry Andric     CmdArgs.push_back("plist");
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric   // Disable the presentation of standard compiler warnings when using
34660b57cec5SDimitry Andric   // --analyze.  We only want to show static analyzer diagnostics or frontend
34670b57cec5SDimitry Andric   // errors.
34680b57cec5SDimitry Andric   CmdArgs.push_back("-w");
34690b57cec5SDimitry Andric 
34700b57cec5SDimitry Andric   // Add -Xanalyzer arguments when running as analyzer.
34710b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
34720b57cec5SDimitry Andric }
34730b57cec5SDimitry Andric 
isValidSymbolName(StringRef S)3474753f127fSDimitry Andric static bool isValidSymbolName(StringRef S) {
3475753f127fSDimitry Andric   if (S.empty())
3476753f127fSDimitry Andric     return false;
3477753f127fSDimitry Andric 
3478753f127fSDimitry Andric   if (std::isdigit(S[0]))
3479753f127fSDimitry Andric     return false;
3480753f127fSDimitry Andric 
3481753f127fSDimitry Andric   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3482753f127fSDimitry Andric }
3483753f127fSDimitry Andric 
RenderSSPOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext)3484e8d8bef9SDimitry Andric static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3485e8d8bef9SDimitry Andric                              const ArgList &Args, ArgStringList &CmdArgs,
3486e8d8bef9SDimitry Andric                              bool KernelOrKext) {
34870b57cec5SDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
34900b57cec5SDimitry Andric   // doesn't even have a stack!
34910b57cec5SDimitry Andric   if (EffectiveTriple.isNVPTX())
34920b57cec5SDimitry Andric     return;
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric   // -stack-protector=0 is default.
3495e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3496e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
34970b57cec5SDimitry Andric       TC.GetDefaultStackProtectorLevel(KernelOrKext);
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
35000b57cec5SDimitry Andric                                options::OPT_fstack_protector_all,
35010b57cec5SDimitry Andric                                options::OPT_fstack_protector_strong,
35020b57cec5SDimitry Andric                                options::OPT_fstack_protector)) {
35030b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fstack_protector))
35040b57cec5SDimitry Andric       StackProtectorLevel =
3505e8d8bef9SDimitry Andric           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
35060b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
35070b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPStrong;
35080b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_all))
35090b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPReq;
3510bdd1243dSDimitry Andric 
3511bdd1243dSDimitry Andric     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3512bdd1243dSDimitry Andric       D.Diag(diag::warn_drv_unsupported_option_for_target)
3513bdd1243dSDimitry Andric           << A->getSpelling() << EffectiveTriple.getTriple();
3514bdd1243dSDimitry Andric       StackProtectorLevel = DefaultStackProtectorLevel;
3515bdd1243dSDimitry Andric     }
35160b57cec5SDimitry Andric   } else {
35170b57cec5SDimitry Andric     StackProtectorLevel = DefaultStackProtectorLevel;
35180b57cec5SDimitry Andric   }
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric   if (StackProtectorLevel) {
35210b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
35220b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
35230b57cec5SDimitry Andric   }
35240b57cec5SDimitry Andric 
35250b57cec5SDimitry Andric   // --param ssp-buffer-size=
35260b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__param)) {
35270b57cec5SDimitry Andric     StringRef Str(A->getValue());
35285f757f3fSDimitry Andric     if (Str.starts_with("ssp-buffer-size=")) {
35290b57cec5SDimitry Andric       if (StackProtectorLevel) {
35300b57cec5SDimitry Andric         CmdArgs.push_back("-stack-protector-buffer-size");
35310b57cec5SDimitry Andric         // FIXME: Verify the argument is a valid integer.
35320b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
35330b57cec5SDimitry Andric       }
35340b57cec5SDimitry Andric       A->claim();
35350b57cec5SDimitry Andric     }
35360b57cec5SDimitry Andric   }
3537e8d8bef9SDimitry Andric 
3538e8d8bef9SDimitry Andric   const std::string &TripleStr = EffectiveTriple.getTriple();
3539e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3540e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3541349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3542349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3543e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3544e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3545349cc55cSDimitry Andric     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3546349cc55cSDimitry Andric          EffectiveTriple.isThumb()) &&
3547349cc55cSDimitry Andric         Value != "tls" && Value != "global") {
3548e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3549fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "tls global";
3550fe6060f1SDimitry Andric       return;
3551fe6060f1SDimitry Andric     }
3552349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3553349cc55cSDimitry Andric         Value == "tls") {
3554349cc55cSDimitry Andric       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3555349cc55cSDimitry Andric         D.Diag(diag::err_drv_ssp_missing_offset_argument)
3556349cc55cSDimitry Andric             << A->getAsString(Args);
3557349cc55cSDimitry Andric         return;
3558349cc55cSDimitry Andric       }
3559349cc55cSDimitry Andric       // Check whether the target subarch supports the hardware TLS register
356004eeddc0SDimitry Andric       if (!arm::isHardTPSupported(EffectiveTriple)) {
3561349cc55cSDimitry Andric         D.Diag(diag::err_target_unsupported_tp_hard)
3562349cc55cSDimitry Andric             << EffectiveTriple.getArchName();
3563349cc55cSDimitry Andric         return;
3564349cc55cSDimitry Andric       }
3565349cc55cSDimitry Andric       // Check whether the user asked for something other than -mtp=cp15
3566349cc55cSDimitry Andric       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3567349cc55cSDimitry Andric         StringRef Value = A->getValue();
3568349cc55cSDimitry Andric         if (Value != "cp15") {
3569349cc55cSDimitry Andric           D.Diag(diag::err_drv_argument_not_allowed_with)
3570349cc55cSDimitry Andric               << A->getAsString(Args) << "-mstack-protector-guard=tls";
3571349cc55cSDimitry Andric           return;
3572349cc55cSDimitry Andric         }
3573349cc55cSDimitry Andric       }
3574349cc55cSDimitry Andric       CmdArgs.push_back("-target-feature");
357506c3fb27SDimitry Andric       CmdArgs.push_back("+read-tp-tpidruro");
3576349cc55cSDimitry Andric     }
3577fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3578fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3579fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "sysreg global";
3580e8d8bef9SDimitry Andric       return;
3581e8d8bef9SDimitry Andric     }
3582e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3583e8d8bef9SDimitry Andric   }
3584e8d8bef9SDimitry Andric 
3585e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3586e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3587349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3588349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3589e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3590e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3591fe6060f1SDimitry Andric     int Offset;
3592e8d8bef9SDimitry Andric     if (Value.getAsInteger(10, Offset)) {
3593e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3594e8d8bef9SDimitry Andric       return;
3595e8d8bef9SDimitry Andric     }
3596349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3597349cc55cSDimitry Andric         (Offset < 0 || Offset > 0xfffff)) {
3598349cc55cSDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
3599349cc55cSDimitry Andric           << A->getOption().getName() << Value;
3600349cc55cSDimitry Andric       return;
3601349cc55cSDimitry Andric     }
3602e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3603e8d8bef9SDimitry Andric   }
3604e8d8bef9SDimitry Andric 
3605e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3606e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3607fe6060f1SDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3608e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3609e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3610e8d8bef9SDimitry Andric     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3611e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3612fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "fs gs";
3613fe6060f1SDimitry Andric       return;
3614fe6060f1SDimitry Andric     }
3615fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3616fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3617e8d8bef9SDimitry Andric       return;
3618e8d8bef9SDimitry Andric     }
3619e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3620e8d8bef9SDimitry Andric   }
3621753f127fSDimitry Andric 
3622753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3623753f127fSDimitry Andric     StringRef Value = A->getValue();
3624753f127fSDimitry Andric     if (!isValidSymbolName(Value)) {
3625753f127fSDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
3626753f127fSDimitry Andric           << A->getOption().getName() << "legal symbol name";
3627753f127fSDimitry Andric       return;
3628753f127fSDimitry Andric     }
3629753f127fSDimitry Andric     A->render(Args, CmdArgs);
3630753f127fSDimitry Andric   }
36310b57cec5SDimitry Andric }
36320b57cec5SDimitry Andric 
RenderSCPOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)36335ffd83dbSDimitry Andric static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
36345ffd83dbSDimitry Andric                              ArgStringList &CmdArgs) {
36355ffd83dbSDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
36365ffd83dbSDimitry Andric 
36373063e1e5SEd Maste   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
36385ffd83dbSDimitry Andric     return;
36395ffd83dbSDimitry Andric 
36405ffd83dbSDimitry Andric   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
36415f757f3fSDimitry Andric       !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
36425ffd83dbSDimitry Andric     return;
36435ffd83dbSDimitry Andric 
364481ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
364581ad6265SDimitry Andric                     options::OPT_fno_stack_clash_protection);
36465ffd83dbSDimitry Andric }
36475ffd83dbSDimitry Andric 
RenderTrivialAutoVarInitOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)36480b57cec5SDimitry Andric static void RenderTrivialAutoVarInitOptions(const Driver &D,
36490b57cec5SDimitry Andric                                             const ToolChain &TC,
36500b57cec5SDimitry Andric                                             const ArgList &Args,
36510b57cec5SDimitry Andric                                             ArgStringList &CmdArgs) {
36520b57cec5SDimitry Andric   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
36530b57cec5SDimitry Andric   StringRef TrivialAutoVarInit = "";
36540b57cec5SDimitry Andric 
36550b57cec5SDimitry Andric   for (const Arg *A : Args) {
36560b57cec5SDimitry Andric     switch (A->getOption().getID()) {
36570b57cec5SDimitry Andric     default:
36580b57cec5SDimitry Andric       continue;
36590b57cec5SDimitry Andric     case options::OPT_ftrivial_auto_var_init: {
36600b57cec5SDimitry Andric       A->claim();
36610b57cec5SDimitry Andric       StringRef Val = A->getValue();
36620b57cec5SDimitry Andric       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
36630b57cec5SDimitry Andric         TrivialAutoVarInit = Val;
36640b57cec5SDimitry Andric       else
36650b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3666bdd1243dSDimitry Andric             << A->getSpelling() << Val;
36670b57cec5SDimitry Andric       break;
36680b57cec5SDimitry Andric     }
36690b57cec5SDimitry Andric     }
36700b57cec5SDimitry Andric   }
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric   if (TrivialAutoVarInit.empty())
36730b57cec5SDimitry Andric     switch (DefaultTrivialAutoVarInit) {
36740b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
36750b57cec5SDimitry Andric       break;
36760b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Pattern:
36770b57cec5SDimitry Andric       TrivialAutoVarInit = "pattern";
36780b57cec5SDimitry Andric       break;
36790b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Zero:
36800b57cec5SDimitry Andric       TrivialAutoVarInit = "zero";
36810b57cec5SDimitry Andric       break;
36820b57cec5SDimitry Andric     }
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric   if (!TrivialAutoVarInit.empty()) {
36850b57cec5SDimitry Andric     CmdArgs.push_back(
36860b57cec5SDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
36870b57cec5SDimitry Andric   }
36885ffd83dbSDimitry Andric 
36895ffd83dbSDimitry Andric   if (Arg *A =
36905ffd83dbSDimitry Andric           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
36915ffd83dbSDimitry Andric     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
36925ffd83dbSDimitry Andric         StringRef(
36935ffd83dbSDimitry Andric             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
36945ffd83dbSDimitry Andric             "uninitialized")
36955ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
36965ffd83dbSDimitry Andric     A->claim();
36975ffd83dbSDimitry Andric     StringRef Val = A->getValue();
36985ffd83dbSDimitry Andric     if (std::stoi(Val.str()) <= 0)
36995ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
37005ffd83dbSDimitry Andric     CmdArgs.push_back(
37015ffd83dbSDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
37025ffd83dbSDimitry Andric   }
37037a6dacacSDimitry Andric 
37047a6dacacSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
37057a6dacacSDimitry Andric     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
37067a6dacacSDimitry Andric         StringRef(
37077a6dacacSDimitry Andric             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
37087a6dacacSDimitry Andric             "uninitialized")
37097a6dacacSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
37107a6dacacSDimitry Andric     A->claim();
37117a6dacacSDimitry Andric     StringRef Val = A->getValue();
37127a6dacacSDimitry Andric     if (std::stoi(Val.str()) <= 0)
37137a6dacacSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
37147a6dacacSDimitry Andric     CmdArgs.push_back(
37157a6dacacSDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
37167a6dacacSDimitry Andric   }
37170b57cec5SDimitry Andric }
37180b57cec5SDimitry Andric 
RenderOpenCLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3719fe6060f1SDimitry Andric static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3720fe6060f1SDimitry Andric                                 types::ID InputType) {
37215ffd83dbSDimitry Andric   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
37225ffd83dbSDimitry Andric   // for denormal flushing handling based on the target.
37230b57cec5SDimitry Andric   const unsigned ForwardedArguments[] = {
37240b57cec5SDimitry Andric       options::OPT_cl_opt_disable,
37250b57cec5SDimitry Andric       options::OPT_cl_strict_aliasing,
37260b57cec5SDimitry Andric       options::OPT_cl_single_precision_constant,
37270b57cec5SDimitry Andric       options::OPT_cl_finite_math_only,
37280b57cec5SDimitry Andric       options::OPT_cl_kernel_arg_info,
37290b57cec5SDimitry Andric       options::OPT_cl_unsafe_math_optimizations,
37300b57cec5SDimitry Andric       options::OPT_cl_fast_relaxed_math,
37310b57cec5SDimitry Andric       options::OPT_cl_mad_enable,
37320b57cec5SDimitry Andric       options::OPT_cl_no_signed_zeros,
37330b57cec5SDimitry Andric       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
37340b57cec5SDimitry Andric       options::OPT_cl_uniform_work_group_size
37350b57cec5SDimitry Andric   };
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
37380b57cec5SDimitry Andric     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
37390b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
374081ad6265SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
374181ad6265SDimitry Andric     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
374281ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
37430b57cec5SDimitry Andric   }
37440b57cec5SDimitry Andric 
37450b57cec5SDimitry Andric   for (const auto &Arg : ForwardedArguments)
37460b57cec5SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
37470b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3748fe6060f1SDimitry Andric 
3749fe6060f1SDimitry Andric   // Only add the default headers if we are compiling OpenCL sources.
3750fe6060f1SDimitry Andric   if ((types::isOpenCL(InputType) ||
3751fe6060f1SDimitry Andric        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3752fe6060f1SDimitry Andric       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3753fe6060f1SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
3754fe6060f1SDimitry Andric     CmdArgs.push_back("-fdeclare-opencl-builtins");
3755fe6060f1SDimitry Andric   }
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric 
RenderHLSLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)375881ad6265SDimitry Andric static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
375981ad6265SDimitry Andric                               types::ID InputType) {
376081ad6265SDimitry Andric   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
376181ad6265SDimitry Andric                                          options::OPT_D,
3762fcaf7f86SDimitry Andric                                          options::OPT_I,
3763bdd1243dSDimitry Andric                                          options::OPT_O,
376481ad6265SDimitry Andric                                          options::OPT_emit_llvm,
3765bdd1243dSDimitry Andric                                          options::OPT_emit_obj,
376681ad6265SDimitry Andric                                          options::OPT_disable_llvm_passes,
3767bdd1243dSDimitry Andric                                          options::OPT_fnative_half_type,
3768bdd1243dSDimitry Andric                                          options::OPT_hlsl_entrypoint};
3769bdd1243dSDimitry Andric   if (!types::isHLSL(InputType))
3770bdd1243dSDimitry Andric     return;
377181ad6265SDimitry Andric   for (const auto &Arg : ForwardedArguments)
377281ad6265SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
377381ad6265SDimitry Andric       A->renderAsInput(Args, CmdArgs);
377481ad6265SDimitry Andric   // Add the default headers if dxc_no_stdinc is not set.
3775bdd1243dSDimitry Andric   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3776bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nostdinc))
377781ad6265SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
377881ad6265SDimitry Andric }
377981ad6265SDimitry Andric 
RenderOpenACCOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)37805f757f3fSDimitry Andric static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
37815f757f3fSDimitry Andric                                  ArgStringList &CmdArgs, types::ID InputType) {
37825f757f3fSDimitry Andric   if (!Args.hasArg(options::OPT_fopenacc))
37835f757f3fSDimitry Andric     return;
37845f757f3fSDimitry Andric 
37855f757f3fSDimitry Andric   CmdArgs.push_back("-fopenacc");
37865f757f3fSDimitry Andric 
37875f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
37885f757f3fSDimitry Andric     StringRef Value = A->getValue();
37895f757f3fSDimitry Andric     int Version;
37905f757f3fSDimitry Andric     if (!Value.getAsInteger(10, Version))
37915f757f3fSDimitry Andric       A->renderAsInput(Args, CmdArgs);
37925f757f3fSDimitry Andric     else
37935f757f3fSDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << Value;
37945f757f3fSDimitry Andric   }
37955f757f3fSDimitry Andric }
37965f757f3fSDimitry Andric 
RenderARCMigrateToolOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)37970b57cec5SDimitry Andric static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
37980b57cec5SDimitry Andric                                         ArgStringList &CmdArgs) {
37990b57cec5SDimitry Andric   bool ARCMTEnabled = false;
38000b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
38010b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
38020b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_modify,
38030b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_migrate)) {
38040b57cec5SDimitry Andric       ARCMTEnabled = true;
38050b57cec5SDimitry Andric       switch (A->getOption().getID()) {
38060b57cec5SDimitry Andric       default: llvm_unreachable("missed a case");
38070b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_check:
3808e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=check");
38090b57cec5SDimitry Andric         break;
38100b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_modify:
3811e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=modify");
38120b57cec5SDimitry Andric         break;
38130b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_migrate:
3814e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=migrate");
38150b57cec5SDimitry Andric         CmdArgs.push_back("-mt-migrate-directory");
38160b57cec5SDimitry Andric         CmdArgs.push_back(A->getValue());
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
38190b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
38200b57cec5SDimitry Andric         break;
38210b57cec5SDimitry Andric       }
38220b57cec5SDimitry Andric     }
38230b57cec5SDimitry Andric   } else {
38240b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
38250b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
38260b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
38270b57cec5SDimitry Andric   }
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
38300b57cec5SDimitry Andric     if (ARCMTEnabled)
38310b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
38320b57cec5SDimitry Andric           << A->getAsString(Args) << "-ccc-arcmt-migrate";
38330b57cec5SDimitry Andric 
38340b57cec5SDimitry Andric     CmdArgs.push_back("-mt-migrate-directory");
38350b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
38380b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_subscripting,
38390b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_property)) {
38400b57cec5SDimitry Andric       // None specified, means enable them all.
38410b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-literals");
38420b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-subscripting");
38430b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-property");
38440b57cec5SDimitry Andric     } else {
38450b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
38460b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
38470b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
38480b57cec5SDimitry Andric     }
38490b57cec5SDimitry Andric   } else {
38500b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
38510b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
38520b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
38530b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
38540b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
38550b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
38560b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
38570b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
38580b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
38590b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
38600b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
38610b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
38620b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
38630b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
38640b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3865349cc55cSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
38660b57cec5SDimitry Andric   }
38670b57cec5SDimitry Andric }
38680b57cec5SDimitry Andric 
RenderBuiltinOptions(const ToolChain & TC,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs)38690b57cec5SDimitry Andric static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
38700b57cec5SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
38710b57cec5SDimitry Andric   // -fbuiltin is default unless -mkernel is used.
38720b57cec5SDimitry Andric   bool UseBuiltins =
38730b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
38740b57cec5SDimitry Andric                    !Args.hasArg(options::OPT_mkernel));
38750b57cec5SDimitry Andric   if (!UseBuiltins)
38760b57cec5SDimitry Andric     CmdArgs.push_back("-fno-builtin");
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric   // -ffreestanding implies -fno-builtin.
38790b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_ffreestanding))
38800b57cec5SDimitry Andric     UseBuiltins = false;
38810b57cec5SDimitry Andric 
38820b57cec5SDimitry Andric   // Process the -fno-builtin-* options.
388381ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
388481ad6265SDimitry Andric     A->claim();
38850b57cec5SDimitry Andric 
38860b57cec5SDimitry Andric     // If -fno-builtin is specified, then there's no need to pass the option to
38870b57cec5SDimitry Andric     // the frontend.
388881ad6265SDimitry Andric     if (UseBuiltins)
388981ad6265SDimitry Andric       A->render(Args, CmdArgs);
38900b57cec5SDimitry Andric   }
38910b57cec5SDimitry Andric 
38920b57cec5SDimitry Andric   // le32-specific flags:
38930b57cec5SDimitry Andric   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
38940b57cec5SDimitry Andric   //                     by default.
38950b57cec5SDimitry Andric   if (TC.getArch() == llvm::Triple::le32)
38960b57cec5SDimitry Andric     CmdArgs.push_back("-fno-math-builtin");
38970b57cec5SDimitry Andric }
38980b57cec5SDimitry Andric 
getDefaultModuleCachePath(SmallVectorImpl<char> & Result)38995ffd83dbSDimitry Andric bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
390081ad6265SDimitry Andric   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
390181ad6265SDimitry Andric     Twine Path{Str};
390281ad6265SDimitry Andric     Path.toVector(Result);
390381ad6265SDimitry Andric     return Path.getSingleStringRef() != "";
390481ad6265SDimitry Andric   }
39055ffd83dbSDimitry Andric   if (llvm::sys::path::cache_directory(Result)) {
39065ffd83dbSDimitry Andric     llvm::sys::path::append(Result, "clang");
39070b57cec5SDimitry Andric     llvm::sys::path::append(Result, "ModuleCache");
39085ffd83dbSDimitry Andric     return true;
39095ffd83dbSDimitry Andric   }
39105ffd83dbSDimitry Andric   return false;
39110b57cec5SDimitry Andric }
39120b57cec5SDimitry Andric 
39130fca6ea1SDimitry Andric llvm::SmallString<256>
getCXX20NamedModuleOutputPath(const ArgList & Args,const char * BaseInput)39140fca6ea1SDimitry Andric clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
39150fca6ea1SDimitry Andric                                                     const char *BaseInput) {
39160fca6ea1SDimitry Andric   if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
39170fca6ea1SDimitry Andric     return StringRef(ModuleOutputEQ->getValue());
39180fca6ea1SDimitry Andric 
39190fca6ea1SDimitry Andric   SmallString<256> OutputPath;
39200fca6ea1SDimitry Andric   if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
39210fca6ea1SDimitry Andric       FinalOutput && Args.hasArg(options::OPT_c))
39220fca6ea1SDimitry Andric     OutputPath = FinalOutput->getValue();
39230fca6ea1SDimitry Andric   else
39240fca6ea1SDimitry Andric     OutputPath = BaseInput;
39250fca6ea1SDimitry Andric 
39260fca6ea1SDimitry Andric   const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
39270fca6ea1SDimitry Andric   llvm::sys::path::replace_extension(OutputPath, Extension);
39280fca6ea1SDimitry Andric   return OutputPath;
39290fca6ea1SDimitry Andric }
39300fca6ea1SDimitry Andric 
RenderModulesOptions(Compilation & C,const Driver & D,const ArgList & Args,const InputInfo & Input,const InputInfo & Output,bool HaveStd20,ArgStringList & CmdArgs)3931bdd1243dSDimitry Andric static bool RenderModulesOptions(Compilation &C, const Driver &D,
39320b57cec5SDimitry Andric                                  const ArgList &Args, const InputInfo &Input,
39335f757f3fSDimitry Andric                                  const InputInfo &Output, bool HaveStd20,
3934bdd1243dSDimitry Andric                                  ArgStringList &CmdArgs) {
3935bdd1243dSDimitry Andric   bool IsCXX = types::isCXX(Input.getType());
39365f757f3fSDimitry Andric   bool HaveStdCXXModules = IsCXX && HaveStd20;
3937bdd1243dSDimitry Andric   bool HaveModules = HaveStdCXXModules;
3938bdd1243dSDimitry Andric 
39390b57cec5SDimitry Andric   // -fmodules enables the use of precompiled modules (off by default).
39400b57cec5SDimitry Andric   // Users can pass -fno-cxx-modules to turn off modules support for
39410b57cec5SDimitry Andric   // C++/Objective-C++ programs.
39420b57cec5SDimitry Andric   bool HaveClangModules = false;
39430b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
39440b57cec5SDimitry Andric     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
39450b57cec5SDimitry Andric                                      options::OPT_fno_cxx_modules, true);
3946bdd1243dSDimitry Andric     if (AllowedInCXX || !IsCXX) {
39470b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules");
39480b57cec5SDimitry Andric       HaveClangModules = true;
39490b57cec5SDimitry Andric     }
39500b57cec5SDimitry Andric   }
39510b57cec5SDimitry Andric 
39520b57cec5SDimitry Andric   HaveModules |= HaveClangModules;
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric   // -fmodule-maps enables implicit reading of module map files. By default,
39550b57cec5SDimitry Andric   // this is enabled if we are using Clang's flavor of precompiled modules.
39560b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
39570b57cec5SDimitry Andric                    options::OPT_fno_implicit_module_maps, HaveClangModules))
39580b57cec5SDimitry Andric     CmdArgs.push_back("-fimplicit-module-maps");
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric   // -fmodules-decluse checks that modules used are declared so (off by default)
396181ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
396281ad6265SDimitry Andric                     options::OPT_fno_modules_decluse);
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
39650b57cec5SDimitry Andric   // all #included headers are part of modules.
39660b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
39670b57cec5SDimitry Andric                    options::OPT_fno_modules_strict_decluse, false))
39680b57cec5SDimitry Andric     CmdArgs.push_back("-fmodules-strict-decluse");
39690b57cec5SDimitry Andric 
39700b57cec5SDimitry Andric   // -fno-implicit-modules turns off implicitly compiling modules on demand.
39710b57cec5SDimitry Andric   bool ImplicitModules = false;
39720b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fimplicit_modules,
39730b57cec5SDimitry Andric                     options::OPT_fno_implicit_modules, HaveClangModules)) {
39740b57cec5SDimitry Andric     if (HaveModules)
39750b57cec5SDimitry Andric       CmdArgs.push_back("-fno-implicit-modules");
39760b57cec5SDimitry Andric   } else if (HaveModules) {
39770b57cec5SDimitry Andric     ImplicitModules = true;
39780b57cec5SDimitry Andric     // -fmodule-cache-path specifies where our implicitly-built module files
39790b57cec5SDimitry Andric     // should be written.
39800b57cec5SDimitry Andric     SmallString<128> Path;
39810b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
39820b57cec5SDimitry Andric       Path = A->getValue();
39830b57cec5SDimitry Andric 
39845ffd83dbSDimitry Andric     bool HasPath = true;
39850b57cec5SDimitry Andric     if (C.isForDiagnostics()) {
39860b57cec5SDimitry Andric       // When generating crash reports, we want to emit the modules along with
39870b57cec5SDimitry Andric       // the reproduction sources, so we ignore any provided module path.
39880b57cec5SDimitry Andric       Path = Output.getFilename();
39890b57cec5SDimitry Andric       llvm::sys::path::replace_extension(Path, ".cache");
39900b57cec5SDimitry Andric       llvm::sys::path::append(Path, "modules");
39910b57cec5SDimitry Andric     } else if (Path.empty()) {
39920b57cec5SDimitry Andric       // No module path was provided: use the default.
39935ffd83dbSDimitry Andric       HasPath = Driver::getDefaultModuleCachePath(Path);
39940b57cec5SDimitry Andric     }
39950b57cec5SDimitry Andric 
39965ffd83dbSDimitry Andric     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
39975ffd83dbSDimitry Andric     // That being said, that failure is unlikely and not caching is harmless.
39985ffd83dbSDimitry Andric     if (HasPath) {
39990b57cec5SDimitry Andric       const char Arg[] = "-fmodules-cache-path=";
40000b57cec5SDimitry Andric       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
40010b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Path));
40020b57cec5SDimitry Andric     }
40035ffd83dbSDimitry Andric   }
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric   if (HaveModules) {
4006e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4007e8d8bef9SDimitry Andric                      options::OPT_fno_prebuilt_implicit_modules, false))
4008e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprebuilt-implicit-modules");
4009a7dea167SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4010a7dea167SDimitry Andric                      options::OPT_fno_modules_validate_input_files_content,
4011a7dea167SDimitry Andric                      false))
4012a7dea167SDimitry Andric       CmdArgs.push_back("-fvalidate-ast-input-files-content");
40130b57cec5SDimitry Andric   }
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric   // -fmodule-name specifies the module that is currently being built (or
40160b57cec5SDimitry Andric   // used for header checking by -fmodule-maps).
40170b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
40180b57cec5SDimitry Andric 
40190b57cec5SDimitry Andric   // -fmodule-map-file can be used to specify files containing module
40200b57cec5SDimitry Andric   // definitions.
40210b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
40220b57cec5SDimitry Andric 
40230b57cec5SDimitry Andric   // -fbuiltin-module-map can be used to load the clang
40240b57cec5SDimitry Andric   // builtin headers modulemap file.
40250b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
40260b57cec5SDimitry Andric     SmallString<128> BuiltinModuleMap(D.ResourceDir);
40270b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "include");
40280b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
40290b57cec5SDimitry Andric     if (llvm::sys::fs::exists(BuiltinModuleMap))
40300b57cec5SDimitry Andric       CmdArgs.push_back(
40310b57cec5SDimitry Andric           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
40320b57cec5SDimitry Andric   }
40330b57cec5SDimitry Andric 
40340b57cec5SDimitry Andric   // The -fmodule-file=<name>=<file> form specifies the mapping of module
40350b57cec5SDimitry Andric   // names to precompiled module files (the module is loaded only if used).
40360b57cec5SDimitry Andric   // The -fmodule-file=<file> form can be used to unconditionally load
40370b57cec5SDimitry Andric   // precompiled module files (whether used or not).
403806c3fb27SDimitry Andric   if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
40390b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
404006c3fb27SDimitry Andric 
404106c3fb27SDimitry Andric     // -fprebuilt-module-path specifies where to load the prebuilt module files.
404206c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
404306c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
404406c3fb27SDimitry Andric           std::string("-fprebuilt-module-path=") + A->getValue()));
404506c3fb27SDimitry Andric       A->claim();
404606c3fb27SDimitry Andric     }
404706c3fb27SDimitry Andric   } else
40480b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodule_file);
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   // When building modules and generating crashdumps, we need to dump a module
40510b57cec5SDimitry Andric   // dependency VFS alongside the output.
40520b57cec5SDimitry Andric   if (HaveClangModules && C.isForDiagnostics()) {
40530b57cec5SDimitry Andric     SmallString<128> VFSDir(Output.getFilename());
40540b57cec5SDimitry Andric     llvm::sys::path::replace_extension(VFSDir, ".cache");
40550b57cec5SDimitry Andric     // Add the cache directory as a temp so the crash diagnostics pick it up.
40560b57cec5SDimitry Andric     C.addTempFile(Args.MakeArgString(VFSDir));
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric     llvm::sys::path::append(VFSDir, "vfs");
40590b57cec5SDimitry Andric     CmdArgs.push_back("-module-dependency-dir");
40600b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(VFSDir));
40610b57cec5SDimitry Andric   }
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   if (HaveClangModules)
40640b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
40650b57cec5SDimitry Andric 
40660b57cec5SDimitry Andric   // Pass through all -fmodules-ignore-macro arguments.
40670b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
40680b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
40690b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
40700b57cec5SDimitry Andric 
4071753f127fSDimitry Andric   if (HaveClangModules) {
40720b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
40750b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
40760b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
40770b57cec5SDimitry Andric             << A->getAsString(Args) << "-fbuild-session-timestamp";
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric       llvm::sys::fs::file_status Status;
40800b57cec5SDimitry Andric       if (llvm::sys::fs::status(A->getValue(), Status))
40810b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << A->getValue();
4082349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
4083349cc55cSDimitry Andric           "-fbuild-session-timestamp=" +
4084349cc55cSDimitry Andric           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4085349cc55cSDimitry Andric                     Status.getLastModificationTime().time_since_epoch())
40860b57cec5SDimitry Andric                     .count())));
40870b57cec5SDimitry Andric     }
40880b57cec5SDimitry Andric 
4089753f127fSDimitry Andric     if (Args.getLastArg(
4090753f127fSDimitry Andric             options::OPT_fmodules_validate_once_per_build_session)) {
40910b57cec5SDimitry Andric       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
40920b57cec5SDimitry Andric                            options::OPT_fbuild_session_file))
40930b57cec5SDimitry Andric         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs,
40960b57cec5SDimitry Andric                       options::OPT_fmodules_validate_once_per_build_session);
40970b57cec5SDimitry Andric     }
40980b57cec5SDimitry Andric 
40990b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
41000b57cec5SDimitry Andric                      options::OPT_fno_modules_validate_system_headers,
41010b57cec5SDimitry Andric                      ImplicitModules))
41020b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules-validate-system-headers");
41030b57cec5SDimitry Andric 
4104753f127fSDimitry Andric     Args.AddLastArg(CmdArgs,
4105753f127fSDimitry Andric                     options::OPT_fmodules_disable_diagnostic_validation);
4106753f127fSDimitry Andric   } else {
4107753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4108753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4109753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4110753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4111753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4112753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4113753f127fSDimitry Andric   }
4114bdd1243dSDimitry Andric 
4115b3edf446SDimitry Andric   // FIXME: We provisionally don't check ODR violations for decls in the global
4116b3edf446SDimitry Andric   // module fragment.
4117b3edf446SDimitry Andric   CmdArgs.push_back("-fskip-odr-check-in-gmf");
4118b3edf446SDimitry Andric 
41190fca6ea1SDimitry Andric   if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
41200fca6ea1SDimitry Andric       (Input.getType() == driver::types::TY_CXXModule ||
41210fca6ea1SDimitry Andric        Input.getType() == driver::types::TY_PP_CXXModule)) {
41220fca6ea1SDimitry Andric     CmdArgs.push_back("-fexperimental-modules-reduced-bmi");
41230fca6ea1SDimitry Andric 
41240fca6ea1SDimitry Andric     if (Args.hasArg(options::OPT_fmodule_output_EQ))
41250fca6ea1SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
41260fca6ea1SDimitry Andric     else
41270fca6ea1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
41280fca6ea1SDimitry Andric           "-fmodule-output=" +
41290fca6ea1SDimitry Andric           getCXX20NamedModuleOutputPath(Args, Input.getBaseInput())));
41300fca6ea1SDimitry Andric   }
41310fca6ea1SDimitry Andric 
41320fca6ea1SDimitry Andric   // Noop if we see '-fexperimental-modules-reduced-bmi' with other translation
41330fca6ea1SDimitry Andric   // units than module units. This is more user friendly to allow end uers to
41340fca6ea1SDimitry Andric   // enable this feature without asking for help from build systems.
41350fca6ea1SDimitry Andric   Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
41360fca6ea1SDimitry Andric 
41370fca6ea1SDimitry Andric   // We need to include the case the input file is a module file here.
41380fca6ea1SDimitry Andric   // Since the default compilation model for C++ module interface unit will
41390fca6ea1SDimitry Andric   // create temporary module file and compile the temporary module file
41400fca6ea1SDimitry Andric   // to get the object file. Then the `-fmodule-output` flag will be
41410fca6ea1SDimitry Andric   // brought to the second compilation process. So we have to claim it for
41420fca6ea1SDimitry Andric   // the case too.
41430fca6ea1SDimitry Andric   if (Input.getType() == driver::types::TY_CXXModule ||
41440fca6ea1SDimitry Andric       Input.getType() == driver::types::TY_PP_CXXModule ||
41450fca6ea1SDimitry Andric       Input.getType() == driver::types::TY_ModuleFile) {
4146bdd1243dSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodule_output);
4147bdd1243dSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
41480fca6ea1SDimitry Andric   }
4149bdd1243dSDimitry Andric 
4150bdd1243dSDimitry Andric   return HaveModules;
41510b57cec5SDimitry Andric }
41520b57cec5SDimitry Andric 
RenderCharacterOptions(const ArgList & Args,const llvm::Triple & T,ArgStringList & CmdArgs)41530b57cec5SDimitry Andric static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
41540b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
41550b57cec5SDimitry Andric   // -fsigned-char is default.
41560b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
41570b57cec5SDimitry Andric                                      options::OPT_fno_signed_char,
41580b57cec5SDimitry Andric                                      options::OPT_funsigned_char,
41590b57cec5SDimitry Andric                                      options::OPT_fno_unsigned_char)) {
41600b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_funsigned_char) ||
41610b57cec5SDimitry Andric         A->getOption().matches(options::OPT_fno_signed_char)) {
41620b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-char");
41630b57cec5SDimitry Andric     }
41640b57cec5SDimitry Andric   } else if (!isSignedCharDefault(T)) {
41650b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-char");
41660b57cec5SDimitry Andric   }
41670b57cec5SDimitry Andric 
41680b57cec5SDimitry Andric   // The default depends on the language standard.
41690b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
41720b57cec5SDimitry Andric                                      options::OPT_fno_short_wchar)) {
41730b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fshort_wchar)) {
41740b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=short");
41750b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-wchar");
41760b57cec5SDimitry Andric     } else {
41770b57cec5SDimitry Andric       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
41780b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=int");
4179e8d8bef9SDimitry Andric       if (T.isOSzOS() ||
4180e8d8bef9SDimitry Andric           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
41810b57cec5SDimitry Andric         CmdArgs.push_back("-fno-signed-wchar");
41820b57cec5SDimitry Andric       else
41830b57cec5SDimitry Andric         CmdArgs.push_back("-fsigned-wchar");
41840b57cec5SDimitry Andric     }
418506c3fb27SDimitry Andric   } else if (T.isOSzOS())
418606c3fb27SDimitry Andric     CmdArgs.push_back("-fno-signed-wchar");
41870b57cec5SDimitry Andric }
41880b57cec5SDimitry Andric 
RenderObjCOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,ObjCRuntime & Runtime,bool InferCovariantReturns,const InputInfo & Input,ArgStringList & CmdArgs)41890b57cec5SDimitry Andric static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
41900b57cec5SDimitry Andric                               const llvm::Triple &T, const ArgList &Args,
41910b57cec5SDimitry Andric                               ObjCRuntime &Runtime, bool InferCovariantReturns,
41920b57cec5SDimitry Andric                               const InputInfo &Input, ArgStringList &CmdArgs) {
41930b57cec5SDimitry Andric   const llvm::Triple::ArchType Arch = TC.getArch();
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
41960b57cec5SDimitry Andric   // is the default. Except for deployment target of 10.5, next runtime is
41970b57cec5SDimitry Andric   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
41980b57cec5SDimitry Andric   if (Runtime.isNonFragile()) {
41990b57cec5SDimitry Andric     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
42000b57cec5SDimitry Andric                       options::OPT_fno_objc_legacy_dispatch,
42010b57cec5SDimitry Andric                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
42020b57cec5SDimitry Andric       if (TC.UseObjCMixedDispatch())
42030b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
42040b57cec5SDimitry Andric       else
42050b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
42060b57cec5SDimitry Andric     }
42070b57cec5SDimitry Andric   }
42080b57cec5SDimitry Andric 
42090b57cec5SDimitry Andric   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
42100b57cec5SDimitry Andric   // to do Array/Dictionary subscripting by default.
42110b57cec5SDimitry Andric   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
42120b57cec5SDimitry Andric       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
42130b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
42160b57cec5SDimitry Andric   // NOTE: This logic is duplicated in ToolChains.cpp.
42170b57cec5SDimitry Andric   if (isObjCAutoRefCount(Args)) {
42180b57cec5SDimitry Andric     TC.CheckObjCARC();
42190b57cec5SDimitry Andric 
42200b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-arc");
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric     // FIXME: It seems like this entire block, and several around it should be
42230b57cec5SDimitry Andric     // wrapped in isObjC, but for now we just use it here as this is where it
42240b57cec5SDimitry Andric     // was being used previously.
42250b57cec5SDimitry Andric     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
42260b57cec5SDimitry Andric       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
42270b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
42280b57cec5SDimitry Andric       else
42290b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
42300b57cec5SDimitry Andric     }
42310b57cec5SDimitry Andric 
42320b57cec5SDimitry Andric     // Allow the user to enable full exceptions code emission.
42330b57cec5SDimitry Andric     // We default off for Objective-C, on for Objective-C++.
42340b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
42350b57cec5SDimitry Andric                      options::OPT_fno_objc_arc_exceptions,
42360b57cec5SDimitry Andric                      /*Default=*/types::isCXX(Input.getType())))
42370b57cec5SDimitry Andric       CmdArgs.push_back("-fobjc-arc-exceptions");
42380b57cec5SDimitry Andric   }
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric   // Silence warning for full exception code emission options when explicitly
42410b57cec5SDimitry Andric   // set to use no ARC.
42420b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fno_objc_arc)) {
42430b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
42440b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
42450b57cec5SDimitry Andric   }
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric   // Allow the user to control whether messages can be converted to runtime
42480b57cec5SDimitry Andric   // functions.
42490b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
42500b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(
42510b57cec5SDimitry Andric         options::OPT_fobjc_convert_messages_to_runtime_calls,
42520b57cec5SDimitry Andric         options::OPT_fno_objc_convert_messages_to_runtime_calls);
42530b57cec5SDimitry Andric     if (Arg &&
42540b57cec5SDimitry Andric         Arg->getOption().matches(
42550b57cec5SDimitry Andric             options::OPT_fno_objc_convert_messages_to_runtime_calls))
42560b57cec5SDimitry Andric       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
42570b57cec5SDimitry Andric   }
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric   // -fobjc-infer-related-result-type is the default, except in the Objective-C
42600b57cec5SDimitry Andric   // rewriter.
42610b57cec5SDimitry Andric   if (InferCovariantReturns)
42620b57cec5SDimitry Andric     CmdArgs.push_back("-fno-objc-infer-related-result-type");
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   // Pass down -fobjc-weak or -fno-objc-weak if present.
42650b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
42660b57cec5SDimitry Andric     auto WeakArg =
42670b57cec5SDimitry Andric         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
42680b57cec5SDimitry Andric     if (!WeakArg) {
42690b57cec5SDimitry Andric       // nothing to do
42700b57cec5SDimitry Andric     } else if (!Runtime.allowsWeak()) {
42710b57cec5SDimitry Andric       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
42720b57cec5SDimitry Andric         D.Diag(diag::err_objc_weak_unsupported);
42730b57cec5SDimitry Andric     } else {
42740b57cec5SDimitry Andric       WeakArg->render(Args, CmdArgs);
42750b57cec5SDimitry Andric     }
42760b57cec5SDimitry Andric   }
4277fe6060f1SDimitry Andric 
4278fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4279fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
42800b57cec5SDimitry Andric }
42810b57cec5SDimitry Andric 
RenderDiagnosticsOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)42820b57cec5SDimitry Andric static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
42830b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) {
42840b57cec5SDimitry Andric   bool CaretDefault = true;
42850b57cec5SDimitry Andric   bool ColumnDefault = true;
42860b57cec5SDimitry Andric 
42870b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
42880b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_column,
42890b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_caret)) {
42900b57cec5SDimitry Andric     switch (A->getOption().getID()) {
42910b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_caret:
42920b57cec5SDimitry Andric       CaretDefault = true;
42930b57cec5SDimitry Andric       ColumnDefault = true;
42940b57cec5SDimitry Andric       break;
42950b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_column:
42960b57cec5SDimitry Andric       CaretDefault = false;
42970b57cec5SDimitry Andric       ColumnDefault = true;
42980b57cec5SDimitry Andric       break;
42990b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_classic:
43000b57cec5SDimitry Andric       CaretDefault = false;
43010b57cec5SDimitry Andric       ColumnDefault = false;
43020b57cec5SDimitry Andric       break;
43030b57cec5SDimitry Andric     }
43040b57cec5SDimitry Andric   }
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   // -fcaret-diagnostics is default.
43070b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
43080b57cec5SDimitry Andric                     options::OPT_fno_caret_diagnostics, CaretDefault))
43090b57cec5SDimitry Andric     CmdArgs.push_back("-fno-caret-diagnostics");
43100b57cec5SDimitry Andric 
431181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
431281ad6265SDimitry Andric                      options::OPT_fno_diagnostics_fixit_info);
431381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
431481ad6265SDimitry Andric                      options::OPT_fno_diagnostics_show_option);
43150b57cec5SDimitry Andric 
43160b57cec5SDimitry Andric   if (const Arg *A =
43170b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
43180b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-show-category");
43190b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
43200b57cec5SDimitry Andric   }
43210b57cec5SDimitry Andric 
432281ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
432381ad6265SDimitry Andric                     options::OPT_fno_diagnostics_show_hotness);
43240b57cec5SDimitry Andric 
43250b57cec5SDimitry Andric   if (const Arg *A =
43260b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
43270b57cec5SDimitry Andric     std::string Opt =
43280b57cec5SDimitry Andric         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
43290b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
43300b57cec5SDimitry Andric   }
43310b57cec5SDimitry Andric 
433206c3fb27SDimitry Andric   if (const Arg *A =
433306c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
433406c3fb27SDimitry Andric     std::string Opt =
433506c3fb27SDimitry Andric         std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
433606c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
433706c3fb27SDimitry Andric   }
433806c3fb27SDimitry Andric 
43390b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
43400b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
43410b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
4342fcaf7f86SDimitry Andric     if (StringRef(A->getValue()) == "sarif" ||
4343fcaf7f86SDimitry Andric         StringRef(A->getValue()) == "SARIF")
4344fcaf7f86SDimitry Andric       D.Diag(diag::warn_drv_sarif_format_unstable);
43450b57cec5SDimitry Andric   }
43460b57cec5SDimitry Andric 
43470b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(
43480b57cec5SDimitry Andric           options::OPT_fdiagnostics_show_note_include_stack,
43490b57cec5SDimitry Andric           options::OPT_fno_diagnostics_show_note_include_stack)) {
43500b57cec5SDimitry Andric     const Option &O = A->getOption();
43510b57cec5SDimitry Andric     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
43520b57cec5SDimitry Andric       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
43530b57cec5SDimitry Andric     else
43540b57cec5SDimitry Andric       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
43550b57cec5SDimitry Andric   }
43560b57cec5SDimitry Andric 
43570b57cec5SDimitry Andric   // Color diagnostics are parsed by the driver directly from argv and later
43580b57cec5SDimitry Andric   // re-parsed to construct this job; claim any possible color diagnostic here
43590b57cec5SDimitry Andric   // to avoid warn_drv_unused_argument and diagnose bad
43600b57cec5SDimitry Andric   // OPT_fdiagnostics_color_EQ values.
436181ad6265SDimitry Andric   Args.getLastArg(options::OPT_fcolor_diagnostics,
436281ad6265SDimitry Andric                   options::OPT_fno_color_diagnostics);
436381ad6265SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
43640b57cec5SDimitry Andric     StringRef Value(A->getValue());
43650b57cec5SDimitry Andric     if (Value != "always" && Value != "never" && Value != "auto")
436681ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
436781ad6265SDimitry Andric           << Value << A->getOption().getName();
43680b57cec5SDimitry Andric   }
43690b57cec5SDimitry Andric 
43700b57cec5SDimitry Andric   if (D.getDiags().getDiagnosticOptions().ShowColors)
43710b57cec5SDimitry Andric     CmdArgs.push_back("-fcolor-diagnostics");
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fansi_escape_codes))
43740b57cec5SDimitry Andric     CmdArgs.push_back("-fansi-escape-codes");
43750b57cec5SDimitry Andric 
437681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
437781ad6265SDimitry Andric                      options::OPT_fno_show_source_location);
43780b57cec5SDimitry Andric 
437906c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
438006c3fb27SDimitry Andric                      options::OPT_fno_diagnostics_show_line_numbers);
438106c3fb27SDimitry Andric 
43820b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
43830b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-absolute-paths");
43840b57cec5SDimitry Andric 
43850b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
43860b57cec5SDimitry Andric                     ColumnDefault))
43870b57cec5SDimitry Andric     CmdArgs.push_back("-fno-show-column");
43880b57cec5SDimitry Andric 
438981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
439081ad6265SDimitry Andric                      options::OPT_fno_spell_checking);
43910b57cec5SDimitry Andric }
43920b57cec5SDimitry Andric 
getDebugFissionKind(const Driver & D,const ArgList & Args,Arg * & Arg)4393fcaf7f86SDimitry Andric DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
43940b57cec5SDimitry Andric                                             const ArgList &Args, Arg *&Arg) {
4395e8d8bef9SDimitry Andric   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4396e8d8bef9SDimitry Andric                         options::OPT_gno_split_dwarf);
4397e8d8bef9SDimitry Andric   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
43980b57cec5SDimitry Andric     return DwarfFissionKind::None;
43990b57cec5SDimitry Andric 
44000b57cec5SDimitry Andric   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
44010b57cec5SDimitry Andric     return DwarfFissionKind::Split;
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric   StringRef Value = Arg->getValue();
44040b57cec5SDimitry Andric   if (Value == "split")
44050b57cec5SDimitry Andric     return DwarfFissionKind::Split;
44060b57cec5SDimitry Andric   if (Value == "single")
44070b57cec5SDimitry Andric     return DwarfFissionKind::Single;
44080b57cec5SDimitry Andric 
44090b57cec5SDimitry Andric   D.Diag(diag::err_drv_unsupported_option_argument)
4410bdd1243dSDimitry Andric       << Arg->getSpelling() << Arg->getValue();
44110b57cec5SDimitry Andric   return DwarfFissionKind::None;
44120b57cec5SDimitry Andric }
44130b57cec5SDimitry Andric 
renderDwarfFormat(const Driver & D,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs,unsigned DwarfVersion)4414fe6060f1SDimitry Andric static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4415fe6060f1SDimitry Andric                               const ArgList &Args, ArgStringList &CmdArgs,
4416fe6060f1SDimitry Andric                               unsigned DwarfVersion) {
4417fe6060f1SDimitry Andric   auto *DwarfFormatArg =
4418fe6060f1SDimitry Andric       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4419fe6060f1SDimitry Andric   if (!DwarfFormatArg)
4420fe6060f1SDimitry Andric     return;
4421fe6060f1SDimitry Andric 
4422fe6060f1SDimitry Andric   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4423fe6060f1SDimitry Andric     if (DwarfVersion < 3)
4424fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4425fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4426fe6060f1SDimitry Andric     else if (!T.isArch64Bit())
4427fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4428fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4429fe6060f1SDimitry Andric     else if (!T.isOSBinFormatELF())
4430fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4431fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4432fe6060f1SDimitry Andric   }
4433fe6060f1SDimitry Andric 
4434fe6060f1SDimitry Andric   DwarfFormatArg->render(Args, CmdArgs);
4435fe6060f1SDimitry Andric }
4436fe6060f1SDimitry Andric 
443706c3fb27SDimitry Andric static void
renderDebugOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,bool IRInput,ArgStringList & CmdArgs,const InputInfo & Output,llvm::codegenoptions::DebugInfoKind & DebugInfoKind,DwarfFissionKind & DwarfFission)443806c3fb27SDimitry Andric renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
44395f757f3fSDimitry Andric                    const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
44405f757f3fSDimitry Andric                    const InputInfo &Output,
444106c3fb27SDimitry Andric                    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
44420b57cec5SDimitry Andric                    DwarfFissionKind &DwarfFission) {
44430b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
44440b57cec5SDimitry Andric                    options::OPT_fno_debug_info_for_profiling, false) &&
44450b57cec5SDimitry Andric       checkDebugInfoOption(
44460b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
44470b57cec5SDimitry Andric     CmdArgs.push_back("-fdebug-info-for-profiling");
44480b57cec5SDimitry Andric 
44490b57cec5SDimitry Andric   // The 'g' groups options involve a somewhat intricate sequence of decisions
44500b57cec5SDimitry Andric   // about what to pass from the driver to the frontend, but by the time they
44510b57cec5SDimitry Andric   // reach cc1 they've been factored into three well-defined orthogonal choices:
44520b57cec5SDimitry Andric   //  * what level of debug info to generate
44530b57cec5SDimitry Andric   //  * what dwarf version to write
44540b57cec5SDimitry Andric   //  * what debugger tuning to use
44550b57cec5SDimitry Andric   // This avoids having to monkey around further in cc1 other than to disable
44560b57cec5SDimitry Andric   // codeview if not running in a Windows environment. Perhaps even that
44570b57cec5SDimitry Andric   // decision should be made in the driver as well though.
44580b57cec5SDimitry Andric   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric   bool SplitDWARFInlining =
44610b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4462480093f4SDimitry Andric                    options::OPT_fno_split_dwarf_inlining, false);
44630b57cec5SDimitry Andric 
4464e8d8bef9SDimitry Andric   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4465e8d8bef9SDimitry Andric   // object file generation and no IR generation, -gN should not be needed. So
4466e8d8bef9SDimitry Andric   // allow -gsplit-dwarf with either -gN or IR input.
4467e8d8bef9SDimitry Andric   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
44680b57cec5SDimitry Andric     Arg *SplitDWARFArg;
44690b57cec5SDimitry Andric     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
44700b57cec5SDimitry Andric     if (DwarfFission != DwarfFissionKind::None &&
44710b57cec5SDimitry Andric         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
44720b57cec5SDimitry Andric       DwarfFission = DwarfFissionKind::None;
44730b57cec5SDimitry Andric       SplitDWARFInlining = false;
44740b57cec5SDimitry Andric     }
4475e8d8bef9SDimitry Andric   }
4476e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
447706c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
44780b57cec5SDimitry Andric 
44790b57cec5SDimitry Andric     // If the last option explicitly specified a debug-info level, use it.
44800b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC) &&
44810b57cec5SDimitry Andric         A->getOption().matches(options::OPT_gN_Group)) {
448206c3fb27SDimitry Andric       DebugInfoKind = debugLevelToInfoKind(*A);
44830b57cec5SDimitry Andric       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
44840b57cec5SDimitry Andric       // complicated if you've disabled inline info in the skeleton CUs
44850b57cec5SDimitry Andric       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
44860b57cec5SDimitry Andric       // line-tables-only, so let those compose naturally in that case.
448706c3fb27SDimitry Andric       if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
448806c3fb27SDimitry Andric           DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
448906c3fb27SDimitry Andric           (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
44900b57cec5SDimitry Andric            SplitDWARFInlining))
44910b57cec5SDimitry Andric         DwarfFission = DwarfFissionKind::None;
44920b57cec5SDimitry Andric     }
44930b57cec5SDimitry Andric   }
44940b57cec5SDimitry Andric 
44950b57cec5SDimitry Andric   // If a debugger tuning argument appeared, remember it.
4496bdd1243dSDimitry Andric   bool HasDebuggerTuning = false;
44970b57cec5SDimitry Andric   if (const Arg *A =
44980b57cec5SDimitry Andric           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4499bdd1243dSDimitry Andric     HasDebuggerTuning = true;
45000b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC)) {
45010b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_glldb))
45020b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::LLDB;
45030b57cec5SDimitry Andric       else if (A->getOption().matches(options::OPT_gsce))
45040b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::SCE;
4505fe6060f1SDimitry Andric       else if (A->getOption().matches(options::OPT_gdbx))
4506fe6060f1SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::DBX;
45070b57cec5SDimitry Andric       else
45080b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::GDB;
45090b57cec5SDimitry Andric     }
45100b57cec5SDimitry Andric   }
45110b57cec5SDimitry Andric 
45120b57cec5SDimitry Andric   // If a -gdwarf argument appeared, remember it.
4513480093f4SDimitry Andric   bool EmitDwarf = false;
4514bdd1243dSDimitry Andric   if (const Arg *A = getDwarfNArg(Args))
4515bdd1243dSDimitry Andric     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
45160b57cec5SDimitry Andric 
45175f757f3fSDimitry Andric   bool EmitCodeView = false;
4518bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4519bdd1243dSDimitry Andric     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric   // If the user asked for debug info but did not explicitly specify -gcodeview
45220b57cec5SDimitry Andric   // or -gdwarf, ask the toolchain for the default format.
4523480093f4SDimitry Andric   if (!EmitCodeView && !EmitDwarf &&
452406c3fb27SDimitry Andric       DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
45250b57cec5SDimitry Andric     switch (TC.getDefaultDebugFormat()) {
452606c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_CodeView:
45270b57cec5SDimitry Andric       EmitCodeView = true;
45280b57cec5SDimitry Andric       break;
452906c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_DWARF:
4530480093f4SDimitry Andric       EmitDwarf = true;
45310b57cec5SDimitry Andric       break;
45320b57cec5SDimitry Andric     }
45330b57cec5SDimitry Andric   }
45340b57cec5SDimitry Andric 
4535e8d8bef9SDimitry Andric   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4536e8d8bef9SDimitry Andric   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4537e8d8bef9SDimitry Andric                                       // be lower than what the user wanted.
4538480093f4SDimitry Andric   if (EmitDwarf) {
4539bdd1243dSDimitry Andric     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4540e8d8bef9SDimitry Andric     // Clamp effective DWARF version to the max supported by the toolchain.
4541e8d8bef9SDimitry Andric     EffectiveDWARFVersion =
4542e8d8bef9SDimitry Andric         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4543bdd1243dSDimitry Andric   } else {
4544bdd1243dSDimitry Andric     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4545480093f4SDimitry Andric   }
4546480093f4SDimitry Andric 
45470b57cec5SDimitry Andric   // -gline-directives-only supported only for the DWARF debug info.
4548e8d8bef9SDimitry Andric   if (RequestedDWARFVersion == 0 &&
454906c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
455006c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
45510b57cec5SDimitry Andric 
4552fe6060f1SDimitry Andric   // strict DWARF is set to false by default. But for DBX, we need it to be set
4553fe6060f1SDimitry Andric   // as true by default.
4554fe6060f1SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4555fe6060f1SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4556fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4557fe6060f1SDimitry Andric                    DebuggerTuning == llvm::DebuggerKind::DBX))
4558fe6060f1SDimitry Andric     CmdArgs.push_back("-gstrict-dwarf");
4559fe6060f1SDimitry Andric 
45600b57cec5SDimitry Andric   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
45610b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_flags_Group);
45620b57cec5SDimitry Andric 
45630b57cec5SDimitry Andric   // Column info is included by default for everything except SCE and
45640b57cec5SDimitry Andric   // CodeView. Clang doesn't track end columns, just starting columns, which,
45650b57cec5SDimitry Andric   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4566fe6060f1SDimitry Andric   // Microsoft debuggers don't handle missing end columns well, and the AIX
4567fe6060f1SDimitry Andric   // debugger DBX also doesn't handle the columns well, so it's better not to
4568fe6060f1SDimitry Andric   // include any column info.
45690b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
45700b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
45715ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4572fe6060f1SDimitry Andric                     !EmitCodeView &&
4573fe6060f1SDimitry Andric                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4574fe6060f1SDimitry Andric                          DebuggerTuning != llvm::DebuggerKind::DBX)))
45755ffd83dbSDimitry Andric     CmdArgs.push_back("-gno-column-info");
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric   // FIXME: Move backend command line options to the module.
4578bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4579bdd1243dSDimitry Andric     // If -gline-tables-only or -gline-directives-only is the last option it
4580bdd1243dSDimitry Andric     // wins.
4581bdd1243dSDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4582bdd1243dSDimitry Andric                              TC)) {
458306c3fb27SDimitry Andric       if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
458406c3fb27SDimitry Andric           DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
458506c3fb27SDimitry Andric         DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
45860b57cec5SDimitry Andric         CmdArgs.push_back("-dwarf-ext-refs");
45870b57cec5SDimitry Andric         CmdArgs.push_back("-fmodule-format=obj");
45880b57cec5SDimitry Andric       }
45890b57cec5SDimitry Andric     }
4590bdd1243dSDimitry Andric   }
45910b57cec5SDimitry Andric 
4592fe6060f1SDimitry Andric   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4593fe6060f1SDimitry Andric     CmdArgs.push_back("-fsplit-dwarf-inlining");
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric   // After we've dealt with all combinations of things that could
45960b57cec5SDimitry Andric   // make DebugInfoKind be other than None or DebugLineTablesOnly,
45970b57cec5SDimitry Andric   // figure out if we need to "upgrade" it to standalone debug info.
45980b57cec5SDimitry Andric   // We parse these two '-f' options whether or not they will be used,
45990b57cec5SDimitry Andric   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
46000b57cec5SDimitry Andric   bool NeedFullDebug = Args.hasFlag(
46010b57cec5SDimitry Andric       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
46020b57cec5SDimitry Andric       DebuggerTuning == llvm::DebuggerKind::LLDB ||
46030b57cec5SDimitry Andric           TC.GetDefaultStandaloneDebug());
46040b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
46050b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4606e8d8bef9SDimitry Andric 
460706c3fb27SDimitry Andric   if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
460806c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4609e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4610e8d8bef9SDimitry Andric                      options::OPT_feliminate_unused_debug_types, false))
461106c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4612e8d8bef9SDimitry Andric     else if (NeedFullDebug)
461306c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4614e8d8bef9SDimitry Andric   }
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
46170b57cec5SDimitry Andric                    false)) {
46180b57cec5SDimitry Andric     // Source embedding is a vendor extension to DWARF v5. By now we have
46190b57cec5SDimitry Andric     // checked if a DWARF version was stated explicitly, and have otherwise
46200b57cec5SDimitry Andric     // fallen back to the target default, so if this is still not at least 5
46210b57cec5SDimitry Andric     // we emit an error.
46220b57cec5SDimitry Andric     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4623e8d8bef9SDimitry Andric     if (RequestedDWARFVersion < 5)
46240b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
46250b57cec5SDimitry Andric           << A->getAsString(Args) << "-gdwarf-5";
4626e8d8bef9SDimitry Andric     else if (EffectiveDWARFVersion < 5)
4627e8d8bef9SDimitry Andric       // The toolchain has reduced allowed dwarf version, so we can't enable
4628e8d8bef9SDimitry Andric       // -gembed-source.
4629e8d8bef9SDimitry Andric       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4630e8d8bef9SDimitry Andric           << A->getAsString(Args) << TC.getTripleString() << 5
4631e8d8bef9SDimitry Andric           << EffectiveDWARFVersion;
46320b57cec5SDimitry Andric     else if (checkDebugInfoOption(A, Args, D, TC))
46330b57cec5SDimitry Andric       CmdArgs.push_back("-gembed-source");
46340b57cec5SDimitry Andric   }
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   if (EmitCodeView) {
46370b57cec5SDimitry Andric     CmdArgs.push_back("-gcodeview");
46380b57cec5SDimitry Andric 
4639bdd1243dSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4640bdd1243dSDimitry Andric                       options::OPT_gno_codeview_ghash);
4641bdd1243dSDimitry Andric 
4642bdd1243dSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4643bdd1243dSDimitry Andric                        options::OPT_gno_codeview_command_line);
46440b57cec5SDimitry Andric   }
46450b57cec5SDimitry Andric 
4646bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4647bdd1243dSDimitry Andric                      options::OPT_gno_inline_line_tables);
4648480093f4SDimitry Andric 
4649480093f4SDimitry Andric   // When emitting remarks, we need at least debug lines in the output.
4650480093f4SDimitry Andric   if (willEmitRemarks(Args) &&
465106c3fb27SDimitry Andric       DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
465206c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4653480093f4SDimitry Andric 
4654e8d8bef9SDimitry Andric   // Adjust the debug info kind for the given toolchain.
4655e8d8bef9SDimitry Andric   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4656e8d8bef9SDimitry Andric 
4657bdd1243dSDimitry Andric   // On AIX, the debugger tuning option can be omitted if it is not explicitly
4658bdd1243dSDimitry Andric   // set.
4659e8d8bef9SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4660bdd1243dSDimitry Andric                           T.isOSAIX() && !HasDebuggerTuning
4661bdd1243dSDimitry Andric                               ? llvm::DebuggerKind::Default
4662bdd1243dSDimitry Andric                               : DebuggerTuning);
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   // -fdebug-macro turns on macro debug info generation.
46650b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
46660b57cec5SDimitry Andric                    false))
46670b57cec5SDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
46680b57cec5SDimitry Andric                              D, TC))
46690b57cec5SDimitry Andric       CmdArgs.push_back("-debug-info-macro");
46700b57cec5SDimitry Andric 
46710b57cec5SDimitry Andric   // -ggnu-pubnames turns on gnu style pubnames in the backend.
46720b57cec5SDimitry Andric   const auto *PubnamesArg =
46730b57cec5SDimitry Andric       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
46740b57cec5SDimitry Andric                       options::OPT_gpubnames, options::OPT_gno_pubnames);
46750b57cec5SDimitry Andric   if (DwarfFission != DwarfFissionKind::None ||
46760fca6ea1SDimitry Andric       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
46770fca6ea1SDimitry Andric     const bool OptionSet =
46780fca6ea1SDimitry Andric         (PubnamesArg &&
46790fca6ea1SDimitry Andric          (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
46800fca6ea1SDimitry Andric           PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
46810fca6ea1SDimitry Andric     if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
46820fca6ea1SDimitry Andric         (!PubnamesArg ||
46830b57cec5SDimitry Andric          (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
46840fca6ea1SDimitry Andric           !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
46850b57cec5SDimitry Andric       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
46860b57cec5SDimitry Andric                                            options::OPT_gpubnames)
46870b57cec5SDimitry Andric                             ? "-gpubnames"
46880b57cec5SDimitry Andric                             : "-ggnu-pubnames");
46890fca6ea1SDimitry Andric   }
4690349cc55cSDimitry Andric   const auto *SimpleTemplateNamesArg =
469181ad6265SDimitry Andric       Args.getLastArg(options::OPT_gsimple_template_names,
469281ad6265SDimitry Andric                       options::OPT_gno_simple_template_names);
4693349cc55cSDimitry Andric   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4694349cc55cSDimitry Andric   if (SimpleTemplateNamesArg &&
4695349cc55cSDimitry Andric       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4696349cc55cSDimitry Andric     const auto &Opt = SimpleTemplateNamesArg->getOption();
4697349cc55cSDimitry Andric     if (Opt.matches(options::OPT_gsimple_template_names)) {
4698349cc55cSDimitry Andric       ForwardTemplateParams = true;
4699349cc55cSDimitry Andric       CmdArgs.push_back("-gsimple-template-names=simple");
4700349cc55cSDimitry Andric     }
4701349cc55cSDimitry Andric   }
47020b57cec5SDimitry Andric 
47030fca6ea1SDimitry Andric   // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
47040fca6ea1SDimitry Andric   bool UseDebugTemplateAlias =
47050fca6ea1SDimitry Andric       DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
47060fca6ea1SDimitry Andric   if (const auto *DebugTemplateAlias = Args.getLastArg(
47070fca6ea1SDimitry Andric           options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
47080fca6ea1SDimitry Andric     // DW_TAG_template_alias is only supported from DWARFv5 but if a user
47090fca6ea1SDimitry Andric     // asks for it we should let them have it (if the target supports it).
47100fca6ea1SDimitry Andric     if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
47110fca6ea1SDimitry Andric       const auto &Opt = DebugTemplateAlias->getOption();
47120fca6ea1SDimitry Andric       UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
47130fca6ea1SDimitry Andric     }
47140fca6ea1SDimitry Andric   }
47150fca6ea1SDimitry Andric   if (UseDebugTemplateAlias)
47160fca6ea1SDimitry Andric     CmdArgs.push_back("-gtemplate-alias");
47170fca6ea1SDimitry Andric 
4718bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4719bdd1243dSDimitry Andric     StringRef v = A->getValue();
4720bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
47210b57cec5SDimitry Andric   }
47220b57cec5SDimitry Andric 
4723bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4724bdd1243dSDimitry Andric                     options::OPT_fno_debug_ranges_base_address);
4725bdd1243dSDimitry Andric 
47260b57cec5SDimitry Andric   // -gdwarf-aranges turns on the emission of the aranges section in the
47270b57cec5SDimitry Andric   // backend.
47280b57cec5SDimitry Andric   // Always enabled for SCE tuning.
47290b57cec5SDimitry Andric   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
47300b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
47310b57cec5SDimitry Andric     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
47320b57cec5SDimitry Andric   if (NeedAranges) {
47330b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
47340b57cec5SDimitry Andric     CmdArgs.push_back("-generate-arange-section");
47350b57cec5SDimitry Andric   }
47360b57cec5SDimitry Andric 
4737bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4738bdd1243dSDimitry Andric                     options::OPT_fno_force_dwarf_frame);
4739480093f4SDimitry Andric 
47400fca6ea1SDimitry Andric   bool EnableTypeUnits = false;
47410b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_types_section,
47420b57cec5SDimitry Andric                    options::OPT_fno_debug_types_section, false)) {
4743e8d8bef9SDimitry Andric     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
47440b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
47450b57cec5SDimitry Andric           << Args.getLastArg(options::OPT_fdebug_types_section)
47460b57cec5SDimitry Andric                  ->getAsString(Args)
47470b57cec5SDimitry Andric           << T.getTriple();
47480b57cec5SDimitry Andric     } else if (checkDebugInfoOption(
47490b57cec5SDimitry Andric                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
47500b57cec5SDimitry Andric                    TC)) {
47510fca6ea1SDimitry Andric       EnableTypeUnits = true;
47520b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
47530b57cec5SDimitry Andric       CmdArgs.push_back("-generate-type-units");
47540b57cec5SDimitry Andric     }
47550b57cec5SDimitry Andric   }
47560b57cec5SDimitry Andric 
47570fca6ea1SDimitry Andric   if (const Arg *A =
47580fca6ea1SDimitry Andric           Args.getLastArg(options::OPT_gomit_unreferenced_methods,
47590fca6ea1SDimitry Andric                           options::OPT_gno_omit_unreferenced_methods))
47600fca6ea1SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
47610fca6ea1SDimitry Andric   if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
47620fca6ea1SDimitry Andric                    options::OPT_gno_omit_unreferenced_methods, false) &&
47630fca6ea1SDimitry Andric       (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
47640fca6ea1SDimitry Andric        DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
47650fca6ea1SDimitry Andric       !EnableTypeUnits) {
47660fca6ea1SDimitry Andric     CmdArgs.push_back("-gomit-unreferenced-methods");
47670fca6ea1SDimitry Andric   }
47680fca6ea1SDimitry Andric 
4769fe6060f1SDimitry Andric   // To avoid join/split of directory+filename, the integrated assembler prefers
4770fe6060f1SDimitry Andric   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4771fe6060f1SDimitry Andric   // form before DWARF v5.
4772fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4773fe6060f1SDimitry Andric                     options::OPT_fno_dwarf_directory_asm,
4774fe6060f1SDimitry Andric                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4775fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-dwarf-directory-asm");
4776fe6060f1SDimitry Andric 
47770b57cec5SDimitry Andric   // Decide how to render forward declarations of template instantiations.
47780b57cec5SDimitry Andric   // SCE wants full descriptions, others just get them in the name.
4779349cc55cSDimitry Andric   if (ForwardTemplateParams)
47800b57cec5SDimitry Andric     CmdArgs.push_back("-debug-forward-template-params");
47810b57cec5SDimitry Andric 
47820b57cec5SDimitry Andric   // Do we need to explicitly import anonymous namespaces into the parent
47830b57cec5SDimitry Andric   // scope?
47840b57cec5SDimitry Andric   if (DebuggerTuning == llvm::DebuggerKind::SCE)
47850b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-explicit-import");
47860b57cec5SDimitry Andric 
4787fe6060f1SDimitry Andric   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
47880b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
47895f757f3fSDimitry Andric 
47905f757f3fSDimitry Andric   // This controls whether or not we perform JustMyCode instrumentation.
47915f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
47925f757f3fSDimitry Andric     if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
47935f757f3fSDimitry Andric       if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
47945f757f3fSDimitry Andric         CmdArgs.push_back("-fjmc");
47955f757f3fSDimitry Andric       else if (D.IsCLMode())
47965f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
47975f757f3fSDimitry Andric                                                              << "'/Zi', '/Z7'";
47985f757f3fSDimitry Andric       else
47995f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
48005f757f3fSDimitry Andric                                                              << "-g";
48015f757f3fSDimitry Andric     } else {
48025f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
48035f757f3fSDimitry Andric     }
48045f757f3fSDimitry Andric   }
48055f757f3fSDimitry Andric 
48065f757f3fSDimitry Andric   // Add in -fdebug-compilation-dir if necessary.
48075f757f3fSDimitry Andric   const char *DebugCompilationDir =
48085f757f3fSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
48095f757f3fSDimitry Andric 
48105f757f3fSDimitry Andric   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
48115f757f3fSDimitry Andric 
48125f757f3fSDimitry Andric   // Add the output path to the object file for CodeView debug infos.
48135f757f3fSDimitry Andric   if (EmitCodeView && Output.isFilename())
48145f757f3fSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
48155f757f3fSDimitry Andric                        Output.getFilename());
48160b57cec5SDimitry Andric }
48170b57cec5SDimitry Andric 
ProcessVSRuntimeLibrary(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)48180fca6ea1SDimitry Andric static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4819bdd1243dSDimitry Andric                                     ArgStringList &CmdArgs) {
4820bdd1243dSDimitry Andric   unsigned RTOptionID = options::OPT__SLASH_MT;
4821bdd1243dSDimitry Andric 
4822bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_LDd))
4823bdd1243dSDimitry Andric     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4824bdd1243dSDimitry Andric     // but defining _DEBUG is sticky.
4825bdd1243dSDimitry Andric     RTOptionID = options::OPT__SLASH_MTd;
4826bdd1243dSDimitry Andric 
4827bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4828bdd1243dSDimitry Andric     RTOptionID = A->getOption().getID();
4829bdd1243dSDimitry Andric 
4830bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4831bdd1243dSDimitry Andric     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4832bdd1243dSDimitry Andric                      .Case("static", options::OPT__SLASH_MT)
4833bdd1243dSDimitry Andric                      .Case("static_dbg", options::OPT__SLASH_MTd)
4834bdd1243dSDimitry Andric                      .Case("dll", options::OPT__SLASH_MD)
4835bdd1243dSDimitry Andric                      .Case("dll_dbg", options::OPT__SLASH_MDd)
4836bdd1243dSDimitry Andric                      .Default(options::OPT__SLASH_MT);
4837bdd1243dSDimitry Andric   }
4838bdd1243dSDimitry Andric 
4839bdd1243dSDimitry Andric   StringRef FlagForCRT;
4840bdd1243dSDimitry Andric   switch (RTOptionID) {
4841bdd1243dSDimitry Andric   case options::OPT__SLASH_MD:
4842bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4843bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4844bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4845bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4846bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrt";
4847bdd1243dSDimitry Andric     break;
4848bdd1243dSDimitry Andric   case options::OPT__SLASH_MDd:
4849bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4850bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4851bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4852bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrtd";
4853bdd1243dSDimitry Andric     break;
4854bdd1243dSDimitry Andric   case options::OPT__SLASH_MT:
4855bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4856bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4857bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4858bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4859bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmt";
4860bdd1243dSDimitry Andric     break;
4861bdd1243dSDimitry Andric   case options::OPT__SLASH_MTd:
4862bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4863bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4864bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4865bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmtd";
4866bdd1243dSDimitry Andric     break;
4867bdd1243dSDimitry Andric   default:
4868bdd1243dSDimitry Andric     llvm_unreachable("Unexpected option ID.");
4869bdd1243dSDimitry Andric   }
4870bdd1243dSDimitry Andric 
4871bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4872bdd1243dSDimitry Andric     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4873bdd1243dSDimitry Andric   } else {
4874bdd1243dSDimitry Andric     CmdArgs.push_back(FlagForCRT.data());
4875bdd1243dSDimitry Andric 
4876bdd1243dSDimitry Andric     // This provides POSIX compatibility (maps 'open' to '_open'), which most
4877bdd1243dSDimitry Andric     // users want.  The /Za flag to cl.exe turns this off, but it's not
4878bdd1243dSDimitry Andric     // implemented in clang.
4879bdd1243dSDimitry Andric     CmdArgs.push_back("--dependent-lib=oldnames");
4880bdd1243dSDimitry Andric   }
48810fca6ea1SDimitry Andric 
48820fca6ea1SDimitry Andric   // All Arm64EC object files implicitly add softintrin.lib. This is necessary
48830fca6ea1SDimitry Andric   // even if the file doesn't actually refer to any of the routines because
48840fca6ea1SDimitry Andric   // the CRT itself has incomplete dependency markings.
48850fca6ea1SDimitry Andric   if (TC.getTriple().isWindowsArm64EC())
48860fca6ea1SDimitry Andric     CmdArgs.push_back("--dependent-lib=softintrin");
4887bdd1243dSDimitry Andric }
4888bdd1243dSDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const48890b57cec5SDimitry Andric void Clang::ConstructJob(Compilation &C, const JobAction &JA,
48900b57cec5SDimitry Andric                          const InputInfo &Output, const InputInfoList &Inputs,
48910b57cec5SDimitry Andric                          const ArgList &Args, const char *LinkingOutput) const {
48920b57cec5SDimitry Andric   const auto &TC = getToolChain();
48930b57cec5SDimitry Andric   const llvm::Triple &RawTriple = TC.getTriple();
48940b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
48950b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
48960b57cec5SDimitry Andric 
48970b57cec5SDimitry Andric   bool KernelOrKext =
48980b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
48990b57cec5SDimitry Andric   const Driver &D = TC.getDriver();
49000b57cec5SDimitry Andric   ArgStringList CmdArgs;
49010b57cec5SDimitry Andric 
49020b57cec5SDimitry Andric   assert(Inputs.size() >= 1 && "Must have at least one input.");
49030b57cec5SDimitry Andric   // CUDA/HIP compilation may have multiple inputs (source file + results of
49040b57cec5SDimitry Andric   // device-side compilations). OpenMP device jobs also take the host IR as a
49050b57cec5SDimitry Andric   // second input. Module precompilation accepts a list of header files to
490681ad6265SDimitry Andric   // include as part of the module. API extraction accepts a list of header
490781ad6265SDimitry Andric   // files whose API information is emitted in the output. All other jobs are
490881ad6265SDimitry Andric   // expected to have exactly one input.
49090b57cec5SDimitry Andric   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4910fe6060f1SDimitry Andric   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
49110b57cec5SDimitry Andric   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4912fe6060f1SDimitry Andric   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
49130b57cec5SDimitry Andric   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
491481ad6265SDimitry Andric   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4915fe6060f1SDimitry Andric   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4916fe6060f1SDimitry Andric                                  JA.isDeviceOffloading(Action::OFK_Host));
491781ad6265SDimitry Andric   bool IsHostOffloadingAction =
4918bdd1243dSDimitry Andric       JA.isHostOffloading(Action::OFK_OpenMP) ||
491981ad6265SDimitry Andric       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
492081ad6265SDimitry Andric        Args.hasFlag(options::OPT_offload_new_driver,
492181ad6265SDimitry Andric                     options::OPT_no_offload_new_driver, false));
492281ad6265SDimitry Andric 
4923753f127fSDimitry Andric   bool IsRDCMode =
4924753f127fSDimitry Andric       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4925fe6060f1SDimitry Andric   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4926fe6060f1SDimitry Andric   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
49270b57cec5SDimitry Andric 
492881ad6265SDimitry Andric   // Extract API doesn't have a main input file, so invent a fake one as a
492981ad6265SDimitry Andric   // placeholder.
493081ad6265SDimitry Andric   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
493181ad6265SDimitry Andric                                        "extract-api");
493281ad6265SDimitry Andric 
4933bdd1243dSDimitry Andric   const InputInfo &Input =
4934bdd1243dSDimitry Andric       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
49350b57cec5SDimitry Andric 
493681ad6265SDimitry Andric   InputInfoList ExtractAPIInputs;
493781ad6265SDimitry Andric   InputInfoList HostOffloadingInputs;
49380b57cec5SDimitry Andric   const InputInfo *CudaDeviceInput = nullptr;
49390b57cec5SDimitry Andric   const InputInfo *OpenMPDeviceInput = nullptr;
49400b57cec5SDimitry Andric   for (const InputInfo &I : Inputs) {
4941bdd1243dSDimitry Andric     if (&I == &Input || I.getType() == types::TY_Nothing) {
4942bdd1243dSDimitry Andric       // This is the primary input or contains nothing.
494381ad6265SDimitry Andric     } else if (IsExtractAPI) {
494481ad6265SDimitry Andric       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
494581ad6265SDimitry Andric       if (I.getType() != ExpectedInputType) {
494681ad6265SDimitry Andric         D.Diag(diag::err_drv_extract_api_wrong_kind)
494781ad6265SDimitry Andric             << I.getFilename() << types::getTypeName(I.getType())
494881ad6265SDimitry Andric             << types::getTypeName(ExpectedInputType);
494981ad6265SDimitry Andric       }
495081ad6265SDimitry Andric       ExtractAPIInputs.push_back(I);
495181ad6265SDimitry Andric     } else if (IsHostOffloadingAction) {
495281ad6265SDimitry Andric       HostOffloadingInputs.push_back(I);
49530b57cec5SDimitry Andric     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
49540b57cec5SDimitry Andric       CudaDeviceInput = &I;
49550b57cec5SDimitry Andric     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
49560b57cec5SDimitry Andric       OpenMPDeviceInput = &I;
49570b57cec5SDimitry Andric     } else {
49580b57cec5SDimitry Andric       llvm_unreachable("unexpectedly given multiple inputs");
49590b57cec5SDimitry Andric     }
49600b57cec5SDimitry Andric   }
49610b57cec5SDimitry Andric 
49625ffd83dbSDimitry Andric   const llvm::Triple *AuxTriple =
49635ffd83dbSDimitry Andric       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
49640b57cec5SDimitry Andric   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
49650b57cec5SDimitry Andric   bool IsIAMCU = RawTriple.isOSIAMCU();
49660b57cec5SDimitry Andric 
49670b57cec5SDimitry Andric   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
49680b57cec5SDimitry Andric   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
49690b57cec5SDimitry Andric   // Windows), we need to pass Windows-specific flags to cc1.
49700b57cec5SDimitry Andric   if (IsCuda || IsHIP)
49710b57cec5SDimitry Andric     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
49720b57cec5SDimitry Andric 
49730b57cec5SDimitry Andric   // C++ is not supported for IAMCU.
49740b57cec5SDimitry Andric   if (IsIAMCU && types::isCXX(Input.getType()))
49750b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
49760b57cec5SDimitry Andric 
49770b57cec5SDimitry Andric   // Invoke ourselves in -cc1 mode.
49780b57cec5SDimitry Andric   //
49790b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
49800b57cec5SDimitry Andric   CmdArgs.push_back("-cc1");
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric   // Add the "effective" target triple.
49830b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
49840b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
49850b57cec5SDimitry Andric 
49860b57cec5SDimitry Andric   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
49870b57cec5SDimitry Andric     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
49880b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_MJ);
4989a7dea167SDimitry Andric   } else if (const Arg *GenCDBFragment =
4990a7dea167SDimitry Andric                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4991a7dea167SDimitry Andric     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4992a7dea167SDimitry Andric                                          TripleStr, Output, Input, Args);
4993a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
49940b57cec5SDimitry Andric   }
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric   if (IsCuda || IsHIP) {
49970b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for a CUDA/HIP device
49980b57cec5SDimitry Andric     // and vice-versa.
49990b57cec5SDimitry Andric     std::string NormalizedTriple;
50000b57cec5SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
50010b57cec5SDimitry Andric         JA.isDeviceOffloading(Action::OFK_HIP))
50020b57cec5SDimitry Andric       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
50030b57cec5SDimitry Andric                              ->getTriple()
50040b57cec5SDimitry Andric                              .normalize();
50050b57cec5SDimitry Andric     else {
50060b57cec5SDimitry Andric       // Host-side compilation.
50070b57cec5SDimitry Andric       NormalizedTriple =
50080b57cec5SDimitry Andric           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
50090b57cec5SDimitry Andric                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
50100b57cec5SDimitry Andric               ->getTriple()
50110b57cec5SDimitry Andric               .normalize();
50120b57cec5SDimitry Andric       if (IsCuda) {
50130b57cec5SDimitry Andric         // We need to figure out which CUDA version we're compiling for, as that
50140b57cec5SDimitry Andric         // determines how we load and launch GPU kernels.
50150b57cec5SDimitry Andric         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
50160b57cec5SDimitry Andric             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
50170b57cec5SDimitry Andric         assert(CTC && "Expected valid CUDA Toolchain.");
50180b57cec5SDimitry Andric         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
50190b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
50200b57cec5SDimitry Andric               Twine("-target-sdk-version=") +
50210b57cec5SDimitry Andric               CudaVersionToString(CTC->CudaInstallation.version())));
502206c3fb27SDimitry Andric         // Unsized function arguments used for variadics were introduced in
502306c3fb27SDimitry Andric         // CUDA-9.0. We still do not support generating code that actually uses
502406c3fb27SDimitry Andric         // variadic arguments yet, but we do need to allow parsing them as
502506c3fb27SDimitry Andric         // recent CUDA headers rely on that.
502606c3fb27SDimitry Andric         // https://github.com/llvm/llvm-project/issues/58410
502706c3fb27SDimitry Andric         if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
502806c3fb27SDimitry Andric           CmdArgs.push_back("-fcuda-allow-variadic-functions");
50290b57cec5SDimitry Andric       }
50300b57cec5SDimitry Andric     }
50310b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
50320b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
503306c3fb27SDimitry Andric 
503406c3fb27SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_HIP) &&
50350fca6ea1SDimitry Andric         (getToolChain().getTriple().isAMDGPU() ||
50360fca6ea1SDimitry Andric          (getToolChain().getTriple().isSPIRV() &&
50370fca6ea1SDimitry Andric           getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
503806c3fb27SDimitry Andric       // Device side compilation printf
503906c3fb27SDimitry Andric       if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
504006c3fb27SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
504106c3fb27SDimitry Andric             "-mprintf-kind=" +
504206c3fb27SDimitry Andric             Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
504306c3fb27SDimitry Andric         // Force compiler error on invalid conversion specifiers
504406c3fb27SDimitry Andric         CmdArgs.push_back(
504506c3fb27SDimitry Andric             Args.MakeArgString("-Werror=format-invalid-specifier"));
50460b57cec5SDimitry Andric       }
504706c3fb27SDimitry Andric     }
504806c3fb27SDimitry Andric   }
504906c3fb27SDimitry Andric 
505006c3fb27SDimitry Andric   // Unconditionally claim the printf option now to avoid unused diagnostic.
505106c3fb27SDimitry Andric   if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
505206c3fb27SDimitry Andric     PF->claim();
50530b57cec5SDimitry Andric 
50545ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
50555ffd83dbSDimitry Andric     CmdArgs.push_back("-fsycl-is-device");
50565ffd83dbSDimitry Andric 
50575ffd83dbSDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
50585ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
50595ffd83dbSDimitry Andric     } else {
5060fe6060f1SDimitry Andric       // Ensure the default version in SYCL mode is 2020.
5061fe6060f1SDimitry Andric       CmdArgs.push_back("-sycl-std=2020");
50625ffd83dbSDimitry Andric     }
50635ffd83dbSDimitry Andric   }
50645ffd83dbSDimitry Andric 
50650b57cec5SDimitry Andric   if (IsOpenMPDevice) {
50660b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for an OpenMP device.
50670b57cec5SDimitry Andric     std::string NormalizedTriple =
50680b57cec5SDimitry Andric         C.getSingleOffloadToolChain<Action::OFK_Host>()
50690b57cec5SDimitry Andric             ->getTriple()
50700b57cec5SDimitry Andric             .normalize();
50710b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
50720b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
50730b57cec5SDimitry Andric   }
50740b57cec5SDimitry Andric 
50750b57cec5SDimitry Andric   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
50760b57cec5SDimitry Andric                                Triple.getArch() == llvm::Triple::thumb)) {
50770b57cec5SDimitry Andric     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
50785ffd83dbSDimitry Andric     unsigned Version = 0;
50795ffd83dbSDimitry Andric     bool Failure =
50805ffd83dbSDimitry Andric         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
50815ffd83dbSDimitry Andric     if (Failure || Version < 7)
50820b57cec5SDimitry Andric       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
50830b57cec5SDimitry Andric                                                 << TripleStr;
50840b57cec5SDimitry Andric   }
50850b57cec5SDimitry Andric 
50860b57cec5SDimitry Andric   // Push all default warning arguments that are specific to
50870b57cec5SDimitry Andric   // the given target.  These come before user provided warning options
50880b57cec5SDimitry Andric   // are provided.
50890b57cec5SDimitry Andric   TC.addClangWarningOptions(CmdArgs);
50900b57cec5SDimitry Andric 
5091fe6060f1SDimitry Andric   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5092bdd1243dSDimitry Andric   if (Triple.isSPIR() || Triple.isSPIRV())
5093fe6060f1SDimitry Andric     CmdArgs.push_back("-Wspir-compat");
5094fe6060f1SDimitry Andric 
50950b57cec5SDimitry Andric   // Select the appropriate action.
50960b57cec5SDimitry Andric   RewriteKind rewriteKind = RK_None;
50970b57cec5SDimitry Andric 
509806c3fb27SDimitry Andric   bool UnifiedLTO = false;
509906c3fb27SDimitry Andric   if (IsUsingLTO) {
510006c3fb27SDimitry Andric     UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
51017a6dacacSDimitry Andric                               options::OPT_fno_unified_lto, Triple.isPS());
510206c3fb27SDimitry Andric     if (UnifiedLTO)
510306c3fb27SDimitry Andric       CmdArgs.push_back("-funified-lto");
510406c3fb27SDimitry Andric   }
510506c3fb27SDimitry Andric 
5106a7dea167SDimitry Andric   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5107a7dea167SDimitry Andric   // it claims when not running an assembler. Otherwise, clang would emit
5108a7dea167SDimitry Andric   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5109a7dea167SDimitry Andric   // flags while debugging something. That'd be somewhat inconvenient, and it's
5110a7dea167SDimitry Andric   // also inconsistent with most other flags -- we don't warn on
5111a7dea167SDimitry Andric   // -ffunction-sections not being used in -E mode either for example, even
5112a7dea167SDimitry Andric   // though it's not really used either.
5113a7dea167SDimitry Andric   if (!isa<AssembleJobAction>(JA)) {
5114a7dea167SDimitry Andric     // The args claimed here should match the args used in
5115a7dea167SDimitry Andric     // CollectArgsForIntegratedAssembler().
5116a7dea167SDimitry Andric     if (TC.useIntegratedAs()) {
5117a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mrelax_all);
5118a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_relax_all);
5119a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5120a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5121a7dea167SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
5122a7dea167SDimitry Andric       case llvm::Triple::arm:
5123a7dea167SDimitry Andric       case llvm::Triple::armeb:
5124a7dea167SDimitry Andric       case llvm::Triple::thumb:
5125a7dea167SDimitry Andric       case llvm::Triple::thumbeb:
5126a7dea167SDimitry Andric         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5127a7dea167SDimitry Andric         break;
5128a7dea167SDimitry Andric       default:
5129a7dea167SDimitry Andric         break;
5130a7dea167SDimitry Andric       }
5131a7dea167SDimitry Andric     }
5132a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5133a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Xassembler);
513481ad6265SDimitry Andric     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5135a7dea167SDimitry Andric   }
5136a7dea167SDimitry Andric 
51370b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA)) {
51380b57cec5SDimitry Andric     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
51390b57cec5SDimitry Andric     CmdArgs.push_back("-analyze");
51400b57cec5SDimitry Andric   } else if (isa<MigrateJobAction>(JA)) {
51410b57cec5SDimitry Andric     CmdArgs.push_back("-migrate");
51420b57cec5SDimitry Andric   } else if (isa<PreprocessJobAction>(JA)) {
51430b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies)
51440b57cec5SDimitry Andric       CmdArgs.push_back("-Eonly");
51450b57cec5SDimitry Andric     else {
51460b57cec5SDimitry Andric       CmdArgs.push_back("-E");
51470b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_rewrite_objc) &&
51480b57cec5SDimitry Andric           !Args.hasArg(options::OPT_g_Group))
51490b57cec5SDimitry Andric         CmdArgs.push_back("-P");
515081ad6265SDimitry Andric       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
515181ad6265SDimitry Andric         CmdArgs.push_back("-fdirectives-only");
51520b57cec5SDimitry Andric     }
51530b57cec5SDimitry Andric   } else if (isa<AssembleJobAction>(JA)) {
51540b57cec5SDimitry Andric     CmdArgs.push_back("-emit-obj");
51550b57cec5SDimitry Andric 
51560b57cec5SDimitry Andric     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
51570b57cec5SDimitry Andric 
51580b57cec5SDimitry Andric     // Also ignore explicit -force_cpusubtype_ALL option.
51590b57cec5SDimitry Andric     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
51600b57cec5SDimitry Andric   } else if (isa<PrecompileJobAction>(JA)) {
51610b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing)
51620b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
51630b57cec5SDimitry Andric     else if (JA.getType() == types::TY_ModuleFile)
5164bdd1243dSDimitry Andric       CmdArgs.push_back("-emit-module-interface");
516581ad6265SDimitry Andric     else if (JA.getType() == types::TY_HeaderUnit)
516681ad6265SDimitry Andric       CmdArgs.push_back("-emit-header-unit");
51670b57cec5SDimitry Andric     else
51680b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
51690b57cec5SDimitry Andric   } else if (isa<VerifyPCHJobAction>(JA)) {
51700b57cec5SDimitry Andric     CmdArgs.push_back("-verify-pch");
517181ad6265SDimitry Andric   } else if (isa<ExtractAPIJobAction>(JA)) {
517281ad6265SDimitry Andric     assert(JA.getType() == types::TY_API_INFO &&
517381ad6265SDimitry Andric            "Extract API actions must generate a API information.");
517481ad6265SDimitry Andric     CmdArgs.push_back("-extract-api");
51750fca6ea1SDimitry Andric 
51760fca6ea1SDimitry Andric     if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
51770fca6ea1SDimitry Andric       PrettySGFArg->render(Args, CmdArgs);
51780fca6ea1SDimitry Andric 
51790fca6ea1SDimitry Andric     Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
51800fca6ea1SDimitry Andric 
518181ad6265SDimitry Andric     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
518281ad6265SDimitry Andric       ProductNameArg->render(Args, CmdArgs);
5183bdd1243dSDimitry Andric     if (Arg *ExtractAPIIgnoresFileArg =
5184bdd1243dSDimitry Andric             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5185bdd1243dSDimitry Andric       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
51860fca6ea1SDimitry Andric     if (Arg *EmitExtensionSymbolGraphs =
51870fca6ea1SDimitry Andric             Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
51880fca6ea1SDimitry Andric       if (!SymbolGraphDirArg)
51890fca6ea1SDimitry Andric         D.Diag(diag::err_drv_missing_symbol_graph_dir);
51900fca6ea1SDimitry Andric 
51910fca6ea1SDimitry Andric       EmitExtensionSymbolGraphs->render(Args, CmdArgs);
51920fca6ea1SDimitry Andric     }
51930fca6ea1SDimitry Andric     if (SymbolGraphDirArg)
51940fca6ea1SDimitry Andric       SymbolGraphDirArg->render(Args, CmdArgs);
51950b57cec5SDimitry Andric   } else {
51960b57cec5SDimitry Andric     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
51970b57cec5SDimitry Andric            "Invalid action for clang tool.");
51980b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing) {
51990b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
52000b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_IR ||
52010b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_IR) {
52020b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm");
52030b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_BC ||
52040b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_BC) {
5205fe6060f1SDimitry Andric       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5206fe6060f1SDimitry Andric       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5207fe6060f1SDimitry Andric           Args.hasArg(options::OPT_emit_llvm)) {
5208fe6060f1SDimitry Andric         CmdArgs.push_back("-emit-llvm");
5209fe6060f1SDimitry Andric       } else {
52100b57cec5SDimitry Andric         CmdArgs.push_back("-emit-llvm-bc");
5211fe6060f1SDimitry Andric       }
5212a7dea167SDimitry Andric     } else if (JA.getType() == types::TY_IFS ||
5213a7dea167SDimitry Andric                JA.getType() == types::TY_IFS_CPP) {
5214a7dea167SDimitry Andric       StringRef ArgStr =
5215a7dea167SDimitry Andric           Args.hasArg(options::OPT_interface_stub_version_EQ)
5216a7dea167SDimitry Andric               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5217fe6060f1SDimitry Andric               : "ifs-v1";
52180b57cec5SDimitry Andric       CmdArgs.push_back("-emit-interface-stubs");
52190b57cec5SDimitry Andric       CmdArgs.push_back(
5220a7dea167SDimitry Andric           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
52210b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_PP_Asm) {
52220b57cec5SDimitry Andric       CmdArgs.push_back("-S");
52230b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_AST) {
52240b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
52250b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_ModuleFile) {
52260b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-info");
52270b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenObjC) {
52280b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
52290b57cec5SDimitry Andric       rewriteKind = RK_NonFragile;
52300b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
52310b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
52320b57cec5SDimitry Andric       rewriteKind = RK_Fragile;
52330b57cec5SDimitry Andric     } else {
52340b57cec5SDimitry Andric       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
52350b57cec5SDimitry Andric     }
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric     // Preserve use-list order by default when emitting bitcode, so that
52380b57cec5SDimitry Andric     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
52390b57cec5SDimitry Andric     // same result as running passes here.  For LTO, we don't need to preserve
52400b57cec5SDimitry Andric     // the use-list order, since serialization to bitcode is part of the flow.
52410b57cec5SDimitry Andric     if (JA.getType() == types::TY_LLVM_BC)
52420b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm-uselists");
52430b57cec5SDimitry Andric 
524481ad6265SDimitry Andric     if (IsUsingLTO) {
5245bdd1243dSDimitry Andric       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
524681ad6265SDimitry Andric           !Args.hasFlag(options::OPT_offload_new_driver,
524781ad6265SDimitry Andric                         options::OPT_no_offload_new_driver, false) &&
524881ad6265SDimitry Andric           !Triple.isAMDGPU()) {
5249fe6060f1SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5250fe6060f1SDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
5251fe6060f1SDimitry Andric                                options::OPT_foffload_lto_EQ)
5252fe6060f1SDimitry Andric                    ->getAsString(Args)
5253fe6060f1SDimitry Andric             << Triple.getTriple();
5254bdd1243dSDimitry Andric       } else if (Triple.isNVPTX() && !IsRDCMode &&
5255bdd1243dSDimitry Andric                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
5256bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5257bdd1243dSDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
5258bdd1243dSDimitry Andric                                options::OPT_foffload_lto_EQ)
5259bdd1243dSDimitry Andric                    ->getAsString(Args)
5260bdd1243dSDimitry Andric             << "-fno-gpu-rdc";
5261349cc55cSDimitry Andric       } else {
5262349cc55cSDimitry Andric         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5263349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
5264349cc55cSDimitry Andric             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
526506c3fb27SDimitry Andric         // PS4 uses the legacy LTO API, which does not support some of the
526606c3fb27SDimitry Andric         // features enabled by -flto-unit.
526706c3fb27SDimitry Andric         if (!RawTriple.isPS4() ||
526806c3fb27SDimitry Andric             (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5269349cc55cSDimitry Andric           CmdArgs.push_back("-flto-unit");
5270fe6060f1SDimitry Andric       }
52710b57cec5SDimitry Andric     }
52720b57cec5SDimitry Andric   }
52730b57cec5SDimitry Andric 
527406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
527506c3fb27SDimitry Andric 
52760b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
52770b57cec5SDimitry Andric     if (!types::isLLVMIR(Input.getType()))
52780b57cec5SDimitry Andric       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
52790b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
52800b57cec5SDimitry Andric   }
52810b57cec5SDimitry Andric 
52825f757f3fSDimitry Andric   if (Triple.isPPC())
52835f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
52845f757f3fSDimitry Andric                       options::OPT_mno_regnames);
52855f757f3fSDimitry Andric 
5286480093f4SDimitry Andric   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5287480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5288480093f4SDimitry Andric 
52890b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
52900b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
52910b57cec5SDimitry Andric 
5292e8d8bef9SDimitry Andric   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5293e8d8bef9SDimitry Andric                                      options::OPT_fmemory_profile_EQ,
5294e8d8bef9SDimitry Andric                                      options::OPT_fno_memory_profile);
5295e8d8bef9SDimitry Andric   if (MemProfArg &&
5296e8d8bef9SDimitry Andric       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5297e8d8bef9SDimitry Andric     MemProfArg->render(Args, CmdArgs);
5298e8d8bef9SDimitry Andric 
529906c3fb27SDimitry Andric   if (auto *MemProfUseArg =
530006c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
530106c3fb27SDimitry Andric     if (MemProfArg)
530206c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
530306c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
530406c3fb27SDimitry Andric     if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
530506c3fb27SDimitry Andric                                             options::OPT_fprofile_generate_EQ))
530606c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
530706c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
530806c3fb27SDimitry Andric     MemProfUseArg->render(Args, CmdArgs);
530906c3fb27SDimitry Andric   }
531006c3fb27SDimitry Andric 
53110b57cec5SDimitry Andric   // Embed-bitcode option.
53120b57cec5SDimitry Andric   // Only white-listed flags below are allowed to be embedded.
5313fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
53140b57cec5SDimitry Andric       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
53150b57cec5SDimitry Andric     // Add flags implied by -fembed-bitcode.
53160b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
53170b57cec5SDimitry Andric     // Disable all llvm IR level optimizations.
53180b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
53190b57cec5SDimitry Andric 
5320480093f4SDimitry Andric     // Render target options.
53210b57cec5SDimitry Andric     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric     // reject options that shouldn't be supported in bitcode
53240b57cec5SDimitry Andric     // also reject kernel/kext
5325349cc55cSDimitry Andric     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
53260b57cec5SDimitry Andric         options::OPT_mkernel,
53270b57cec5SDimitry Andric         options::OPT_fapple_kext,
53280b57cec5SDimitry Andric         options::OPT_ffunction_sections,
53290b57cec5SDimitry Andric         options::OPT_fno_function_sections,
53300b57cec5SDimitry Andric         options::OPT_fdata_sections,
53310b57cec5SDimitry Andric         options::OPT_fno_data_sections,
53325ffd83dbSDimitry Andric         options::OPT_fbasic_block_sections_EQ,
53335ffd83dbSDimitry Andric         options::OPT_funique_internal_linkage_names,
53345ffd83dbSDimitry Andric         options::OPT_fno_unique_internal_linkage_names,
53350b57cec5SDimitry Andric         options::OPT_funique_section_names,
53360b57cec5SDimitry Andric         options::OPT_fno_unique_section_names,
53375ffd83dbSDimitry Andric         options::OPT_funique_basic_block_section_names,
53385ffd83dbSDimitry Andric         options::OPT_fno_unique_basic_block_section_names,
53390b57cec5SDimitry Andric         options::OPT_mrestrict_it,
53400b57cec5SDimitry Andric         options::OPT_mno_restrict_it,
53410b57cec5SDimitry Andric         options::OPT_mstackrealign,
53420b57cec5SDimitry Andric         options::OPT_mno_stackrealign,
53430b57cec5SDimitry Andric         options::OPT_mstack_alignment,
53440b57cec5SDimitry Andric         options::OPT_mcmodel_EQ,
53450b57cec5SDimitry Andric         options::OPT_mlong_calls,
53460b57cec5SDimitry Andric         options::OPT_mno_long_calls,
53470b57cec5SDimitry Andric         options::OPT_ggnu_pubnames,
53480b57cec5SDimitry Andric         options::OPT_gdwarf_aranges,
53490b57cec5SDimitry Andric         options::OPT_fdebug_types_section,
53500b57cec5SDimitry Andric         options::OPT_fno_debug_types_section,
53510b57cec5SDimitry Andric         options::OPT_fdwarf_directory_asm,
53520b57cec5SDimitry Andric         options::OPT_fno_dwarf_directory_asm,
53530b57cec5SDimitry Andric         options::OPT_mrelax_all,
53540b57cec5SDimitry Andric         options::OPT_mno_relax_all,
53550b57cec5SDimitry Andric         options::OPT_ftrap_function_EQ,
53560b57cec5SDimitry Andric         options::OPT_ffixed_r9,
53570b57cec5SDimitry Andric         options::OPT_mfix_cortex_a53_835769,
53580b57cec5SDimitry Andric         options::OPT_mno_fix_cortex_a53_835769,
53590b57cec5SDimitry Andric         options::OPT_ffixed_x18,
53600b57cec5SDimitry Andric         options::OPT_mglobal_merge,
53610b57cec5SDimitry Andric         options::OPT_mno_global_merge,
53620b57cec5SDimitry Andric         options::OPT_mred_zone,
53630b57cec5SDimitry Andric         options::OPT_mno_red_zone,
53640b57cec5SDimitry Andric         options::OPT_Wa_COMMA,
53650b57cec5SDimitry Andric         options::OPT_Xassembler,
53660b57cec5SDimitry Andric         options::OPT_mllvm,
53670b57cec5SDimitry Andric     };
53680b57cec5SDimitry Andric     for (const auto &A : Args)
5369349cc55cSDimitry Andric       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
53700b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
53710b57cec5SDimitry Andric 
53720b57cec5SDimitry Andric     // Render the CodeGen options that need to be passed.
537381ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
537481ad6265SDimitry Andric                        options::OPT_fno_optimize_sibling_calls);
53750b57cec5SDimitry Andric 
53760b57cec5SDimitry Andric     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
53775ffd83dbSDimitry Andric                                CmdArgs, JA);
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric     // Render ABI arguments
53800b57cec5SDimitry Andric     switch (TC.getArch()) {
53810b57cec5SDimitry Andric     default: break;
53820b57cec5SDimitry Andric     case llvm::Triple::arm:
53830b57cec5SDimitry Andric     case llvm::Triple::armeb:
53840b57cec5SDimitry Andric     case llvm::Triple::thumbeb:
5385349cc55cSDimitry Andric       RenderARMABI(D, Triple, Args, CmdArgs);
53860b57cec5SDimitry Andric       break;
53870b57cec5SDimitry Andric     case llvm::Triple::aarch64:
5388480093f4SDimitry Andric     case llvm::Triple::aarch64_32:
53890b57cec5SDimitry Andric     case llvm::Triple::aarch64_be:
53900b57cec5SDimitry Andric       RenderAArch64ABI(Triple, Args, CmdArgs);
53910b57cec5SDimitry Andric       break;
53920b57cec5SDimitry Andric     }
53930b57cec5SDimitry Andric 
53940b57cec5SDimitry Andric     // Optimization level for CodeGen.
53950b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
53960b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_O4)) {
53970b57cec5SDimitry Andric         CmdArgs.push_back("-O3");
53980b57cec5SDimitry Andric         D.Diag(diag::warn_O4_is_O3);
53990b57cec5SDimitry Andric       } else {
54000b57cec5SDimitry Andric         A->render(Args, CmdArgs);
54010b57cec5SDimitry Andric       }
54020b57cec5SDimitry Andric     }
54030b57cec5SDimitry Andric 
54040b57cec5SDimitry Andric     // Input/Output file.
54050b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies) {
54060b57cec5SDimitry Andric       // Handled with other dependency code.
54070b57cec5SDimitry Andric     } else if (Output.isFilename()) {
54080b57cec5SDimitry Andric       CmdArgs.push_back("-o");
54090b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
54100b57cec5SDimitry Andric     } else {
54110b57cec5SDimitry Andric       assert(Output.isNothing() && "Input output.");
54120b57cec5SDimitry Andric     }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric     for (const auto &II : Inputs) {
54150b57cec5SDimitry Andric       addDashXForInput(Args, II, CmdArgs);
54160b57cec5SDimitry Andric       if (II.isFilename())
54170b57cec5SDimitry Andric         CmdArgs.push_back(II.getFilename());
54180b57cec5SDimitry Andric       else
54190b57cec5SDimitry Andric         II.getInputArg().renderAsInput(Args, CmdArgs);
54200b57cec5SDimitry Andric     }
54210b57cec5SDimitry Andric 
5422e8d8bef9SDimitry Andric     C.addCommand(std::make_unique<Command>(
5423e8d8bef9SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
542406c3fb27SDimitry Andric         CmdArgs, Inputs, Output, D.getPrependArg()));
54250b57cec5SDimitry Andric     return;
54260b57cec5SDimitry Andric   }
54270b57cec5SDimitry Andric 
5428fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
54290b57cec5SDimitry Andric     CmdArgs.push_back("-fembed-bitcode=marker");
54300b57cec5SDimitry Andric 
54310b57cec5SDimitry Andric   // We normally speed up the clang process a bit by skipping destructors at
54320b57cec5SDimitry Andric   // exit, but when we're generating diagnostics we can rely on some of the
54330b57cec5SDimitry Andric   // cleanup.
54340b57cec5SDimitry Andric   if (!C.isForDiagnostics())
54350b57cec5SDimitry Andric     CmdArgs.push_back("-disable-free");
5436349cc55cSDimitry Andric   CmdArgs.push_back("-clear-ast-before-backend");
54370b57cec5SDimitry Andric 
54380b57cec5SDimitry Andric #ifdef NDEBUG
54390b57cec5SDimitry Andric   const bool IsAssertBuild = false;
54400b57cec5SDimitry Andric #else
54410b57cec5SDimitry Andric   const bool IsAssertBuild = true;
54420b57cec5SDimitry Andric #endif
54430b57cec5SDimitry Andric 
54445f757f3fSDimitry Andric   // Disable the verification pass in asserts builds unless otherwise specified.
54455f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
54465f757f3fSDimitry Andric                    options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
54470b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-verifier");
54485f757f3fSDimitry Andric   }
54490b57cec5SDimitry Andric 
54500b57cec5SDimitry Andric   // Discard value names in assert builds unless otherwise specified.
54510b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdiscard_value_names,
545247395794SDimitry Andric                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
545347395794SDimitry Andric     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5454349cc55cSDimitry Andric         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
545547395794SDimitry Andric           return types::isLLVMIR(II.getType());
5456349cc55cSDimitry Andric         })) {
545747395794SDimitry Andric       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
545847395794SDimitry Andric     }
54590b57cec5SDimitry Andric     CmdArgs.push_back("-discard-value-names");
546047395794SDimitry Andric   }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
54630b57cec5SDimitry Andric   // -save-temps.
54640b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
54650b57cec5SDimitry Andric   CmdArgs.push_back(getBaseInputName(Args, Input));
54660b57cec5SDimitry Andric 
54670b57cec5SDimitry Andric   // Some flags which affect the language (via preprocessor
54680b57cec5SDimitry Andric   // defines).
54690b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
54700b57cec5SDimitry Andric     CmdArgs.push_back("-static-define");
54710b57cec5SDimitry Andric 
54720b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_municode))
54730b57cec5SDimitry Andric     CmdArgs.push_back("-DUNICODE");
54740b57cec5SDimitry Andric 
54750b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA))
54760b57cec5SDimitry Andric     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
54770b57cec5SDimitry Andric 
5478a7dea167SDimitry Andric   if (isa<AnalyzeJobAction>(JA) ||
5479a7dea167SDimitry Andric       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5480a7dea167SDimitry Andric     CmdArgs.push_back("-setup-static-analyzer");
5481a7dea167SDimitry Andric 
54820b57cec5SDimitry Andric   // Enable compatilibily mode to avoid analyzer-config related errors.
54830b57cec5SDimitry Andric   // Since we can't access frontend flags through hasArg, let's manually iterate
54840b57cec5SDimitry Andric   // through them.
54850b57cec5SDimitry Andric   bool FoundAnalyzerConfig = false;
5486bdd1243dSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
54870b57cec5SDimitry Andric     if (StringRef(Arg->getValue()) == "-analyzer-config") {
54880b57cec5SDimitry Andric       FoundAnalyzerConfig = true;
54890b57cec5SDimitry Andric       break;
54900b57cec5SDimitry Andric     }
54910b57cec5SDimitry Andric   if (!FoundAnalyzerConfig)
5492bdd1243dSDimitry Andric     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
54930b57cec5SDimitry Andric       if (StringRef(Arg->getValue()) == "-analyzer-config") {
54940b57cec5SDimitry Andric         FoundAnalyzerConfig = true;
54950b57cec5SDimitry Andric         break;
54960b57cec5SDimitry Andric       }
54970b57cec5SDimitry Andric   if (FoundAnalyzerConfig)
54980b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
54990b57cec5SDimitry Andric 
55000b57cec5SDimitry Andric   CheckCodeGenerationOptions(D, Args);
55010b57cec5SDimitry Andric 
55020b57cec5SDimitry Andric   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
55030b57cec5SDimitry Andric   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
55040b57cec5SDimitry Andric   if (FunctionAlignment) {
55050b57cec5SDimitry Andric     CmdArgs.push_back("-function-alignment");
55060b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
55070b57cec5SDimitry Andric   }
55080b57cec5SDimitry Andric 
5509349cc55cSDimitry Andric   // We support -falign-loops=N where N is a power of 2. GCC supports more
5510349cc55cSDimitry Andric   // forms.
5511349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5512349cc55cSDimitry Andric     unsigned Value = 0;
5513349cc55cSDimitry Andric     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5514349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5515349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5516349cc55cSDimitry Andric     else if (Value & (Value - 1))
5517349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5518349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5519349cc55cSDimitry Andric     // Treat =0 as unspecified (use the target preference).
5520349cc55cSDimitry Andric     if (Value)
5521349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5522349cc55cSDimitry Andric                                            Twine(std::min(Value, 65536u))));
5523349cc55cSDimitry Andric   }
5524349cc55cSDimitry Andric 
552506c3fb27SDimitry Andric   if (Triple.isOSzOS()) {
552606c3fb27SDimitry Andric     // On z/OS some of the system header feature macros need to
552706c3fb27SDimitry Andric     // be defined to enable most cross platform projects to build
552806c3fb27SDimitry Andric     // successfully.  Ths include the libc++ library.  A
552906c3fb27SDimitry Andric     // complicating factor is that users can define these
553006c3fb27SDimitry Andric     // macros to the same or different values.  We need to add
553106c3fb27SDimitry Andric     // the definition for these macros to the compilation command
553206c3fb27SDimitry Andric     // if the user hasn't already defined them.
553306c3fb27SDimitry Andric 
553406c3fb27SDimitry Andric     auto findMacroDefinition = [&](const std::string &Macro) {
553506c3fb27SDimitry Andric       auto MacroDefs = Args.getAllArgValues(options::OPT_D);
55365f757f3fSDimitry Andric       return llvm::any_of(MacroDefs, [&](const std::string &M) {
55375f757f3fSDimitry Andric         return M == Macro || M.find(Macro + '=') != std::string::npos;
55385f757f3fSDimitry Andric       });
553906c3fb27SDimitry Andric     };
554006c3fb27SDimitry Andric 
554106c3fb27SDimitry Andric     // _UNIX03_WITHDRAWN is required for libcxx & porting.
554206c3fb27SDimitry Andric     if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
554306c3fb27SDimitry Andric       CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
554406c3fb27SDimitry Andric     // _OPEN_DEFAULT is required for XL compat
554506c3fb27SDimitry Andric     if (!findMacroDefinition("_OPEN_DEFAULT"))
554606c3fb27SDimitry Andric       CmdArgs.push_back("-D_OPEN_DEFAULT");
554706c3fb27SDimitry Andric     if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
554806c3fb27SDimitry Andric       // _XOPEN_SOURCE=600 is required for libcxx.
554906c3fb27SDimitry Andric       if (!findMacroDefinition("_XOPEN_SOURCE"))
555006c3fb27SDimitry Andric         CmdArgs.push_back("-D_XOPEN_SOURCE=600");
555106c3fb27SDimitry Andric     }
555206c3fb27SDimitry Andric   }
555306c3fb27SDimitry Andric 
55540b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
55550b57cec5SDimitry Andric   unsigned PICLevel;
55560b57cec5SDimitry Andric   bool IsPIE;
55570b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5558bdd1243dSDimitry Andric   Arg *LastPICDataRelArg =
5559bdd1243dSDimitry Andric       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5560bdd1243dSDimitry Andric                       options::OPT_mpic_data_is_text_relative);
5561bdd1243dSDimitry Andric   bool NoPICDataIsTextRelative = false;
5562bdd1243dSDimitry Andric   if (LastPICDataRelArg) {
5563bdd1243dSDimitry Andric     if (LastPICDataRelArg->getOption().matches(
5564bdd1243dSDimitry Andric             options::OPT_mno_pic_data_is_text_relative)) {
5565bdd1243dSDimitry Andric       NoPICDataIsTextRelative = true;
5566bdd1243dSDimitry Andric       if (!PICLevel)
5567bdd1243dSDimitry Andric         D.Diag(diag::err_drv_argument_only_allowed_with)
5568bdd1243dSDimitry Andric             << "-mno-pic-data-is-text-relative"
5569bdd1243dSDimitry Andric             << "-fpic/-fpie";
5570bdd1243dSDimitry Andric     }
5571bdd1243dSDimitry Andric     if (!Triple.isSystemZ())
5572bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5573bdd1243dSDimitry Andric           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5574bdd1243dSDimitry Andric                                       : "-mpic-data-is-text-relative")
5575bdd1243dSDimitry Andric           << RawTriple.str();
5576bdd1243dSDimitry Andric   }
55770b57cec5SDimitry Andric 
55785ffd83dbSDimitry Andric   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
55795ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
55805ffd83dbSDimitry Andric   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
55815ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
55820b57cec5SDimitry Andric 
55835ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_mcmse) &&
55845ffd83dbSDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported)) {
55855ffd83dbSDimitry Andric     if (IsROPI)
55865ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
55875ffd83dbSDimitry Andric     if (IsRWPI)
55885ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
55895ffd83dbSDimitry Andric   }
55905ffd83dbSDimitry Andric 
55915ffd83dbSDimitry Andric   if (IsROPI && types::isCXX(Input.getType()) &&
55920b57cec5SDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported))
55930b57cec5SDimitry Andric     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
55940b57cec5SDimitry Andric 
55955ffd83dbSDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
55960b57cec5SDimitry Andric   if (RMName) {
55970b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
55980b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
55990b57cec5SDimitry Andric   }
56000b57cec5SDimitry Andric   if (PICLevel > 0) {
56010b57cec5SDimitry Andric     CmdArgs.push_back("-pic-level");
56020b57cec5SDimitry Andric     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
56030b57cec5SDimitry Andric     if (IsPIE)
56040b57cec5SDimitry Andric       CmdArgs.push_back("-pic-is-pie");
5605bdd1243dSDimitry Andric     if (NoPICDataIsTextRelative)
5606bdd1243dSDimitry Andric       CmdArgs.push_back("-mcmodel=medium");
56070b57cec5SDimitry Andric   }
56080b57cec5SDimitry Andric 
56090b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::ROPI ||
56100b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
56110b57cec5SDimitry Andric     CmdArgs.push_back("-fropi");
56120b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::RWPI ||
56130b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
56140b57cec5SDimitry Andric     CmdArgs.push_back("-frwpi");
56150b57cec5SDimitry Andric 
56160b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
56170b57cec5SDimitry Andric     CmdArgs.push_back("-meabi");
56180b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
56190b57cec5SDimitry Andric   }
56200b57cec5SDimitry Andric 
5621e8d8bef9SDimitry Andric   // -fsemantic-interposition is forwarded to CC1: set the
5622e8d8bef9SDimitry Andric   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5623e8d8bef9SDimitry Andric   // make default visibility external linkage definitions dso_preemptable.
5624e8d8bef9SDimitry Andric   //
5625e8d8bef9SDimitry Andric   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5626e8d8bef9SDimitry Andric   // aliases (make default visibility external linkage definitions dso_local).
5627e8d8bef9SDimitry Andric   // This is the CC1 default for ELF to match COFF/Mach-O.
5628e8d8bef9SDimitry Andric   //
5629e8d8bef9SDimitry Andric   // Otherwise use Clang's traditional behavior: like
5630e8d8bef9SDimitry Andric   // -fno-semantic-interposition but local aliases are not used. So references
5631e8d8bef9SDimitry Andric   // can be interposed if not optimized out.
5632e8d8bef9SDimitry Andric   if (Triple.isOSBinFormatELF()) {
5633e8d8bef9SDimitry Andric     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5634e8d8bef9SDimitry Andric                              options::OPT_fno_semantic_interposition);
5635e8d8bef9SDimitry Andric     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5636e8d8bef9SDimitry Andric       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5637fe6060f1SDimitry Andric       bool SupportsLocalAlias =
5638fe6060f1SDimitry Andric           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5639e8d8bef9SDimitry Andric       if (!A)
5640e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5641e8d8bef9SDimitry Andric       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
56425ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
5643e8d8bef9SDimitry Andric       else if (!SupportsLocalAlias)
5644e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5645e8d8bef9SDimitry Andric     }
5646e8d8bef9SDimitry Andric   }
56475ffd83dbSDimitry Andric 
56485ffd83dbSDimitry Andric   {
56495ffd83dbSDimitry Andric     std::string Model;
56500b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
56510b57cec5SDimitry Andric       if (!TC.isThreadModelSupported(A->getValue()))
56520b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_thread_model_for_target)
56530b57cec5SDimitry Andric             << A->getValue() << A->getAsString(Args);
56545ffd83dbSDimitry Andric       Model = A->getValue();
56555ffd83dbSDimitry Andric     } else
56565ffd83dbSDimitry Andric       Model = TC.getThreadModel();
56575ffd83dbSDimitry Andric     if (Model != "posix") {
56585ffd83dbSDimitry Andric       CmdArgs.push_back("-mthread-model");
56595ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Model));
56600b57cec5SDimitry Andric     }
56615ffd83dbSDimitry Andric   }
56620b57cec5SDimitry Andric 
5663bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5664bdd1243dSDimitry Andric     StringRef Name = A->getValue();
5665bdd1243dSDimitry Andric     if (Name == "SVML") {
5666bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5667bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5668bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5669bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5670bdd1243dSDimitry Andric     } else if (Name == "LIBMVEC-X86") {
5671bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5672bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5673bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5674bdd1243dSDimitry Andric             << Name << Triple.getArchName();
567506c3fb27SDimitry Andric     } else if (Name == "SLEEF" || Name == "ArmPL") {
5676bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::aarch64 &&
5677bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::aarch64_be)
5678bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5679bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5680bdd1243dSDimitry Andric     }
5681bdd1243dSDimitry Andric     A->render(Args, CmdArgs);
5682bdd1243dSDimitry Andric   }
56830b57cec5SDimitry Andric 
56840b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmerge_all_constants,
56850b57cec5SDimitry Andric                    options::OPT_fno_merge_all_constants, false))
56860b57cec5SDimitry Andric     CmdArgs.push_back("-fmerge-all-constants");
56870b57cec5SDimitry Andric 
5688bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5689bdd1243dSDimitry Andric                      options::OPT_fno_delete_null_pointer_checks);
56900b57cec5SDimitry Andric 
56910b57cec5SDimitry Andric   // LLVM Code Generator Options.
56920b57cec5SDimitry Andric 
5693972a253aSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5694972a253aSDimitry Andric     if (!Triple.isOSAIX() || Triple.isPPC32())
5695972a253aSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5696972a253aSDimitry Andric         << A->getSpelling() << RawTriple.str();
5697972a253aSDimitry Andric     CmdArgs.push_back("-mabi=quadword-atomics");
5698972a253aSDimitry Andric   }
5699972a253aSDimitry Andric 
5700fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5701fe6060f1SDimitry Andric     // Emit the unsupported option error until the Clang's library integration
5702fe6060f1SDimitry Andric     // support for 128-bit long double is available for AIX.
5703fe6060f1SDimitry Andric     if (Triple.isOSAIX())
5704fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5705fe6060f1SDimitry Andric           << A->getSpelling() << RawTriple.str();
5706e8d8bef9SDimitry Andric   }
5707e8d8bef9SDimitry Andric 
57080b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
570906c3fb27SDimitry Andric     StringRef V = A->getValue(), V1 = V;
571006c3fb27SDimitry Andric     unsigned Size;
571106c3fb27SDimitry Andric     if (V1.consumeInteger(10, Size) || !V1.empty())
571206c3fb27SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
571306c3fb27SDimitry Andric           << V << A->getOption().getName();
5714fe6060f1SDimitry Andric     else
571506c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
57160b57cec5SDimitry Andric   }
57170b57cec5SDimitry Andric 
571881ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
571981ad6265SDimitry Andric                      options::OPT_fno_jump_tables);
572081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
572181ad6265SDimitry Andric                     options::OPT_fno_profile_sample_accurate);
572281ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
572381ad6265SDimitry Andric                      options::OPT_fno_preserve_as_comments);
57240b57cec5SDimitry Andric 
57250b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
57260b57cec5SDimitry Andric     CmdArgs.push_back("-mregparm");
57270b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
57280b57cec5SDimitry Andric   }
57290b57cec5SDimitry Andric 
5730e86cf8adSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5731e86cf8adSDimitry Andric                                options::OPT_msvr4_struct_return)) {
5732e8d8bef9SDimitry Andric     if (!TC.getTriple().isPPC32()) {
5733e86cf8adSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5734e86cf8adSDimitry Andric           << A->getSpelling() << RawTriple.str();
5735e86cf8adSDimitry Andric     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5736e86cf8adSDimitry Andric       CmdArgs.push_back("-maix-struct-return");
5737e86cf8adSDimitry Andric     } else {
5738e86cf8adSDimitry Andric       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5739e86cf8adSDimitry Andric       CmdArgs.push_back("-msvr4-struct-return");
5740e86cf8adSDimitry Andric     }
5741e86cf8adSDimitry Andric   }
5742e86cf8adSDimitry Andric 
57430b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
57440b57cec5SDimitry Andric                                options::OPT_freg_struct_return)) {
57450b57cec5SDimitry Andric     if (TC.getArch() != llvm::Triple::x86) {
57460b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
57470b57cec5SDimitry Andric           << A->getSpelling() << RawTriple.str();
57480b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
57490b57cec5SDimitry Andric       CmdArgs.push_back("-fpcc-struct-return");
57500b57cec5SDimitry Andric     } else {
57510b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_freg_struct_return));
57520b57cec5SDimitry Andric       CmdArgs.push_back("-freg-struct-return");
57530b57cec5SDimitry Andric     }
57540b57cec5SDimitry Andric   }
57550b57cec5SDimitry Andric 
57565f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
57575f757f3fSDimitry Andric     if (Triple.getArch() == llvm::Triple::m68k)
57585f757f3fSDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
57595f757f3fSDimitry Andric     else
57600b57cec5SDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=stdcall");
57615f757f3fSDimitry Andric   }
57620b57cec5SDimitry Andric 
57635ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_fenable_matrix)) {
57645ffd83dbSDimitry Andric     // enable-matrix is needed by both the LangOpts and by LLVM.
57655ffd83dbSDimitry Andric     CmdArgs.push_back("-fenable-matrix");
57665ffd83dbSDimitry Andric     CmdArgs.push_back("-mllvm");
57675ffd83dbSDimitry Andric     CmdArgs.push_back("-enable-matrix");
57685ffd83dbSDimitry Andric   }
57695ffd83dbSDimitry Andric 
5770a7dea167SDimitry Andric   CodeGenOptions::FramePointerKind FPKeepKind =
5771a7dea167SDimitry Andric                   getFramePointerKind(Args, RawTriple);
5772a7dea167SDimitry Andric   const char *FPKeepKindStr = nullptr;
5773a7dea167SDimitry Andric   switch (FPKeepKind) {
5774a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
5775a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=none";
5776a7dea167SDimitry Andric     break;
57770fca6ea1SDimitry Andric   case CodeGenOptions::FramePointerKind::Reserved:
57780fca6ea1SDimitry Andric     FPKeepKindStr = "-mframe-pointer=reserved";
57790fca6ea1SDimitry Andric     break;
5780a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
5781a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=non-leaf";
5782a7dea167SDimitry Andric     break;
5783a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
5784a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=all";
5785a7dea167SDimitry Andric     break;
5786a7dea167SDimitry Andric   }
5787a7dea167SDimitry Andric   assert(FPKeepKindStr && "unknown FramePointerKind");
5788a7dea167SDimitry Andric   CmdArgs.push_back(FPKeepKindStr);
5789a7dea167SDimitry Andric 
579081ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
579181ad6265SDimitry Andric                      options::OPT_fno_zero_initialized_in_bss);
57920b57cec5SDimitry Andric 
57930b57cec5SDimitry Andric   bool OFastEnabled = isOptimizationLevelFast(Args);
57940fca6ea1SDimitry Andric   if (OFastEnabled)
57950fca6ea1SDimitry Andric     D.Diag(diag::warn_drv_deprecated_arg_ofast);
57960b57cec5SDimitry Andric   // If -Ofast is the optimization level, then -fstrict-aliasing should be
57970b57cec5SDimitry Andric   // enabled.  This alias option is being used to simplify the hasFlag logic.
57980b57cec5SDimitry Andric   OptSpecifier StrictAliasingAliasOption =
57990b57cec5SDimitry Andric       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
58000fca6ea1SDimitry Andric   // We turn strict aliasing off by default if we're Windows MSVC since MSVC
58010b57cec5SDimitry Andric   // doesn't do any TBAA.
58020b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
58030fca6ea1SDimitry Andric                     options::OPT_fno_strict_aliasing, !IsWindowsMSVC))
58040b57cec5SDimitry Andric     CmdArgs.push_back("-relaxed-aliasing");
58050fca6ea1SDimitry Andric   if (Args.hasFlag(options::OPT_fpointer_tbaa, options::OPT_fno_pointer_tbaa,
58060fca6ea1SDimitry Andric                    false))
58070fca6ea1SDimitry Andric     CmdArgs.push_back("-pointer-tbaa");
58080b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
580981ad6265SDimitry Andric                     options::OPT_fno_struct_path_tbaa, true))
58100b57cec5SDimitry Andric     CmdArgs.push_back("-no-struct-path-tbaa");
581181ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
581281ad6265SDimitry Andric                     options::OPT_fno_strict_enums);
581381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
581481ad6265SDimitry Andric                      options::OPT_fno_strict_return);
581581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
581681ad6265SDimitry Andric                     options::OPT_fno_allow_editor_placeholders);
581781ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
581881ad6265SDimitry Andric                     options::OPT_fno_strict_vtable_pointers);
581981ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
582081ad6265SDimitry Andric                     options::OPT_fno_force_emit_vtables);
582181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
582281ad6265SDimitry Andric                      options::OPT_fno_optimize_sibling_calls);
582381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
582481ad6265SDimitry Andric                      options::OPT_fno_escaping_block_tail_calls);
58250b57cec5SDimitry Andric 
58260b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
58270b57cec5SDimitry Andric                   options::OPT_fno_fine_grained_bitfield_accesses);
58280b57cec5SDimitry Andric 
5829fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5830fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5831fe6060f1SDimitry Andric 
58325f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
58335f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
58345f757f3fSDimitry Andric 
58350fca6ea1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
58360fca6ea1SDimitry Andric                   options::OPT_fno_disable_block_signature_string);
58370fca6ea1SDimitry Andric 
58380b57cec5SDimitry Andric   // Handle segmented stacks.
5839bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5840bdd1243dSDimitry Andric                     options::OPT_fno_split_stack);
5841fe6060f1SDimitry Andric 
5842fe6060f1SDimitry Andric   // -fprotect-parens=0 is default.
5843fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fprotect_parens,
5844fe6060f1SDimitry Andric                    options::OPT_fno_protect_parens, false))
5845fe6060f1SDimitry Andric     CmdArgs.push_back("-fprotect-parens");
58460b57cec5SDimitry Andric 
58475ffd83dbSDimitry Andric   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
58485ffd83dbSDimitry Andric 
5849fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5850fe6060f1SDimitry Andric     const llvm::Triple::ArchType Arch = TC.getArch();
5851fe6060f1SDimitry Andric     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5852fe6060f1SDimitry Andric       StringRef V = A->getValue();
5853fe6060f1SDimitry Andric       if (V == "64")
5854fe6060f1SDimitry Andric         CmdArgs.push_back("-fextend-arguments=64");
5855fe6060f1SDimitry Andric       else if (V != "32")
5856fe6060f1SDimitry Andric         D.Diag(diag::err_drv_invalid_argument_to_option)
5857fe6060f1SDimitry Andric             << A->getValue() << A->getOption().getName();
5858fe6060f1SDimitry Andric     } else
5859fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5860fe6060f1SDimitry Andric           << A->getOption().getName() << TripleStr;
5861fe6060f1SDimitry Andric   }
5862fe6060f1SDimitry Andric 
58635ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
58645ffd83dbSDimitry Andric     if (TC.getArch() == llvm::Triple::avr)
58655ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
58665ffd83dbSDimitry Andric     else
58675ffd83dbSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
58685ffd83dbSDimitry Andric           << A->getAsString(Args) << TripleStr;
58695ffd83dbSDimitry Andric   }
58700b57cec5SDimitry Andric 
5871a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5872480093f4SDimitry Andric     if (TC.getTriple().isX86())
5873a7dea167SDimitry Andric       A->render(Args, CmdArgs);
5874e8d8bef9SDimitry Andric     else if (TC.getTriple().isPPC() &&
5875a7dea167SDimitry Andric              (A->getOption().getID() != options::OPT_mlong_double_80))
58760b57cec5SDimitry Andric       A->render(Args, CmdArgs);
58770b57cec5SDimitry Andric     else
58780b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
58790b57cec5SDimitry Andric           << A->getAsString(Args) << TripleStr;
58800b57cec5SDimitry Andric   }
58810b57cec5SDimitry Andric 
58820b57cec5SDimitry Andric   // Decide whether to use verbose asm. Verbose assembly is the default on
58830b57cec5SDimitry Andric   // toolchains which have the integrated assembler on by default.
58840b57cec5SDimitry Andric   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
58855ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5886a7dea167SDimitry Andric                     IsIntegratedAssemblerDefault))
58875ffd83dbSDimitry Andric     CmdArgs.push_back("-fno-verbose-asm");
58880b57cec5SDimitry Andric 
5889e8d8bef9SDimitry Andric   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5890e8d8bef9SDimitry Andric   // use that to indicate the MC default in the backend.
5891e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5892e8d8bef9SDimitry Andric     StringRef V = A->getValue();
5893e8d8bef9SDimitry Andric     unsigned Num;
5894e8d8bef9SDimitry Andric     if (V == "none")
5895e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5896e8d8bef9SDimitry Andric     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5897e8d8bef9SDimitry Andric              (V.empty() || (V.consume_front(".") &&
5898e8d8bef9SDimitry Andric                             !V.consumeInteger(10, Num) && V.empty())))
5899e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5900e8d8bef9SDimitry Andric     else
5901e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
5902e8d8bef9SDimitry Andric           << A->getValue() << A->getOption().getName();
5903e8d8bef9SDimitry Andric   }
5904e8d8bef9SDimitry Andric 
5905fe6060f1SDimitry Andric   // If toolchain choose to use MCAsmParser for inline asm don't pass the
59060fca6ea1SDimitry Andric   // option to disable integrated-as explicitly.
5907fe6060f1SDimitry Andric   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
59080b57cec5SDimitry Andric     CmdArgs.push_back("-no-integrated-as");
59090b57cec5SDimitry Andric 
59100b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
59110b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
59120b57cec5SDimitry Andric     CmdArgs.push_back("Structure");
59130b57cec5SDimitry Andric   }
59140b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
59150b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
59160b57cec5SDimitry Andric     CmdArgs.push_back("Arguments");
59170b57cec5SDimitry Andric   }
59180b57cec5SDimitry Andric 
59190b57cec5SDimitry Andric   // Enable -mconstructor-aliases except on darwin, where we have to work around
59205f757f3fSDimitry Andric   // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
59215f757f3fSDimitry Andric   // code, where aliases aren't supported.
5922349cc55cSDimitry Andric   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
59230b57cec5SDimitry Andric     CmdArgs.push_back("-mconstructor-aliases");
59240b57cec5SDimitry Andric 
59250b57cec5SDimitry Andric   // Darwin's kernel doesn't support guard variables; just die if we
59260b57cec5SDimitry Andric   // try to use them.
59270b57cec5SDimitry Andric   if (KernelOrKext && RawTriple.isOSDarwin())
59280b57cec5SDimitry Andric     CmdArgs.push_back("-fforbid-guard-variables");
59290b57cec5SDimitry Andric 
59300b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
59315ffd83dbSDimitry Andric                    Triple.isWindowsGNUEnvironment())) {
59320b57cec5SDimitry Andric     CmdArgs.push_back("-mms-bitfields");
59330b57cec5SDimitry Andric   }
59340b57cec5SDimitry Andric 
59355f757f3fSDimitry Andric   if (Triple.isWindowsGNUEnvironment()) {
59365f757f3fSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
59375f757f3fSDimitry Andric                        options::OPT_fno_auto_import);
59385f757f3fSDimitry Andric   }
59395f757f3fSDimitry Andric 
59405f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
59415f757f3fSDimitry Andric                    Triple.isX86() && D.IsCLMode()))
59425f757f3fSDimitry Andric     CmdArgs.push_back("-fms-volatile");
59435f757f3fSDimitry Andric 
5944e8d8bef9SDimitry Andric   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5945e8d8bef9SDimitry Andric   // defaults to -fno-direct-access-external-data. Pass the option if different
5946e8d8bef9SDimitry Andric   // from the default.
5947e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
59485f757f3fSDimitry Andric                                options::OPT_fno_direct_access_external_data)) {
5949e8d8bef9SDimitry Andric     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5950e8d8bef9SDimitry Andric         (PICLevel == 0))
5951e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
59525f757f3fSDimitry Andric   } else if (PICLevel == 0 && Triple.isLoongArch()) {
59535f757f3fSDimitry Andric     // Some targets default to -fno-direct-access-external-data even for
59545f757f3fSDimitry Andric     // -fno-pic.
59555f757f3fSDimitry Andric     CmdArgs.push_back("-fno-direct-access-external-data");
59565f757f3fSDimitry Andric   }
59570b57cec5SDimitry Andric 
59580b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
59590b57cec5SDimitry Andric     CmdArgs.push_back("-fno-plt");
59600b57cec5SDimitry Andric   }
59610b57cec5SDimitry Andric 
59620b57cec5SDimitry Andric   // -fhosted is default.
59630b57cec5SDimitry Andric   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
59640b57cec5SDimitry Andric   // use Freestanding.
59650b57cec5SDimitry Andric   bool Freestanding =
59660b57cec5SDimitry Andric       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
59670b57cec5SDimitry Andric       KernelOrKext;
59680b57cec5SDimitry Andric   if (Freestanding)
59690b57cec5SDimitry Andric     CmdArgs.push_back("-ffreestanding");
59700b57cec5SDimitry Andric 
597181ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
597281ad6265SDimitry Andric 
59730b57cec5SDimitry Andric   // This is a coarse approximation of what llvm-gcc actually does, both
59740b57cec5SDimitry Andric   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
59750b57cec5SDimitry Andric   // complicated ways.
5976349cc55cSDimitry Andric   auto SanitizeArgs = TC.getSanitizerArgs(Args);
5977bdd1243dSDimitry Andric 
5978bdd1243dSDimitry Andric   bool IsAsyncUnwindTablesDefault =
5979bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5980bdd1243dSDimitry Andric   bool IsSyncUnwindTablesDefault =
5981bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5982bdd1243dSDimitry Andric 
5983349cc55cSDimitry Andric   bool AsyncUnwindTables = Args.hasFlag(
5984349cc55cSDimitry Andric       options::OPT_fasynchronous_unwind_tables,
59850b57cec5SDimitry Andric       options::OPT_fno_asynchronous_unwind_tables,
5986bdd1243dSDimitry Andric       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
59870b57cec5SDimitry Andric           !Freestanding);
5988bdd1243dSDimitry Andric   bool UnwindTables =
5989bdd1243dSDimitry Andric       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5990bdd1243dSDimitry Andric                    IsSyncUnwindTablesDefault && !Freestanding);
5991349cc55cSDimitry Andric   if (AsyncUnwindTables)
5992349cc55cSDimitry Andric     CmdArgs.push_back("-funwind-tables=2");
5993349cc55cSDimitry Andric   else if (UnwindTables)
5994349cc55cSDimitry Andric      CmdArgs.push_back("-funwind-tables=1");
59950b57cec5SDimitry Andric 
59965ffd83dbSDimitry Andric   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
59975ffd83dbSDimitry Andric   // `--gpu-use-aux-triple-only` is specified.
59985ffd83dbSDimitry Andric   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5999fe6060f1SDimitry Andric       (IsCudaDevice || IsHIPDevice)) {
60005ffd83dbSDimitry Andric     const ArgList &HostArgs =
60015ffd83dbSDimitry Andric         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
60025ffd83dbSDimitry Andric     std::string HostCPU =
6003349cc55cSDimitry Andric         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
60045ffd83dbSDimitry Andric     if (!HostCPU.empty()) {
60055ffd83dbSDimitry Andric       CmdArgs.push_back("-aux-target-cpu");
60065ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(HostCPU));
60075ffd83dbSDimitry Andric     }
60085ffd83dbSDimitry Andric     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
60095ffd83dbSDimitry Andric                       /*ForAS*/ false, /*IsAux*/ true);
60105ffd83dbSDimitry Andric   }
60115ffd83dbSDimitry Andric 
60120b57cec5SDimitry Andric   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
60130b57cec5SDimitry Andric 
60140fca6ea1SDimitry Andric   addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
60150b57cec5SDimitry Andric 
6016480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6017480093f4SDimitry Andric     StringRef Value = A->getValue();
6018480093f4SDimitry Andric     unsigned TLSSize = 0;
6019480093f4SDimitry Andric     Value.getAsInteger(10, TLSSize);
6020480093f4SDimitry Andric     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6021480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6022480093f4SDimitry Andric           << A->getOption().getName() << TripleStr;
6023480093f4SDimitry Andric     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6024480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
6025480093f4SDimitry Andric           << A->getOption().getName() << Value;
6026480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6027480093f4SDimitry Andric   }
6028480093f4SDimitry Andric 
6029b3edf446SDimitry Andric   if (isTLSDESCEnabled(TC, Args))
6030b3edf446SDimitry Andric     CmdArgs.push_back("-enable-tlsdesc");
6031b3edf446SDimitry Andric 
60320b57cec5SDimitry Andric   // Add the target cpu
6033349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
60340b57cec5SDimitry Andric   if (!CPU.empty()) {
60350b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
60360b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
60370b57cec5SDimitry Andric   }
60380b57cec5SDimitry Andric 
60390b57cec5SDimitry Andric   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
60400b57cec5SDimitry Andric 
60410b57cec5SDimitry Andric   // Add clang-cl arguments.
60420b57cec5SDimitry Andric   types::ID InputType = Input.getType();
60430b57cec5SDimitry Andric   if (D.IsCLMode())
60445f757f3fSDimitry Andric     AddClangCLArgs(Args, InputType, CmdArgs);
60450b57cec5SDimitry Andric 
60465f757f3fSDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
60475f757f3fSDimitry Andric       llvm::codegenoptions::NoDebugInfo;
6048e8d8bef9SDimitry Andric   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
60495f757f3fSDimitry Andric   renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
60505f757f3fSDimitry Andric                      CmdArgs, Output, DebugInfoKind, DwarfFission);
605181ad6265SDimitry Andric 
60520b57cec5SDimitry Andric   // Add the split debug info name to the command lines here so we
60530b57cec5SDimitry Andric   // can propagate it to the backend.
60540b57cec5SDimitry Andric   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6055e8d8bef9SDimitry Andric                     (TC.getTriple().isOSBinFormatELF() ||
605606c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatWasm() ||
605706c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatCOFF()) &&
60580b57cec5SDimitry Andric                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
60590b57cec5SDimitry Andric                      isa<BackendJobAction>(JA));
60600b57cec5SDimitry Andric   if (SplitDWARF) {
6061e8d8bef9SDimitry Andric     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
60620b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-file");
60630b57cec5SDimitry Andric     CmdArgs.push_back(SplitDWARFOut);
60640b57cec5SDimitry Andric     if (DwarfFission == DwarfFissionKind::Split) {
60650b57cec5SDimitry Andric       CmdArgs.push_back("-split-dwarf-output");
60660b57cec5SDimitry Andric       CmdArgs.push_back(SplitDWARFOut);
60670b57cec5SDimitry Andric     }
60680b57cec5SDimitry Andric   }
60690b57cec5SDimitry Andric 
60700b57cec5SDimitry Andric   // Pass the linker version in use.
60710b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
60720b57cec5SDimitry Andric     CmdArgs.push_back("-target-linker-version");
60730b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
60740b57cec5SDimitry Andric   }
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric   // Explicitly error on some things we know we don't support and can't just
60770b57cec5SDimitry Andric   // ignore.
60780b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
60790b57cec5SDimitry Andric     Arg *Unsupported;
60800b57cec5SDimitry Andric     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
60810b57cec5SDimitry Andric         TC.getArch() == llvm::Triple::x86) {
60820b57cec5SDimitry Andric       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
60830b57cec5SDimitry Andric           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
60840b57cec5SDimitry Andric         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
60850b57cec5SDimitry Andric             << Unsupported->getOption().getName();
60860b57cec5SDimitry Andric     }
60870b57cec5SDimitry Andric     // The faltivec option has been superseded by the maltivec option.
60880b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
60890b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
60900b57cec5SDimitry Andric           << Unsupported->getOption().getName()
60910b57cec5SDimitry Andric           << "please use -maltivec and include altivec.h explicitly";
60920b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
60930b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
60940b57cec5SDimitry Andric           << Unsupported->getOption().getName() << "please use -mno-altivec";
60950b57cec5SDimitry Andric   }
60960b57cec5SDimitry Andric 
60970b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_v);
60985ffd83dbSDimitry Andric 
60995ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_H)) {
61005ffd83dbSDimitry Andric     CmdArgs.push_back("-H");
61015ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
61025ffd83dbSDimitry Andric   }
6103fe6060f1SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
61045ffd83dbSDimitry Andric 
6105bdd1243dSDimitry Andric   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
61060b57cec5SDimitry Andric     CmdArgs.push_back("-header-include-file");
6107fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6108fe6060f1SDimitry Andric                           ? D.CCPrintHeadersFilename.c_str()
61090b57cec5SDimitry Andric                           : "-");
61105ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
6111bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
6112bdd1243dSDimitry Andric         "-header-include-format=" +
6113bdd1243dSDimitry Andric         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
6114bdd1243dSDimitry Andric     CmdArgs.push_back(
6115bdd1243dSDimitry Andric         Args.MakeArgString("-header-include-filtering=" +
6116bdd1243dSDimitry Andric                            std::string(headerIncludeFilteringKindToString(
6117bdd1243dSDimitry Andric                                D.CCPrintHeadersFiltering))));
61180b57cec5SDimitry Andric   }
61190b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_P);
61200b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
61210b57cec5SDimitry Andric 
61220b57cec5SDimitry Andric   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
61230b57cec5SDimitry Andric     CmdArgs.push_back("-diagnostic-log-file");
6124fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6125fe6060f1SDimitry Andric                           ? D.CCLogDiagnosticsFilename.c_str()
61260b57cec5SDimitry Andric                           : "-");
61270b57cec5SDimitry Andric   }
61280b57cec5SDimitry Andric 
612913138422SDimitry Andric   // Give the gen diagnostics more chances to succeed, by avoiding intentional
613013138422SDimitry Andric   // crashes.
613113138422SDimitry Andric   if (D.CCGenDiagnostics)
613213138422SDimitry Andric     CmdArgs.push_back("-disable-pragma-debug-crash");
613313138422SDimitry Andric 
6134fe6060f1SDimitry Andric   // Allow backend to put its diagnostic files in the same place as frontend
6135fe6060f1SDimitry Andric   // crash diagnostics files.
6136fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6137fe6060f1SDimitry Andric     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6138fe6060f1SDimitry Andric     CmdArgs.push_back("-mllvm");
6139fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6140fe6060f1SDimitry Andric   }
6141fe6060f1SDimitry Andric 
61420b57cec5SDimitry Andric   bool UseSeparateSections = isUseSeparateSections(Triple);
61430b57cec5SDimitry Andric 
61440b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_ffunction_sections,
61450b57cec5SDimitry Andric                    options::OPT_fno_function_sections, UseSeparateSections)) {
61460b57cec5SDimitry Andric     CmdArgs.push_back("-ffunction-sections");
61470b57cec5SDimitry Andric   }
61480b57cec5SDimitry Andric 
61490fca6ea1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
61500fca6ea1SDimitry Andric                                options::OPT_fno_basic_block_address_map)) {
61510fca6ea1SDimitry Andric     if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
61520fca6ea1SDimitry Andric       if (A->getOption().matches(options::OPT_fbasic_block_address_map))
61530fca6ea1SDimitry Andric         A->render(Args, CmdArgs);
61540fca6ea1SDimitry Andric     } else {
61550fca6ea1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
61560fca6ea1SDimitry Andric           << A->getAsString(Args) << TripleStr;
61570fca6ea1SDimitry Andric     }
61580fca6ea1SDimitry Andric   }
61590fca6ea1SDimitry Andric 
61605ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
61615ffd83dbSDimitry Andric     StringRef Val = A->getValue();
6162fe6060f1SDimitry Andric     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
61635ffd83dbSDimitry Andric       if (Val != "all" && Val != "labels" && Val != "none" &&
61645f757f3fSDimitry Andric           !Val.starts_with("list="))
61655ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
61665ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
61675ffd83dbSDimitry Andric       else
61685ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
61690fca6ea1SDimitry Andric     } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
61700fca6ea1SDimitry Andric       // "all" is not supported on AArch64 since branch relaxation creates new
61710fca6ea1SDimitry Andric       // basic blocks for some cross-section branches.
61720fca6ea1SDimitry Andric       if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
61730fca6ea1SDimitry Andric         D.Diag(diag::err_drv_invalid_value)
61740fca6ea1SDimitry Andric             << A->getAsString(Args) << A->getValue();
61750fca6ea1SDimitry Andric       else
61760fca6ea1SDimitry Andric         A->render(Args, CmdArgs);
6177fe6060f1SDimitry Andric     } else if (Triple.isNVPTX()) {
6178fe6060f1SDimitry Andric       // Do not pass the option to the GPU compilation. We still want it enabled
6179fe6060f1SDimitry Andric       // for the host-side compilation, so seeing it here is not an error.
6180fe6060f1SDimitry Andric     } else if (Val != "none") {
6181fe6060f1SDimitry Andric       // =none is allowed everywhere. It's useful for overriding the option
6182fe6060f1SDimitry Andric       // and is the same as not specifying the option.
6183e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6184e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
6185e8d8bef9SDimitry Andric     }
61865ffd83dbSDimitry Andric   }
61875ffd83dbSDimitry Andric 
6188e8d8bef9SDimitry Andric   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
61890b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
6190e8d8bef9SDimitry Andric                    UseSeparateSections || HasDefaultDataSections)) {
61910b57cec5SDimitry Andric     CmdArgs.push_back("-fdata-sections");
61920b57cec5SDimitry Andric   }
61930b57cec5SDimitry Andric 
619481ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
619581ad6265SDimitry Andric                      options::OPT_fno_unique_section_names);
61960fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
61970fca6ea1SDimitry Andric                     options::OPT_fno_separate_named_sections);
619881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
619981ad6265SDimitry Andric                     options::OPT_fno_unique_internal_linkage_names);
620081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
620181ad6265SDimitry Andric                     options::OPT_fno_unique_basic_block_section_names);
620206c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
620306c3fb27SDimitry Andric                     options::OPT_fno_convergent_functions);
62045ffd83dbSDimitry Andric 
6205e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6206e8d8bef9SDimitry Andric                                options::OPT_fno_split_machine_functions)) {
62075f757f3fSDimitry Andric     if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
62085f757f3fSDimitry Andric       // This codegen pass is only available on x86 and AArch64 ELF targets.
62095f757f3fSDimitry Andric       if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6210e8d8bef9SDimitry Andric         A->render(Args, CmdArgs);
62115f757f3fSDimitry Andric       else
6212e8d8bef9SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6213e8d8bef9SDimitry Andric             << A->getAsString(Args) << TripleStr;
6214e8d8bef9SDimitry Andric     }
6215e8d8bef9SDimitry Andric   }
6216e8d8bef9SDimitry Andric 
62170b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
62180b57cec5SDimitry Andric                   options::OPT_finstrument_functions_after_inlining,
62190b57cec5SDimitry Andric                   options::OPT_finstrument_function_entry_bare);
62200b57cec5SDimitry Andric 
62215ffd83dbSDimitry Andric   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
62225ffd83dbSDimitry Andric   // for sampling, overhead of call arc collection is way too high and there's
62235ffd83dbSDimitry Andric   // no way to collect the output.
62245ffd83dbSDimitry Andric   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
622506c3fb27SDimitry Andric     addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
62260b57cec5SDimitry Andric 
62270b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
62280b57cec5SDimitry Andric 
6229bdd1243dSDimitry Andric   if (getLastProfileSampleUseArg(Args) &&
6230bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fsample_profile_use_profi)) {
6231bdd1243dSDimitry Andric     CmdArgs.push_back("-mllvm");
6232bdd1243dSDimitry Andric     CmdArgs.push_back("-sample-profile-use-profi");
6233bdd1243dSDimitry Andric   }
6234bdd1243dSDimitry Andric 
623581ad6265SDimitry Andric   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
623681ad6265SDimitry Andric   if (RawTriple.isPS() &&
62370b57cec5SDimitry Andric       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
623881ad6265SDimitry Andric     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
623981ad6265SDimitry Andric     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
62400b57cec5SDimitry Andric   }
62410b57cec5SDimitry Andric 
62420b57cec5SDimitry Andric   // Pass options for controlling the default header search paths.
62430b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_nostdinc)) {
62440b57cec5SDimitry Andric     CmdArgs.push_back("-nostdsysteminc");
62450b57cec5SDimitry Andric     CmdArgs.push_back("-nobuiltininc");
62460b57cec5SDimitry Andric   } else {
62470b57cec5SDimitry Andric     if (Args.hasArg(options::OPT_nostdlibinc))
62480b57cec5SDimitry Andric       CmdArgs.push_back("-nostdsysteminc");
62490b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
62500b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
62510b57cec5SDimitry Andric   }
62520b57cec5SDimitry Andric 
62530b57cec5SDimitry Andric   // Pass the path to compiler resource files.
62540b57cec5SDimitry Andric   CmdArgs.push_back("-resource-dir");
62550b57cec5SDimitry Andric   CmdArgs.push_back(D.ResourceDir.c_str());
62560b57cec5SDimitry Andric 
62570b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
62580b57cec5SDimitry Andric 
62590b57cec5SDimitry Andric   RenderARCMigrateToolOptions(D, Args, CmdArgs);
62600b57cec5SDimitry Andric 
62610b57cec5SDimitry Andric   // Add preprocessing options like -I, -D, etc. if we are using the
62620b57cec5SDimitry Andric   // preprocessor.
62630b57cec5SDimitry Andric   //
62640b57cec5SDimitry Andric   // FIXME: Support -fpreprocessed
62650b57cec5SDimitry Andric   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
62660b57cec5SDimitry Andric     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
62670b57cec5SDimitry Andric 
62680b57cec5SDimitry Andric   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
62690b57cec5SDimitry Andric   // that "The compiler can only warn and ignore the option if not recognized".
62700b57cec5SDimitry Andric   // When building with ccache, it will pass -D options to clang even on
62710b57cec5SDimitry Andric   // preprocessed inputs and configure concludes that -fPIC is not supported.
62720b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_D);
62730b57cec5SDimitry Andric 
62740b57cec5SDimitry Andric   // Manually translate -O4 to -O3; let clang reject others.
62750b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
62760b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4)) {
62770b57cec5SDimitry Andric       CmdArgs.push_back("-O3");
62780b57cec5SDimitry Andric       D.Diag(diag::warn_O4_is_O3);
62790b57cec5SDimitry Andric     } else {
62800b57cec5SDimitry Andric       A->render(Args, CmdArgs);
62810b57cec5SDimitry Andric     }
62820b57cec5SDimitry Andric   }
62830b57cec5SDimitry Andric 
62840b57cec5SDimitry Andric   // Warn about ignored options to clang.
62850b57cec5SDimitry Andric   for (const Arg *A :
62860b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
62870b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
62880b57cec5SDimitry Andric     A->claim();
62890b57cec5SDimitry Andric   }
62900b57cec5SDimitry Andric 
62910b57cec5SDimitry Andric   for (const Arg *A :
62920b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
62930b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
62940b57cec5SDimitry Andric     A->claim();
62950b57cec5SDimitry Andric   }
62960b57cec5SDimitry Andric 
62970b57cec5SDimitry Andric   claimNoWarnArgs(Args);
62980b57cec5SDimitry Andric 
62990b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
63000b57cec5SDimitry Andric 
6301349cc55cSDimitry Andric   for (const Arg *A :
6302349cc55cSDimitry Andric        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6303349cc55cSDimitry Andric     A->claim();
6304349cc55cSDimitry Andric     if (A->getOption().getID() == options::OPT__SLASH_wd) {
6305349cc55cSDimitry Andric       unsigned WarningNumber;
6306349cc55cSDimitry Andric       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6307349cc55cSDimitry Andric         D.Diag(diag::err_drv_invalid_int_value)
6308349cc55cSDimitry Andric             << A->getAsString(Args) << A->getValue();
6309349cc55cSDimitry Andric         continue;
6310349cc55cSDimitry Andric       }
6311349cc55cSDimitry Andric 
6312349cc55cSDimitry Andric       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6313349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
6314349cc55cSDimitry Andric             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6315349cc55cSDimitry Andric       }
6316349cc55cSDimitry Andric       continue;
6317349cc55cSDimitry Andric     }
6318349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6319349cc55cSDimitry Andric   }
6320349cc55cSDimitry Andric 
63215f757f3fSDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
63225f757f3fSDimitry Andric 
63230b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
63240b57cec5SDimitry Andric     CmdArgs.push_back("-pedantic");
63250b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
63260b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_w);
63270b57cec5SDimitry Andric 
6328bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6329bdd1243dSDimitry Andric                     options::OPT_fno_fixed_point);
63300b57cec5SDimitry Andric 
6331fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6332fe6060f1SDimitry Andric     A->render(Args, CmdArgs);
6333fe6060f1SDimitry Andric 
6334fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6335fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
6336fe6060f1SDimitry Andric 
63375f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
63385f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
63395f757f3fSDimitry Andric 
6340349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6341349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6342349cc55cSDimitry Andric 
63430b57cec5SDimitry Andric   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
63440b57cec5SDimitry Andric   // (-ansi is equivalent to -std=c89 or -std=c++98).
63450b57cec5SDimitry Andric   //
63460b57cec5SDimitry Andric   // If a std is supplied, only add -trigraphs if it follows the
63470b57cec5SDimitry Andric   // option.
6348fe6060f1SDimitry Andric   bool ImplyVCPPCVer = false;
63490b57cec5SDimitry Andric   bool ImplyVCPPCXXVer = false;
63500b57cec5SDimitry Andric   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
63510b57cec5SDimitry Andric   if (Std) {
63520b57cec5SDimitry Andric     if (Std->getOption().matches(options::OPT_ansi))
63530b57cec5SDimitry Andric       if (types::isCXX(InputType))
63540b57cec5SDimitry Andric         CmdArgs.push_back("-std=c++98");
63550b57cec5SDimitry Andric       else
63560b57cec5SDimitry Andric         CmdArgs.push_back("-std=c89");
63570b57cec5SDimitry Andric     else
63580b57cec5SDimitry Andric       Std->render(Args, CmdArgs);
63590b57cec5SDimitry Andric 
63600b57cec5SDimitry Andric     // If -f(no-)trigraphs appears after the language standard flag, honor it.
63610b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
63620b57cec5SDimitry Andric                                  options::OPT_ftrigraphs,
63630b57cec5SDimitry Andric                                  options::OPT_fno_trigraphs))
63640b57cec5SDimitry Andric       if (A != Std)
63650b57cec5SDimitry Andric         A->render(Args, CmdArgs);
63660b57cec5SDimitry Andric   } else {
63670b57cec5SDimitry Andric     // Honor -std-default.
63680b57cec5SDimitry Andric     //
63690b57cec5SDimitry Andric     // FIXME: Clang doesn't correctly handle -std= when the input language
63700b57cec5SDimitry Andric     // doesn't match. For the time being just ignore this for C++ inputs;
63710b57cec5SDimitry Andric     // eventually we want to do all the standard defaulting here instead of
63720b57cec5SDimitry Andric     // splitting it between the driver and clang -cc1.
6373fe6060f1SDimitry Andric     if (!types::isCXX(InputType)) {
6374fe6060f1SDimitry Andric       if (!Args.hasArg(options::OPT__SLASH_std)) {
63750b57cec5SDimitry Andric         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
63760b57cec5SDimitry Andric                                   /*Joined=*/true);
6377fe6060f1SDimitry Andric       } else
6378fe6060f1SDimitry Andric         ImplyVCPPCVer = true;
6379fe6060f1SDimitry Andric     }
63800b57cec5SDimitry Andric     else if (IsWindowsMSVC)
63810b57cec5SDimitry Andric       ImplyVCPPCXXVer = true;
63820b57cec5SDimitry Andric 
63830b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
63840b57cec5SDimitry Andric                     options::OPT_fno_trigraphs);
63850b57cec5SDimitry Andric   }
63860b57cec5SDimitry Andric 
63870b57cec5SDimitry Andric   // GCC's behavior for -Wwrite-strings is a bit strange:
63880b57cec5SDimitry Andric   //  * In C, this "warning flag" changes the types of string literals from
63890b57cec5SDimitry Andric   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
63900b57cec5SDimitry Andric   //    for the discarded qualifier.
63910b57cec5SDimitry Andric   //  * In C++, this is just a normal warning flag.
63920b57cec5SDimitry Andric   //
63930b57cec5SDimitry Andric   // Implementing this warning correctly in C is hard, so we follow GCC's
63940b57cec5SDimitry Andric   // behavior for now. FIXME: Directly diagnose uses of a string literal as
63950b57cec5SDimitry Andric   // a non-const char* in C, rather than using this crude hack.
63960b57cec5SDimitry Andric   if (!types::isCXX(InputType)) {
63970b57cec5SDimitry Andric     // FIXME: This should behave just like a warning flag, and thus should also
63980b57cec5SDimitry Andric     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
63990b57cec5SDimitry Andric     Arg *WriteStrings =
64000b57cec5SDimitry Andric         Args.getLastArg(options::OPT_Wwrite_strings,
64010b57cec5SDimitry Andric                         options::OPT_Wno_write_strings, options::OPT_w);
64020b57cec5SDimitry Andric     if (WriteStrings &&
64030b57cec5SDimitry Andric         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
64040b57cec5SDimitry Andric       CmdArgs.push_back("-fconst-strings");
64050b57cec5SDimitry Andric   }
64060b57cec5SDimitry Andric 
64070b57cec5SDimitry Andric   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
64080b57cec5SDimitry Andric   // during C++ compilation, which it is by default. GCC keeps this define even
64090b57cec5SDimitry Andric   // in the presence of '-w', match this behavior bug-for-bug.
64100b57cec5SDimitry Andric   if (types::isCXX(InputType) &&
64110b57cec5SDimitry Andric       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
64120b57cec5SDimitry Andric                    true)) {
64130b57cec5SDimitry Andric     CmdArgs.push_back("-fdeprecated-macro");
64140b57cec5SDimitry Andric   }
64150b57cec5SDimitry Andric 
64160b57cec5SDimitry Andric   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
64170b57cec5SDimitry Andric   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
64180b57cec5SDimitry Andric     if (Asm->getOption().matches(options::OPT_fasm))
64190b57cec5SDimitry Andric       CmdArgs.push_back("-fgnu-keywords");
64200b57cec5SDimitry Andric     else
64210b57cec5SDimitry Andric       CmdArgs.push_back("-fno-gnu-keywords");
64220b57cec5SDimitry Andric   }
64230b57cec5SDimitry Andric 
6424480093f4SDimitry Andric   if (!ShouldEnableAutolink(Args, TC, JA))
64250b57cec5SDimitry Andric     CmdArgs.push_back("-fno-autolink");
64260b57cec5SDimitry Andric 
642706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
642806c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
642906c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
643006c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
64310b57cec5SDimitry Andric 
6432fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
643381ad6265SDimitry Andric 
6434a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6435a7dea167SDimitry Andric     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6436a7dea167SDimitry Andric 
64370b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
64380b57cec5SDimitry Andric     CmdArgs.push_back("-fbracket-depth");
64390b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
64400b57cec5SDimitry Andric   }
64410b57cec5SDimitry Andric 
64420b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
64430b57cec5SDimitry Andric                                options::OPT_Wlarge_by_value_copy_def)) {
64440b57cec5SDimitry Andric     if (A->getNumValues()) {
64450b57cec5SDimitry Andric       StringRef bytes = A->getValue();
64460b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
64470b57cec5SDimitry Andric     } else
64480b57cec5SDimitry Andric       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
64490b57cec5SDimitry Andric   }
64500b57cec5SDimitry Andric 
64510b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_relocatable_pch))
64520b57cec5SDimitry Andric     CmdArgs.push_back("-relocatable-pch");
64530b57cec5SDimitry Andric 
64540b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
64550b57cec5SDimitry Andric     static const char *kCFABIs[] = {
64560b57cec5SDimitry Andric       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
64570b57cec5SDimitry Andric     };
64580b57cec5SDimitry Andric 
645981ad6265SDimitry Andric     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
64600b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
64610b57cec5SDimitry Andric     else
64620b57cec5SDimitry Andric       A->render(Args, CmdArgs);
64630b57cec5SDimitry Andric   }
64640b57cec5SDimitry Andric 
64650b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
64660b57cec5SDimitry Andric     CmdArgs.push_back("-fconstant-string-class");
64670b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
64680b57cec5SDimitry Andric   }
64690b57cec5SDimitry Andric 
64700b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
64710b57cec5SDimitry Andric     CmdArgs.push_back("-ftabstop");
64720b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
64730b57cec5SDimitry Andric   }
64740b57cec5SDimitry Andric 
6475bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6476bdd1243dSDimitry Andric                     options::OPT_fno_stack_size_section);
64770b57cec5SDimitry Andric 
6478fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fstack_usage)) {
6479fe6060f1SDimitry Andric     CmdArgs.push_back("-stack-usage-file");
6480fe6060f1SDimitry Andric 
6481fe6060f1SDimitry Andric     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6482fe6060f1SDimitry Andric       SmallString<128> OutputFilename(OutputOpt->getValue());
6483fe6060f1SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "su");
6484fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6485fe6060f1SDimitry Andric     } else
6486fe6060f1SDimitry Andric       CmdArgs.push_back(
6487fe6060f1SDimitry Andric           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6488fe6060f1SDimitry Andric   }
6489fe6060f1SDimitry Andric 
64900b57cec5SDimitry Andric   CmdArgs.push_back("-ferror-limit");
64910b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
64920b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
64930b57cec5SDimitry Andric   else
64940b57cec5SDimitry Andric     CmdArgs.push_back("19");
64950b57cec5SDimitry Andric 
649606c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
649706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
649806c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
649906c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
650006c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
65010b57cec5SDimitry Andric 
65020b57cec5SDimitry Andric   // Pass -fmessage-length=.
65035ffd83dbSDimitry Andric   unsigned MessageLength = 0;
65040b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
65055ffd83dbSDimitry Andric     StringRef V(A->getValue());
65065ffd83dbSDimitry Andric     if (V.getAsInteger(0, MessageLength))
65075ffd83dbSDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
65085ffd83dbSDimitry Andric           << V << A->getOption().getName();
65090b57cec5SDimitry Andric   } else {
65100b57cec5SDimitry Andric     // If -fmessage-length=N was not specified, determine whether this is a
65110b57cec5SDimitry Andric     // terminal and, if so, implicitly define -fmessage-length appropriately.
65125ffd83dbSDimitry Andric     MessageLength = llvm::sys::Process::StandardErrColumns();
65130b57cec5SDimitry Andric   }
65145ffd83dbSDimitry Andric   if (MessageLength != 0)
65155ffd83dbSDimitry Andric     CmdArgs.push_back(
65165ffd83dbSDimitry Andric         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
65170b57cec5SDimitry Andric 
651881ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
651981ad6265SDimitry Andric     CmdArgs.push_back(
652081ad6265SDimitry Andric         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
652181ad6265SDimitry Andric 
652281ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
652381ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
652481ad6265SDimitry Andric                                          Twine(A->getValue(0))));
652581ad6265SDimitry Andric 
65260b57cec5SDimitry Andric   // -fvisibility= and -fvisibility-ms-compat are of a piece.
65270b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
65280b57cec5SDimitry Andric                                      options::OPT_fvisibility_ms_compat)) {
65290b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6530bdd1243dSDimitry Andric       A->render(Args, CmdArgs);
65310b57cec5SDimitry Andric     } else {
65320b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6533bdd1243dSDimitry Andric       CmdArgs.push_back("-fvisibility=hidden");
6534bdd1243dSDimitry Andric       CmdArgs.push_back("-ftype-visibility=default");
65350b57cec5SDimitry Andric     }
653604eeddc0SDimitry Andric   } else if (IsOpenMPDevice) {
653704eeddc0SDimitry Andric     // When compiling for the OpenMP device we want protected visibility by
6538bdd1243dSDimitry Andric     // default. This prevents the device from accidentally preempting code on
6539bdd1243dSDimitry Andric     // the host, makes the system more robust, and improves performance.
6540bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=protected");
65410b57cec5SDimitry Andric   }
65420b57cec5SDimitry Andric 
6543bdd1243dSDimitry Andric   // PS4/PS5 process these options in addClangTargetOptions.
6544bdd1243dSDimitry Andric   if (!RawTriple.isPS()) {
6545e8d8bef9SDimitry Andric     if (const Arg *A =
6546e8d8bef9SDimitry Andric             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6547e8d8bef9SDimitry Andric                             options::OPT_fno_visibility_from_dllstorageclass)) {
6548e8d8bef9SDimitry Andric       if (A->getOption().matches(
6549e8d8bef9SDimitry Andric               options::OPT_fvisibility_from_dllstorageclass)) {
6550e8d8bef9SDimitry Andric         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6551e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6552e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6553e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6554e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs,
6555e8d8bef9SDimitry Andric                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6556e8d8bef9SDimitry Andric       }
6557e8d8bef9SDimitry Andric     }
6558bdd1243dSDimitry Andric   }
6559e8d8bef9SDimitry Andric 
6560fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6561fe6060f1SDimitry Andric                     options::OPT_fno_visibility_inlines_hidden, false))
6562fe6060f1SDimitry Andric     CmdArgs.push_back("-fvisibility-inlines-hidden");
6563fe6060f1SDimitry Andric 
6564e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6565e8d8bef9SDimitry Andric                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
65667a6dacacSDimitry Andric 
65677a6dacacSDimitry Andric   // -fvisibility-global-new-delete-hidden is a deprecated spelling of
65687a6dacacSDimitry Andric   // -fvisibility-global-new-delete=force-hidden.
65697a6dacacSDimitry Andric   if (const Arg *A =
65707a6dacacSDimitry Andric           Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
65717a6dacacSDimitry Andric     D.Diag(diag::warn_drv_deprecated_arg)
65720fca6ea1SDimitry Andric         << A->getAsString(Args) << /*hasReplacement=*/true
65737a6dacacSDimitry Andric         << "-fvisibility-global-new-delete=force-hidden";
65747a6dacacSDimitry Andric   }
65757a6dacacSDimitry Andric 
65767a6dacacSDimitry Andric   if (const Arg *A =
65777a6dacacSDimitry Andric           Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
65787a6dacacSDimitry Andric                           options::OPT_fvisibility_global_new_delete_hidden)) {
65797a6dacacSDimitry Andric     if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
65807a6dacacSDimitry Andric       A->render(Args, CmdArgs);
65817a6dacacSDimitry Andric     } else {
65827a6dacacSDimitry Andric       assert(A->getOption().matches(
65837a6dacacSDimitry Andric           options::OPT_fvisibility_global_new_delete_hidden));
65847a6dacacSDimitry Andric       CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
65857a6dacacSDimitry Andric     }
65867a6dacacSDimitry Andric   }
65877a6dacacSDimitry Andric 
65880b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
65890b57cec5SDimitry Andric 
65904824e7fdSDimitry Andric   if (Args.hasFlag(options::OPT_fnew_infallible,
65914824e7fdSDimitry Andric                    options::OPT_fno_new_infallible, false))
65924824e7fdSDimitry Andric     CmdArgs.push_back("-fnew-infallible");
65934824e7fdSDimitry Andric 
6594fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fno_operator_names,
6595fe6060f1SDimitry Andric                    options::OPT_foperator_names, false))
6596fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-operator-names");
6597fe6060f1SDimitry Andric 
65980b57cec5SDimitry Andric   // Forward -f (flag) options which we can pass directly.
65990b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
66000b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
66010b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
660281ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
66030fca6ea1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
66040fca6ea1SDimitry Andric                   options::OPT_fno_raw_string_literals);
660581ad6265SDimitry Andric 
660606c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
660706c3fb27SDimitry Andric                    Triple.hasDefaultEmulatedTLS()))
660806c3fb27SDimitry Andric     CmdArgs.push_back("-femulated-tls");
660906c3fb27SDimitry Andric 
661006c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
661106c3fb27SDimitry Andric                     options::OPT_fno_check_new);
661206c3fb27SDimitry Andric 
661381ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
661481ad6265SDimitry Andric     // FIXME: There's no reason for this to be restricted to X86. The backend
661581ad6265SDimitry Andric     // code needs to be changed to include the appropriate function calls
661681ad6265SDimitry Andric     // automatically.
661781ad6265SDimitry Andric     if (!Triple.isX86() && !Triple.isAArch64())
661881ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
661981ad6265SDimitry Andric           << A->getAsString(Args) << TripleStr;
662081ad6265SDimitry Andric   }
66210b57cec5SDimitry Andric 
66220b57cec5SDimitry Andric   // AltiVec-like language extensions aren't relevant for assembling.
66230b57cec5SDimitry Andric   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
66240b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
66250b57cec5SDimitry Andric 
66260b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
66270b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
66280b57cec5SDimitry Andric 
66290b57cec5SDimitry Andric   // Forward flags for OpenMP. We don't do this if the current action is an
66300b57cec5SDimitry Andric   // device offloading action other than OpenMP.
66310b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
66320b57cec5SDimitry Andric                    options::OPT_fno_openmp, false) &&
66330b57cec5SDimitry Andric       (JA.isDeviceOffloading(Action::OFK_None) ||
66340b57cec5SDimitry Andric        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
66350b57cec5SDimitry Andric     switch (D.getOpenMPRuntime(Args)) {
66360b57cec5SDimitry Andric     case Driver::OMPRT_OMP:
66370b57cec5SDimitry Andric     case Driver::OMPRT_IOMP5:
66380b57cec5SDimitry Andric       // Clang can generate useful OpenMP code for these two runtime libraries.
66390b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp");
66400b57cec5SDimitry Andric 
66410b57cec5SDimitry Andric       // If no option regarding the use of TLS in OpenMP codegeneration is
66420b57cec5SDimitry Andric       // given, decide a default based on the target. Otherwise rely on the
66430b57cec5SDimitry Andric       // options and pass the right information to the frontend.
66440b57cec5SDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
66450b57cec5SDimitry Andric                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
66460b57cec5SDimitry Andric         CmdArgs.push_back("-fnoopenmp-use-tls");
66470b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
66480b57cec5SDimitry Andric                       options::OPT_fno_openmp_simd);
6649480093f4SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
66500b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6651349cc55cSDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6652349cc55cSDimitry Andric                         options::OPT_fno_openmp_extensions, /*Default=*/true))
6653349cc55cSDimitry Andric         CmdArgs.push_back("-fno-openmp-extensions");
66540b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
66550b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
66560b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs,
66570b57cec5SDimitry Andric                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
66580b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
66590b57cec5SDimitry Andric                        options::OPT_fno_openmp_optimistic_collapse,
66600b57cec5SDimitry Andric                        /*Default=*/false))
66610b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-optimistic-collapse");
66620b57cec5SDimitry Andric 
66630b57cec5SDimitry Andric       // When in OpenMP offloading mode with NVPTX target, forward
66640b57cec5SDimitry Andric       // cuda-mode flag
66650b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
66660b57cec5SDimitry Andric                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
66670b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-cuda-mode");
66680b57cec5SDimitry Andric 
6669349cc55cSDimitry Andric       // When in OpenMP offloading mode, enable debugging on the device.
6670349cc55cSDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6671349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6672349cc55cSDimitry Andric                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6673349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-target-debug");
6674349cc55cSDimitry Andric 
6675349cc55cSDimitry Andric       // When in OpenMP offloading mode, forward assumptions information about
6676349cc55cSDimitry Andric       // thread and team counts in the device.
6677349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6678349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_teams_oversubscription,
6679349cc55cSDimitry Andric                        /*Default=*/false))
6680349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6681349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6682349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_threads_oversubscription,
6683349cc55cSDimitry Andric                        /*Default=*/false))
6684349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
668581ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
668681ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6687bdd1243dSDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6688bdd1243dSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
668981ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
669081ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-offload-mandatory");
66917a6dacacSDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_force_usm))
66927a6dacacSDimitry Andric         CmdArgs.push_back("-fopenmp-force-usm");
66930b57cec5SDimitry Andric       break;
66940b57cec5SDimitry Andric     default:
66950b57cec5SDimitry Andric       // By default, if Clang doesn't know how to generate useful OpenMP code
66960b57cec5SDimitry Andric       // for a specific runtime library, we just don't pass the '-fopenmp' flag
66970b57cec5SDimitry Andric       // down to the actual compilation.
66980b57cec5SDimitry Andric       // FIXME: It would be better to have a mode which *only* omits IR
66990b57cec5SDimitry Andric       // generation based on the OpenMP support so that we get consistent
67000b57cec5SDimitry Andric       // semantic analysis, etc.
67010b57cec5SDimitry Andric       break;
67020b57cec5SDimitry Andric     }
67030b57cec5SDimitry Andric   } else {
67040b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
67050b57cec5SDimitry Andric                     options::OPT_fno_openmp_simd);
67060b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
670781ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
670881ad6265SDimitry Andric                        options::OPT_fno_openmp_extensions);
67090b57cec5SDimitry Andric   }
67100b57cec5SDimitry Andric 
671181ad6265SDimitry Andric   // Forward the new driver to change offloading code generation.
6712bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_offload_new_driver,
6713bdd1243dSDimitry Andric                    options::OPT_no_offload_new_driver, false))
671481ad6265SDimitry Andric     CmdArgs.push_back("--offload-new-driver");
671581ad6265SDimitry Andric 
6716349cc55cSDimitry Andric   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
67170b57cec5SDimitry Andric 
67180b57cec5SDimitry Andric   const XRayArgs &XRay = TC.getXRayArgs();
67190b57cec5SDimitry Andric   XRay.addArgs(TC, Args, CmdArgs, InputType);
67200b57cec5SDimitry Andric 
6721e8d8bef9SDimitry Andric   for (const auto &Filename :
6722e8d8bef9SDimitry Andric        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6723e8d8bef9SDimitry Andric     if (D.getVFS().exists(Filename))
6724e8d8bef9SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6725e8d8bef9SDimitry Andric     else
6726e8d8bef9SDimitry Andric       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6727e8d8bef9SDimitry Andric   }
6728e8d8bef9SDimitry Andric 
6729480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6730480093f4SDimitry Andric     StringRef S0 = A->getValue(), S = S0;
673155e4f9d5SDimitry Andric     unsigned Size, Offset = 0;
673206c3fb27SDimitry Andric     if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
67330fca6ea1SDimitry Andric         !Triple.isX86() &&
67340fca6ea1SDimitry Andric         !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
67350fca6ea1SDimitry Andric                                 Triple.getArch() == llvm::Triple::ppc64)))
6736480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6737480093f4SDimitry Andric           << A->getAsString(Args) << TripleStr;
6738480093f4SDimitry Andric     else if (S.consumeInteger(10, Size) ||
6739480093f4SDimitry Andric              (!S.empty() && (!S.consume_front(",") ||
674055e4f9d5SDimitry Andric                              S.consumeInteger(10, Offset) || !S.empty())))
6741480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
6742480093f4SDimitry Andric           << S0 << A->getOption().getName();
674355e4f9d5SDimitry Andric     else if (Size < Offset)
6744480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
674555e4f9d5SDimitry Andric     else {
6746480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
674755e4f9d5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
674855e4f9d5SDimitry Andric           "-fpatchable-function-entry-offset=" + Twine(Offset)));
674955e4f9d5SDimitry Andric     }
6750480093f4SDimitry Andric   }
6751480093f4SDimitry Andric 
675204eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
675304eeddc0SDimitry Andric 
6754480093f4SDimitry Andric   if (TC.SupportsProfiling()) {
67550b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_pg);
67560b57cec5SDimitry Andric 
6757480093f4SDimitry Andric     llvm::Triple::ArchType Arch = TC.getArch();
6758480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6759480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6760480093f4SDimitry Andric         A->render(Args, CmdArgs);
6761480093f4SDimitry Andric       else
6762480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6763480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6764480093f4SDimitry Andric     }
6765480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6766480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6767480093f4SDimitry Andric         A->render(Args, CmdArgs);
6768480093f4SDimitry Andric       else
6769480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6770480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6771480093f4SDimitry Andric     }
6772480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6773480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6774480093f4SDimitry Andric         A->render(Args, CmdArgs);
6775480093f4SDimitry Andric       else
6776480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6777480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6778480093f4SDimitry Andric     }
6779480093f4SDimitry Andric   }
678006c3fb27SDimitry Andric 
678106c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
678206c3fb27SDimitry Andric     if (TC.getTriple().isOSzOS()) {
6783bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6784bdd1243dSDimitry Andric           << A->getAsString(Args) << TripleStr;
6785bdd1243dSDimitry Andric     }
6786bdd1243dSDimitry Andric   }
678706c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
678806c3fb27SDimitry Andric     if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
678906c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
679006c3fb27SDimitry Andric           << A->getAsString(Args) << TripleStr;
679106c3fb27SDimitry Andric     }
679206c3fb27SDimitry Andric   }
679306c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
679406c3fb27SDimitry Andric     if (A->getOption().matches(options::OPT_p)) {
679506c3fb27SDimitry Andric       A->claim();
679606c3fb27SDimitry Andric       if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
679706c3fb27SDimitry Andric         CmdArgs.push_back("-pg");
679806c3fb27SDimitry Andric     }
679906c3fb27SDimitry Andric   }
680006c3fb27SDimitry Andric 
680106c3fb27SDimitry Andric   // Reject AIX-specific link options on other targets.
680206c3fb27SDimitry Andric   if (!TC.getTriple().isOSAIX()) {
680306c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
680406c3fb27SDimitry Andric                                       options::OPT_mxcoff_build_id_EQ)) {
680506c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
680606c3fb27SDimitry Andric           << A->getSpelling() << TripleStr;
680706c3fb27SDimitry Andric     }
680806c3fb27SDimitry Andric   }
68090b57cec5SDimitry Andric 
68100b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_fapple_kext) ||
68110b57cec5SDimitry Andric       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
68120b57cec5SDimitry Andric     CmdArgs.push_back("-fapple-kext");
68130b57cec5SDimitry Andric 
6814fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6815a7dea167SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
68160b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
68170b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
68180b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
68190b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6820e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
68210b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
68220b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6823480093f4SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
68240b57cec5SDimitry Andric 
682506c3fb27SDimitry Andric   if (const char *Name = C.getTimeTraceFile(&JA)) {
682606c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
682706c3fb27SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
68280fca6ea1SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
682906c3fb27SDimitry Andric   }
683006c3fb27SDimitry Andric 
68310b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
68320b57cec5SDimitry Andric     CmdArgs.push_back("-ftrapv-handler");
68330b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
68340b57cec5SDimitry Andric   }
68350b57cec5SDimitry Andric 
68360b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
68370b57cec5SDimitry Andric 
68380b57cec5SDimitry Andric   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
68390b57cec5SDimitry Andric   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
68400b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
68410b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fwrapv))
68420b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
68430b57cec5SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
68440b57cec5SDimitry Andric                                       options::OPT_fno_strict_overflow)) {
68450b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_strict_overflow))
68460b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
68470b57cec5SDimitry Andric   }
68480b57cec5SDimitry Andric 
6849d409305fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6850d409305fSDimitry Andric                   options::OPT_fno_finite_loops);
6851d409305fSDimitry Andric 
68520b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
68530b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
68540b57cec5SDimitry Andric                   options::OPT_fno_unroll_loops);
68550b57cec5SDimitry Andric 
6856fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6857fcaf7f86SDimitry Andric 
68580b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pthread);
68590b57cec5SDimitry Andric 
6860bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6861bdd1243dSDimitry Andric                     options::OPT_mno_speculative_load_hardening);
68620b57cec5SDimitry Andric 
6863e8d8bef9SDimitry Andric   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
68645ffd83dbSDimitry Andric   RenderSCPOptions(TC, Args, CmdArgs);
68650b57cec5SDimitry Andric   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
68660b57cec5SDimitry Andric 
6867349cc55cSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6868349cc55cSDimitry Andric 
6869bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6870bdd1243dSDimitry Andric                     options::OPT_mno_stackrealign);
68710b57cec5SDimitry Andric 
68720b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_alignment)) {
68730b57cec5SDimitry Andric     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
68740b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
68750b57cec5SDimitry Andric   }
68760b57cec5SDimitry Andric 
68770b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_probe_size)) {
68780b57cec5SDimitry Andric     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
68790b57cec5SDimitry Andric 
68800b57cec5SDimitry Andric     if (!Size.empty())
68810b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
68820b57cec5SDimitry Andric     else
68830b57cec5SDimitry Andric       CmdArgs.push_back("-mstack-probe-size=0");
68840b57cec5SDimitry Andric   }
68850b57cec5SDimitry Andric 
688681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
688781ad6265SDimitry Andric                      options::OPT_mno_stack_arg_probe);
68880b57cec5SDimitry Andric 
68890b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
68900b57cec5SDimitry Andric                                options::OPT_mno_restrict_it)) {
68910b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mrestrict_it)) {
68920b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
68930b57cec5SDimitry Andric       CmdArgs.push_back("-arm-restrict-it");
68940b57cec5SDimitry Andric     } else {
68950b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
689681ad6265SDimitry Andric       CmdArgs.push_back("-arm-default-it");
68970b57cec5SDimitry Andric     }
68980b57cec5SDimitry Andric   }
68990b57cec5SDimitry Andric 
69000b57cec5SDimitry Andric   // Forward -cl options to -cc1
6901fe6060f1SDimitry Andric   RenderOpenCLOptions(Args, CmdArgs, InputType);
69020b57cec5SDimitry Andric 
690381ad6265SDimitry Andric   // Forward hlsl options to -cc1
690481ad6265SDimitry Andric   RenderHLSLOptions(Args, CmdArgs, InputType);
690581ad6265SDimitry Andric 
69065f757f3fSDimitry Andric   // Forward OpenACC options to -cc1
69075f757f3fSDimitry Andric   RenderOpenACCOptions(D, Args, CmdArgs, InputType);
69085f757f3fSDimitry Andric 
6909e8d8bef9SDimitry Andric   if (IsHIP) {
6910e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
69115ffd83dbSDimitry Andric                      options::OPT_fno_hip_new_launch_api, true))
6912a7dea167SDimitry Andric       CmdArgs.push_back("-fhip-new-launch-api");
69135f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
69145f757f3fSDimitry Andric                       options::OPT_fno_gpu_allow_device_init);
69155f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
69165f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
691781ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
691881ad6265SDimitry Andric                       options::OPT_fno_hip_kernel_arg_name);
6919e8d8bef9SDimitry Andric   }
6920e8d8bef9SDimitry Andric 
6921e8d8bef9SDimitry Andric   if (IsCuda || IsHIP) {
6922753f127fSDimitry Andric     if (IsRDCMode)
6923fe6060f1SDimitry Andric       CmdArgs.push_back("-fgpu-rdc");
69245f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
69255f757f3fSDimitry Andric                       options::OPT_fno_gpu_defer_diag);
6926e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6927e8d8bef9SDimitry Andric                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6928e8d8bef9SDimitry Andric                      false)) {
6929e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6930e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-defer-diag");
6931e8d8bef9SDimitry Andric     }
6932e8d8bef9SDimitry Andric   }
6933a7dea167SDimitry Andric 
693481ad6265SDimitry Andric   // Forward -nogpulib to -cc1.
693581ad6265SDimitry Andric   if (Args.hasArg(options::OPT_nogpulib))
693681ad6265SDimitry Andric     CmdArgs.push_back("-nogpulib");
693781ad6265SDimitry Andric 
69380b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
69390b57cec5SDimitry Andric     CmdArgs.push_back(
69400b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
69410b57cec5SDimitry Andric   }
69420b57cec5SDimitry Andric 
6943753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6944753f127fSDimitry Andric     CmdArgs.push_back(
6945753f127fSDimitry Andric         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6946753f127fSDimitry Andric 
6947bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6948bdd1243dSDimitry Andric 
6949fe6060f1SDimitry Andric   // Forward -f options with positive and negative forms; we translate these by
6950fe6060f1SDimitry Andric   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6951fe6060f1SDimitry Andric   // profile info is for the host-side compilation only.
6952fe6060f1SDimitry Andric   if (!(IsCudaDevice || IsHIPDevice)) {
69530b57cec5SDimitry Andric     if (Arg *A = getLastProfileSampleUseArg(Args)) {
69540b57cec5SDimitry Andric       auto *PGOArg = Args.getLastArg(
69550b57cec5SDimitry Andric           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6956fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate,
6957fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6958fe6060f1SDimitry Andric           options::OPT_fprofile_use_EQ);
69590b57cec5SDimitry Andric       if (PGOArg)
69600b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
69610b57cec5SDimitry Andric             << "SampleUse with PGO options";
69620b57cec5SDimitry Andric 
69630b57cec5SDimitry Andric       StringRef fname = A->getValue();
69640b57cec5SDimitry Andric       if (!llvm::sys::fs::exists(fname))
69650b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << fname;
69660b57cec5SDimitry Andric       else
69670b57cec5SDimitry Andric         A->render(Args, CmdArgs);
69680b57cec5SDimitry Andric     }
69690b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
69700b57cec5SDimitry Andric 
6971e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6972fe6060f1SDimitry Andric                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6973e8d8bef9SDimitry Andric       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6974fe6060f1SDimitry Andric       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6975fe6060f1SDimitry Andric       // off.
6976fe6060f1SDimitry Andric       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6977fe6060f1SDimitry Andric                        options::OPT_fno_unique_internal_linkage_names, true))
6978fe6060f1SDimitry Andric         CmdArgs.push_back("-funique-internal-linkage-names");
6979fe6060f1SDimitry Andric     }
6980fe6060f1SDimitry Andric   }
69810b57cec5SDimitry Andric   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
69820b57cec5SDimitry Andric 
698381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
698481ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
69850b57cec5SDimitry Andric 
69865f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
69875f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes");
69885f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes_modules,
69895f757f3fSDimitry Andric                    options::OPT_fno_apinotes_modules, false))
69905f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes-modules");
69915f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
69925f757f3fSDimitry Andric 
69930b57cec5SDimitry Andric   // -fblocks=0 is default.
69940b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
69950b57cec5SDimitry Andric                    TC.IsBlocksDefault()) ||
69960b57cec5SDimitry Andric       (Args.hasArg(options::OPT_fgnu_runtime) &&
69970b57cec5SDimitry Andric        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
69980b57cec5SDimitry Andric        !Args.hasArg(options::OPT_fno_blocks))) {
69990b57cec5SDimitry Andric     CmdArgs.push_back("-fblocks");
70000b57cec5SDimitry Andric 
70010b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
70020b57cec5SDimitry Andric       CmdArgs.push_back("-fblocks-runtime-optional");
70030b57cec5SDimitry Andric   }
70040b57cec5SDimitry Andric 
70050b57cec5SDimitry Andric   // -fencode-extended-block-signature=1 is default.
70060b57cec5SDimitry Andric   if (TC.IsEncodeExtendedBlockSignatureDefault())
70070b57cec5SDimitry Andric     CmdArgs.push_back("-fencode-extended-block-signature");
70080b57cec5SDimitry Andric 
7009bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7010bdd1243dSDimitry Andric                    options::OPT_fno_coro_aligned_allocation, false) &&
7011bdd1243dSDimitry Andric       types::isCXX(InputType))
7012bdd1243dSDimitry Andric     CmdArgs.push_back("-fcoro-aligned-allocation");
7013bdd1243dSDimitry Andric 
70140b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
70150b57cec5SDimitry Andric                   options::OPT_fno_double_square_bracket_attributes);
70160b57cec5SDimitry Andric 
701781ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
701881ad6265SDimitry Andric                      options::OPT_fno_access_control);
701981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
702081ad6265SDimitry Andric                      options::OPT_fno_elide_constructors);
70210b57cec5SDimitry Andric 
70220b57cec5SDimitry Andric   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
70230b57cec5SDimitry Andric 
70240b57cec5SDimitry Andric   if (KernelOrKext || (types::isCXX(InputType) &&
70250b57cec5SDimitry Andric                        (RTTIMode == ToolChain::RM_Disabled)))
70260b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti");
70270b57cec5SDimitry Andric 
7028e8d8bef9SDimitry Andric   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
70290b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7030e8d8bef9SDimitry Andric                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
70310b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
70320b57cec5SDimitry Andric 
70330b57cec5SDimitry Andric   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
70340b57cec5SDimitry Andric 
70350b57cec5SDimitry Andric   // -fuse-cxa-atexit is default.
70360b57cec5SDimitry Andric   if (!Args.hasFlag(
70370b57cec5SDimitry Andric           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
70385ffd83dbSDimitry Andric           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
70390b57cec5SDimitry Andric               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
70400b57cec5SDimitry Andric                RawTriple.hasEnvironment())) ||
70410b57cec5SDimitry Andric       KernelOrKext)
70420b57cec5SDimitry Andric     CmdArgs.push_back("-fno-use-cxa-atexit");
70430b57cec5SDimitry Andric 
70440b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
70450b57cec5SDimitry Andric                    options::OPT_fno_register_global_dtors_with_atexit,
70460b57cec5SDimitry Andric                    RawTriple.isOSDarwin() && !KernelOrKext))
70470b57cec5SDimitry Andric     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
70480b57cec5SDimitry Andric 
704981ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
705081ad6265SDimitry Andric                     options::OPT_fno_use_line_directives);
70510b57cec5SDimitry Andric 
7052349cc55cSDimitry Andric   // -fno-minimize-whitespace is default.
7053349cc55cSDimitry Andric   if (Args.hasFlag(options::OPT_fminimize_whitespace,
7054349cc55cSDimitry Andric                    options::OPT_fno_minimize_whitespace, false)) {
7055349cc55cSDimitry Andric     types::ID InputType = Inputs[0].getType();
7056349cc55cSDimitry Andric     if (!isDerivedFromC(InputType))
70575f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
70585f757f3fSDimitry Andric           << "-fminimize-whitespace" << types::getTypeName(InputType);
7059349cc55cSDimitry Andric     CmdArgs.push_back("-fminimize-whitespace");
7060349cc55cSDimitry Andric   }
7061349cc55cSDimitry Andric 
70625f757f3fSDimitry Andric   // -fno-keep-system-includes is default.
70635f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fkeep_system_includes,
70645f757f3fSDimitry Andric                    options::OPT_fno_keep_system_includes, false)) {
70655f757f3fSDimitry Andric     types::ID InputType = Inputs[0].getType();
70665f757f3fSDimitry Andric     if (!isDerivedFromC(InputType))
70675f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
70685f757f3fSDimitry Andric           << "-fkeep-system-includes" << types::getTypeName(InputType);
70695f757f3fSDimitry Andric     CmdArgs.push_back("-fkeep-system-includes");
70705f757f3fSDimitry Andric   }
70715f757f3fSDimitry Andric 
70725ffd83dbSDimitry Andric   // -fms-extensions=0 is default.
70735ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
70745ffd83dbSDimitry Andric                    IsWindowsMSVC))
70755ffd83dbSDimitry Andric     CmdArgs.push_back("-fms-extensions");
70765ffd83dbSDimitry Andric 
70770b57cec5SDimitry Andric   // -fms-compatibility=0 is default.
7078a7dea167SDimitry Andric   bool IsMSVCCompat = Args.hasFlag(
7079a7dea167SDimitry Andric       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7080a7dea167SDimitry Andric       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7081a7dea167SDimitry Andric                                      options::OPT_fno_ms_extensions, true)));
70820fca6ea1SDimitry Andric   if (IsMSVCCompat) {
70830b57cec5SDimitry Andric     CmdArgs.push_back("-fms-compatibility");
70840fca6ea1SDimitry Andric     if (!types::isCXX(Input.getType()) &&
70850fca6ea1SDimitry Andric         Args.hasArg(options::OPT_fms_define_stdc))
70860fca6ea1SDimitry Andric       CmdArgs.push_back("-fms-define-stdc");
70870fca6ea1SDimitry Andric   }
70880b57cec5SDimitry Andric 
7089bdd1243dSDimitry Andric   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7090bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
70910fca6ea1SDimitry Andric     ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7092bdd1243dSDimitry Andric 
7093a7dea167SDimitry Andric   // Handle -fgcc-version, if present.
7094a7dea167SDimitry Andric   VersionTuple GNUCVer;
7095a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7096a7dea167SDimitry Andric     // Check that the version has 1 to 3 components and the minor and patch
7097a7dea167SDimitry Andric     // versions fit in two decimal digits.
7098a7dea167SDimitry Andric     StringRef Val = A->getValue();
7099a7dea167SDimitry Andric     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7100a7dea167SDimitry Andric     bool Invalid = GNUCVer.tryParse(Val);
710181ad6265SDimitry Andric     unsigned Minor = GNUCVer.getMinor().value_or(0);
710281ad6265SDimitry Andric     unsigned Patch = GNUCVer.getSubminor().value_or(0);
7103a7dea167SDimitry Andric     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7104a7dea167SDimitry Andric       D.Diag(diag::err_drv_invalid_value)
7105a7dea167SDimitry Andric           << A->getAsString(Args) << A->getValue();
7106a7dea167SDimitry Andric     }
7107a7dea167SDimitry Andric   } else if (!IsMSVCCompat) {
7108a7dea167SDimitry Andric     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7109a7dea167SDimitry Andric     GNUCVer = VersionTuple(4, 2, 1);
7110a7dea167SDimitry Andric   }
7111a7dea167SDimitry Andric   if (!GNUCVer.empty()) {
7112a7dea167SDimitry Andric     CmdArgs.push_back(
7113a7dea167SDimitry Andric         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7114a7dea167SDimitry Andric   }
7115a7dea167SDimitry Andric 
71160b57cec5SDimitry Andric   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
71170b57cec5SDimitry Andric   if (!MSVT.empty())
71180b57cec5SDimitry Andric     CmdArgs.push_back(
71190b57cec5SDimitry Andric         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
71200b57cec5SDimitry Andric 
71210b57cec5SDimitry Andric   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7122fe6060f1SDimitry Andric   if (ImplyVCPPCVer) {
7123fe6060f1SDimitry Andric     StringRef LanguageStandard;
7124fe6060f1SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7125fe6060f1SDimitry Andric       Std = StdArg;
7126fe6060f1SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7127fe6060f1SDimitry Andric                              .Case("c11", "-std=c11")
7128fe6060f1SDimitry Andric                              .Case("c17", "-std=c17")
7129fe6060f1SDimitry Andric                              .Default("");
7130fe6060f1SDimitry Andric       if (LanguageStandard.empty())
7131fe6060f1SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
7132fe6060f1SDimitry Andric             << StdArg->getAsString(Args);
7133fe6060f1SDimitry Andric     }
7134fe6060f1SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
7135fe6060f1SDimitry Andric   }
71360b57cec5SDimitry Andric   if (ImplyVCPPCXXVer) {
71370b57cec5SDimitry Andric     StringRef LanguageStandard;
71380b57cec5SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
71390b57cec5SDimitry Andric       Std = StdArg;
71400b57cec5SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
71410b57cec5SDimitry Andric                              .Case("c++14", "-std=c++14")
71420b57cec5SDimitry Andric                              .Case("c++17", "-std=c++17")
7143fe6060f1SDimitry Andric                              .Case("c++20", "-std=c++20")
714406c3fb27SDimitry Andric                              // TODO add c++23 and c++26 when MSVC supports it.
714506c3fb27SDimitry Andric                              .Case("c++latest", "-std=c++26")
71460b57cec5SDimitry Andric                              .Default("");
71470b57cec5SDimitry Andric       if (LanguageStandard.empty())
71480b57cec5SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
71490b57cec5SDimitry Andric             << StdArg->getAsString(Args);
71500b57cec5SDimitry Andric     }
71510b57cec5SDimitry Andric 
71520b57cec5SDimitry Andric     if (LanguageStandard.empty()) {
71530b57cec5SDimitry Andric       if (IsMSVC2015Compatible)
71540b57cec5SDimitry Andric         LanguageStandard = "-std=c++14";
71550b57cec5SDimitry Andric       else
71560b57cec5SDimitry Andric         LanguageStandard = "-std=c++11";
71570b57cec5SDimitry Andric     }
71580b57cec5SDimitry Andric 
71590b57cec5SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
71600b57cec5SDimitry Andric   }
71610b57cec5SDimitry Andric 
716281ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
716381ad6265SDimitry Andric                     options::OPT_fno_borland_extensions);
71640b57cec5SDimitry Andric 
716581ad6265SDimitry Andric   // -fno-declspec is default, except for PS4/PS5.
71660b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
716781ad6265SDimitry Andric                    RawTriple.isPS()))
71680b57cec5SDimitry Andric     CmdArgs.push_back("-fdeclspec");
71690b57cec5SDimitry Andric   else if (Args.hasArg(options::OPT_fno_declspec))
71700b57cec5SDimitry Andric     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
71710b57cec5SDimitry Andric 
71720b57cec5SDimitry Andric   // -fthreadsafe-static is default, except for MSVC compatibility versions less
71730b57cec5SDimitry Andric   // than 19.
71740b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
71750b57cec5SDimitry Andric                     options::OPT_fno_threadsafe_statics,
7176349cc55cSDimitry Andric                     !types::isOpenCL(InputType) &&
7177349cc55cSDimitry Andric                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
71780b57cec5SDimitry Andric     CmdArgs.push_back("-fno-threadsafe-statics");
71790b57cec5SDimitry Andric 
71800fca6ea1SDimitry Andric   // Add -fno-assumptions, if it was specified.
71810fca6ea1SDimitry Andric   if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
71820fca6ea1SDimitry Andric                     true))
71830fca6ea1SDimitry Andric     CmdArgs.push_back("-fno-assumptions");
71840fca6ea1SDimitry Andric 
71850b57cec5SDimitry Andric   // -fgnu-keywords default varies depending on language; only pass if
71860b57cec5SDimitry Andric   // specified.
71870b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
71880b57cec5SDimitry Andric                   options::OPT_fno_gnu_keywords);
71890b57cec5SDimitry Andric 
719081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
719181ad6265SDimitry Andric                     options::OPT_fno_gnu89_inline);
71920b57cec5SDimitry Andric 
719381ad6265SDimitry Andric   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
71940b57cec5SDimitry Andric                                          options::OPT_finline_hint_functions,
71950b57cec5SDimitry Andric                                          options::OPT_fno_inline_functions);
719681ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
719781ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_fno_inline))
719881ad6265SDimitry Andric       A->render(Args, CmdArgs);
719981ad6265SDimitry Andric   } else if (InlineArg) {
720081ad6265SDimitry Andric     InlineArg->render(Args, CmdArgs);
720181ad6265SDimitry Andric   }
72020b57cec5SDimitry Andric 
7203bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7204bdd1243dSDimitry Andric 
72055f757f3fSDimitry Andric   // FIXME: Find a better way to determine whether we are in C++20.
72065f757f3fSDimitry Andric   bool HaveCxx20 =
72075f757f3fSDimitry Andric       Std &&
72085f757f3fSDimitry Andric       (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
72095f757f3fSDimitry Andric        Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
72105f757f3fSDimitry Andric        Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
72115f757f3fSDimitry Andric        Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
72125f757f3fSDimitry Andric        Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
72135f757f3fSDimitry Andric        Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
72145f757f3fSDimitry Andric        Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
72150b57cec5SDimitry Andric   bool HaveModules =
72165f757f3fSDimitry Andric       RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
72175f757f3fSDimitry Andric 
72185f757f3fSDimitry Andric   // -fdelayed-template-parsing is default when targeting MSVC.
72195f757f3fSDimitry Andric   // Many old Windows SDK versions require this to parse.
72205f757f3fSDimitry Andric   //
72215f757f3fSDimitry Andric   // According to
72225f757f3fSDimitry Andric   // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
72235f757f3fSDimitry Andric   // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
72245f757f3fSDimitry Andric   // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
72255f757f3fSDimitry Andric   // not enable -fdelayed-template-parsing by default after C++20.
72265f757f3fSDimitry Andric   //
72275f757f3fSDimitry Andric   // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
72285f757f3fSDimitry Andric   // able to disable this by default at some point.
72295f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
72305f757f3fSDimitry Andric                    options::OPT_fno_delayed_template_parsing,
72315f757f3fSDimitry Andric                    IsWindowsMSVC && !HaveCxx20)) {
72325f757f3fSDimitry Andric     if (HaveCxx20)
72335f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
72345f757f3fSDimitry Andric 
72355f757f3fSDimitry Andric     CmdArgs.push_back("-fdelayed-template-parsing");
72365f757f3fSDimitry Andric   }
72370b57cec5SDimitry Andric 
7238a7dea167SDimitry Andric   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7239a7dea167SDimitry Andric                    options::OPT_fno_pch_validate_input_files_content, false))
7240a7dea167SDimitry Andric     CmdArgs.push_back("-fvalidate-ast-input-files-content");
72415ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
72425ffd83dbSDimitry Andric                    options::OPT_fno_pch_instantiate_templates, false))
72435ffd83dbSDimitry Andric     CmdArgs.push_back("-fpch-instantiate-templates");
7244590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7245590d96feSDimitry Andric                    false))
7246590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-codegen");
7247590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7248590d96feSDimitry Andric                    false))
7249590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-debuginfo");
7250a7dea167SDimitry Andric 
72515ffd83dbSDimitry Andric   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
72520b57cec5SDimitry Andric   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
72530b57cec5SDimitry Andric                     Input, CmdArgs);
72540b57cec5SDimitry Andric 
7255fe6060f1SDimitry Andric   if (types::isObjC(Input.getType()) &&
7256fe6060f1SDimitry Andric       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7257fe6060f1SDimitry Andric                    options::OPT_fno_objc_encode_cxx_class_template_spec,
7258fe6060f1SDimitry Andric                    !Runtime.isNeXTFamily()))
7259fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7260fe6060f1SDimitry Andric 
72610b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fapplication_extension,
72620b57cec5SDimitry Andric                    options::OPT_fno_application_extension, false))
72630b57cec5SDimitry Andric     CmdArgs.push_back("-fapplication-extension");
72640b57cec5SDimitry Andric 
72650b57cec5SDimitry Andric   // Handle GCC-style exception args.
7266fe6060f1SDimitry Andric   bool EH = false;
72670b57cec5SDimitry Andric   if (!C.getDriver().IsCLMode())
7268fe6060f1SDimitry Andric     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
72690b57cec5SDimitry Andric 
72700b57cec5SDimitry Andric   // Handle exception personalities
7271a7dea167SDimitry Andric   Arg *A = Args.getLastArg(
7272a7dea167SDimitry Andric       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7273a7dea167SDimitry Andric       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
72740b57cec5SDimitry Andric   if (A) {
72750b57cec5SDimitry Andric     const Option &Opt = A->getOption();
72760b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fsjlj_exceptions))
7277e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
72780b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fseh_exceptions))
7279e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
72800b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fdwarf_exceptions))
7281e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
7282a7dea167SDimitry Andric     if (Opt.matches(options::OPT_fwasm_exceptions))
7283e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=wasm");
72840b57cec5SDimitry Andric   } else {
72850b57cec5SDimitry Andric     switch (TC.GetExceptionModel(Args)) {
72860b57cec5SDimitry Andric     default:
72870b57cec5SDimitry Andric       break;
72880b57cec5SDimitry Andric     case llvm::ExceptionHandling::DwarfCFI:
7289e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
72900b57cec5SDimitry Andric       break;
72910b57cec5SDimitry Andric     case llvm::ExceptionHandling::SjLj:
7292e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
72930b57cec5SDimitry Andric       break;
72940b57cec5SDimitry Andric     case llvm::ExceptionHandling::WinEH:
7295e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
72960b57cec5SDimitry Andric       break;
72970b57cec5SDimitry Andric     }
72980b57cec5SDimitry Andric   }
72990b57cec5SDimitry Andric 
73000b57cec5SDimitry Andric   // C++ "sane" operator new.
730181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
730281ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
73030b57cec5SDimitry Andric 
730406c3fb27SDimitry Andric   // -fassume-unique-vtables is on by default.
730506c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
730606c3fb27SDimitry Andric                      options::OPT_fno_assume_unique_vtables);
730706c3fb27SDimitry Andric 
73080fca6ea1SDimitry Andric   // -frelaxed-template-template-args is deprecated.
73090fca6ea1SDimitry Andric   if (Arg *A =
73100fca6ea1SDimitry Andric           Args.getLastArg(options::OPT_frelaxed_template_template_args,
73110fca6ea1SDimitry Andric                           options::OPT_fno_relaxed_template_template_args)) {
73120fca6ea1SDimitry Andric     if (A->getOption().matches(
73130fca6ea1SDimitry Andric             options::OPT_fno_relaxed_template_template_args)) {
73140fca6ea1SDimitry Andric       D.Diag(diag::warn_drv_deprecated_arg_no_relaxed_template_template_args);
73150fca6ea1SDimitry Andric       CmdArgs.push_back("-fno-relaxed-template-template-args");
73160fca6ea1SDimitry Andric     } else {
73170fca6ea1SDimitry Andric       D.Diag(diag::warn_drv_deprecated_arg)
73180fca6ea1SDimitry Andric           << A->getAsString(Args) << /*hasReplacement=*/false;
73190fca6ea1SDimitry Andric     }
73200fca6ea1SDimitry Andric   }
73210b57cec5SDimitry Andric 
73220fca6ea1SDimitry Andric   // -fsized-deallocation is on by default in C++14 onwards and otherwise off
73230fca6ea1SDimitry Andric   // by default.
73240fca6ea1SDimitry Andric   Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
732581ad6265SDimitry Andric                   options::OPT_fno_sized_deallocation);
73260b57cec5SDimitry Andric 
73270b57cec5SDimitry Andric   // -faligned-allocation is on by default in C++17 onwards and otherwise off
73280b57cec5SDimitry Andric   // by default.
73290b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
73300b57cec5SDimitry Andric                                options::OPT_fno_aligned_allocation,
73310b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ)) {
73320b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
73330b57cec5SDimitry Andric       CmdArgs.push_back("-fno-aligned-allocation");
73340b57cec5SDimitry Andric     else
73350b57cec5SDimitry Andric       CmdArgs.push_back("-faligned-allocation");
73360b57cec5SDimitry Andric   }
73370b57cec5SDimitry Andric 
73380b57cec5SDimitry Andric   // The default new alignment can be specified using a dedicated option or via
73390b57cec5SDimitry Andric   // a GCC-compatible option that also turns on aligned allocation.
73400b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
73410b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ))
73420b57cec5SDimitry Andric     CmdArgs.push_back(
73430b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
73440b57cec5SDimitry Andric 
73450b57cec5SDimitry Andric   // -fconstant-cfstrings is default, and may be subject to argument translation
73460b57cec5SDimitry Andric   // on Darwin.
73470b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
734881ad6265SDimitry Andric                     options::OPT_fno_constant_cfstrings, true) ||
73490b57cec5SDimitry Andric       !Args.hasFlag(options::OPT_mconstant_cfstrings,
735081ad6265SDimitry Andric                     options::OPT_mno_constant_cfstrings, true))
73510b57cec5SDimitry Andric     CmdArgs.push_back("-fno-constant-cfstrings");
73520b57cec5SDimitry Andric 
735381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
735481ad6265SDimitry Andric                     options::OPT_fno_pascal_strings);
73550b57cec5SDimitry Andric 
73560b57cec5SDimitry Andric   // Honor -fpack-struct= and -fpack-struct, if given. Note that
73570b57cec5SDimitry Andric   // -fno-pack-struct doesn't apply to -fpack-struct=.
73580b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
73590b57cec5SDimitry Andric     std::string PackStructStr = "-fpack-struct=";
73600b57cec5SDimitry Andric     PackStructStr += A->getValue();
73610b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
73620b57cec5SDimitry Andric   } else if (Args.hasFlag(options::OPT_fpack_struct,
73630b57cec5SDimitry Andric                           options::OPT_fno_pack_struct, false)) {
73640b57cec5SDimitry Andric     CmdArgs.push_back("-fpack-struct=1");
73650b57cec5SDimitry Andric   }
73660b57cec5SDimitry Andric 
73670b57cec5SDimitry Andric   // Handle -fmax-type-align=N and -fno-type-align
73680b57cec5SDimitry Andric   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
73690b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
73700b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
73710b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=";
73720b57cec5SDimitry Andric       MaxTypeAlignStr += A->getValue();
73730b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
73740b57cec5SDimitry Andric     }
73750b57cec5SDimitry Andric   } else if (RawTriple.isOSDarwin()) {
73760b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
73770b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=16";
73780b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
73790b57cec5SDimitry Andric     }
73800b57cec5SDimitry Andric   }
73810b57cec5SDimitry Andric 
73820b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
73830b57cec5SDimitry Andric     CmdArgs.push_back("-Qn");
73840b57cec5SDimitry Andric 
73855ffd83dbSDimitry Andric   // -fno-common is the default, set -fcommon only when that flag is set.
738681ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
73870b57cec5SDimitry Andric 
73880b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't yet support
73890b57cec5SDimitry Andric   // -funsigned-bitfields.
73900b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
739181ad6265SDimitry Andric                     options::OPT_funsigned_bitfields, true))
73920b57cec5SDimitry Andric     D.Diag(diag::warn_drv_clang_unsupported)
73930b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
73940b57cec5SDimitry Andric 
73950b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
739681ad6265SDimitry Andric   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
73970b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported)
73980b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
73990b57cec5SDimitry Andric 
74000b57cec5SDimitry Andric   // -finput_charset=UTF-8 is default. Reject others
74010b57cec5SDimitry Andric   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
74020b57cec5SDimitry Andric     StringRef value = inputCharset->getValue();
7403fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
74040b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
74050b57cec5SDimitry Andric                                           << value;
74060b57cec5SDimitry Andric   }
74070b57cec5SDimitry Andric 
74080b57cec5SDimitry Andric   // -fexec_charset=UTF-8 is default. Reject others
74090b57cec5SDimitry Andric   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
74100b57cec5SDimitry Andric     StringRef value = execCharset->getValue();
7411fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
74120b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
74130b57cec5SDimitry Andric                                           << value;
74140b57cec5SDimitry Andric   }
74150b57cec5SDimitry Andric 
74160b57cec5SDimitry Andric   RenderDiagnosticsOptions(D, Args, CmdArgs);
74170b57cec5SDimitry Andric 
741881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
741981ad6265SDimitry Andric                     options::OPT_fno_asm_blocks);
74200b57cec5SDimitry Andric 
7421bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7422bdd1243dSDimitry Andric                      options::OPT_fno_gnu_inline_asm);
74230b57cec5SDimitry Andric 
74240b57cec5SDimitry Andric   // Enable vectorization per default according to the optimization level
74250b57cec5SDimitry Andric   // selected. For optimization levels that want vectorization we use the alias
74260b57cec5SDimitry Andric   // option to simplify the hasFlag logic.
74270b57cec5SDimitry Andric   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
74280b57cec5SDimitry Andric   OptSpecifier VectorizeAliasOption =
74290b57cec5SDimitry Andric       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
74300b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
74310b57cec5SDimitry Andric                    options::OPT_fno_vectorize, EnableVec))
74320b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-loops");
74330b57cec5SDimitry Andric 
74340b57cec5SDimitry Andric   // -fslp-vectorize is enabled based on the optimization level selected.
74350b57cec5SDimitry Andric   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
74360b57cec5SDimitry Andric   OptSpecifier SLPVectAliasOption =
74370b57cec5SDimitry Andric       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
74380b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
74390b57cec5SDimitry Andric                    options::OPT_fno_slp_vectorize, EnableSLPVec))
74400b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-slp");
74410b57cec5SDimitry Andric 
74420b57cec5SDimitry Andric   ParseMPreferVectorWidth(D, Args, CmdArgs);
74430b57cec5SDimitry Andric 
74440b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
74450b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs,
74460b57cec5SDimitry Andric                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
74470b57cec5SDimitry Andric 
74480b57cec5SDimitry Andric   // -fdollars-in-identifiers default varies depending on platform and
74490b57cec5SDimitry Andric   // language; only pass if specified.
74500b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
74510b57cec5SDimitry Andric                                options::OPT_fno_dollars_in_identifiers)) {
74520b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
74530b57cec5SDimitry Andric       CmdArgs.push_back("-fdollars-in-identifiers");
74540b57cec5SDimitry Andric     else
74550b57cec5SDimitry Andric       CmdArgs.push_back("-fno-dollars-in-identifiers");
74560b57cec5SDimitry Andric   }
74570b57cec5SDimitry Andric 
745881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
745981ad6265SDimitry Andric                     options::OPT_fno_apple_pragma_pack);
74600b57cec5SDimitry Andric 
74610b57cec5SDimitry Andric   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7462480093f4SDimitry Andric   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7463480093f4SDimitry Andric     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
74640b57cec5SDimitry Andric 
74650b57cec5SDimitry Andric   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
74660b57cec5SDimitry Andric                                      options::OPT_fno_rewrite_imports, false);
74670b57cec5SDimitry Andric   if (RewriteImports)
74680b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-imports");
74690b57cec5SDimitry Andric 
7470bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7471bdd1243dSDimitry Andric                     options::OPT_fno_directives_only);
747281ad6265SDimitry Andric 
74730b57cec5SDimitry Andric   // Enable rewrite includes if the user's asked for it or if we're generating
74740b57cec5SDimitry Andric   // diagnostics.
74750b57cec5SDimitry Andric   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
74760b57cec5SDimitry Andric   // nice to enable this when doing a crashdump for modules as well.
74770b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_frewrite_includes,
74780b57cec5SDimitry Andric                    options::OPT_fno_rewrite_includes, false) ||
74790b57cec5SDimitry Andric       (C.isForDiagnostics() && !HaveModules))
74800b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-includes");
74810b57cec5SDimitry Andric 
74820b57cec5SDimitry Andric   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
74830b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_traditional,
74840b57cec5SDimitry Andric                                options::OPT_traditional_cpp)) {
74850b57cec5SDimitry Andric     if (isa<PreprocessJobAction>(JA))
74860b57cec5SDimitry Andric       CmdArgs.push_back("-traditional-cpp");
74870b57cec5SDimitry Andric     else
74880b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
74890b57cec5SDimitry Andric   }
74900b57cec5SDimitry Andric 
74910b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dM);
74920b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dD);
749304eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dI);
74940b57cec5SDimitry Andric 
74955ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
74965ffd83dbSDimitry Andric 
74970b57cec5SDimitry Andric   // Handle serialized diagnostics.
74980b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
74990b57cec5SDimitry Andric     CmdArgs.push_back("-serialize-diagnostic-file");
75000b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
75010b57cec5SDimitry Andric   }
75020b57cec5SDimitry Andric 
75030b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
75040b57cec5SDimitry Andric     CmdArgs.push_back("-fretain-comments-from-system-headers");
75050b57cec5SDimitry Andric 
75060b57cec5SDimitry Andric   // Forward -fcomment-block-commands to -cc1.
75070b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
75080b57cec5SDimitry Andric   // Forward -fparse-all-comments to -cc1.
75090b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
75100b57cec5SDimitry Andric 
75110b57cec5SDimitry Andric   // Turn -fplugin=name.so into -load name.so
75120b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
75130b57cec5SDimitry Andric     CmdArgs.push_back("-load");
75140b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
75150b57cec5SDimitry Andric     A->claim();
75160b57cec5SDimitry Andric   }
75170b57cec5SDimitry Andric 
75184824e7fdSDimitry Andric   // Turn -fplugin-arg-pluginname-key=value into
75194824e7fdSDimitry Andric   // -plugin-arg-pluginname key=value
75204824e7fdSDimitry Andric   // GCC has an actual plugin_argument struct with key/value pairs that it
75214824e7fdSDimitry Andric   // passes to its plugins, but we don't, so just pass it on as-is.
75224824e7fdSDimitry Andric   //
75234824e7fdSDimitry Andric   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
75244824e7fdSDimitry Andric   // argument key are allowed to contain dashes. GCC therefore only
75254824e7fdSDimitry Andric   // allows dashes in the key. We do the same.
75264824e7fdSDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
75274824e7fdSDimitry Andric     auto ArgValue = StringRef(A->getValue());
75284824e7fdSDimitry Andric     auto FirstDashIndex = ArgValue.find('-');
75294824e7fdSDimitry Andric     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
75304824e7fdSDimitry Andric     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
75314824e7fdSDimitry Andric 
75324824e7fdSDimitry Andric     A->claim();
75334824e7fdSDimitry Andric     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
75344824e7fdSDimitry Andric       if (PluginName.empty()) {
75354824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
75364824e7fdSDimitry Andric       } else {
75374824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_arg)
75384824e7fdSDimitry Andric             << PluginName << A->getAsString(Args);
75394824e7fdSDimitry Andric       }
75404824e7fdSDimitry Andric       continue;
75414824e7fdSDimitry Andric     }
75424824e7fdSDimitry Andric 
75434824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
75444824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Arg));
75454824e7fdSDimitry Andric   }
75464824e7fdSDimitry Andric 
75470b57cec5SDimitry Andric   // Forward -fpass-plugin=name.so to -cc1.
75480b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
75490b57cec5SDimitry Andric     CmdArgs.push_back(
75500b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
75510b57cec5SDimitry Andric     A->claim();
75520b57cec5SDimitry Andric   }
75530b57cec5SDimitry Andric 
755406c3fb27SDimitry Andric   // Forward --vfsoverlay to -cc1.
755506c3fb27SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
755606c3fb27SDimitry Andric     CmdArgs.push_back("--vfsoverlay");
755706c3fb27SDimitry Andric     CmdArgs.push_back(A->getValue());
755806c3fb27SDimitry Andric     A->claim();
755906c3fb27SDimitry Andric   }
756006c3fb27SDimitry Andric 
756106c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
756206c3fb27SDimitry Andric                     options::OPT_fno_safe_buffer_usage_suggestions);
756306c3fb27SDimitry Andric 
75640fca6ea1SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
75650fca6ea1SDimitry Andric                     options::OPT_fno_experimental_late_parse_attributes);
75660fca6ea1SDimitry Andric 
75670b57cec5SDimitry Andric   // Setup statistics file output.
75680b57cec5SDimitry Andric   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
756906c3fb27SDimitry Andric   if (!StatsFile.empty()) {
75700b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
757106c3fb27SDimitry Andric     if (D.CCPrintInternalStats)
757206c3fb27SDimitry Andric       CmdArgs.push_back("-stats-file-append");
757306c3fb27SDimitry Andric   }
75740b57cec5SDimitry Andric 
75750b57cec5SDimitry Andric   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
75760b57cec5SDimitry Andric   // parser.
7577bdd1243dSDimitry Andric   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7578bdd1243dSDimitry Andric     Arg->claim();
75790b57cec5SDimitry Andric     // -finclude-default-header flag is for preprocessor,
75800b57cec5SDimitry Andric     // do not pass it to other cc1 commands when save-temps is enabled
75810b57cec5SDimitry Andric     if (C.getDriver().isSaveTempsEnabled() &&
75820b57cec5SDimitry Andric         !isa<PreprocessJobAction>(JA)) {
7583bdd1243dSDimitry Andric       if (StringRef(Arg->getValue()) == "-finclude-default-header")
7584bdd1243dSDimitry Andric         continue;
7585bdd1243dSDimitry Andric     }
75860b57cec5SDimitry Andric     CmdArgs.push_back(Arg->getValue());
75870b57cec5SDimitry Andric   }
75880b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
75890b57cec5SDimitry Andric     A->claim();
75900b57cec5SDimitry Andric 
75910b57cec5SDimitry Andric     // We translate this by hand to the -cc1 argument, since nightly test uses
75920b57cec5SDimitry Andric     // it and developers have been trained to spell it with -mllvm. Both
75930b57cec5SDimitry Andric     // spellings are now deprecated and should be removed.
75940b57cec5SDimitry Andric     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
75950b57cec5SDimitry Andric       CmdArgs.push_back("-disable-llvm-optzns");
75960b57cec5SDimitry Andric     } else {
75970b57cec5SDimitry Andric       A->render(Args, CmdArgs);
75980b57cec5SDimitry Andric     }
75990b57cec5SDimitry Andric   }
76000b57cec5SDimitry Andric 
76010b57cec5SDimitry Andric   // With -save-temps, we want to save the unoptimized bitcode output from the
76020b57cec5SDimitry Andric   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
76030b57cec5SDimitry Andric   // by the frontend.
76040b57cec5SDimitry Andric   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
76050b57cec5SDimitry Andric   // has slightly different breakdown between stages.
76060b57cec5SDimitry Andric   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
76070b57cec5SDimitry Andric   // pristine IR generated by the frontend. Ideally, a new compile action should
76080b57cec5SDimitry Andric   // be added so both IR can be captured.
76095ffd83dbSDimitry Andric   if ((C.getDriver().isSaveTempsEnabled() ||
76105ffd83dbSDimitry Andric        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7611fe6060f1SDimitry Andric       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
76120b57cec5SDimitry Andric       isa<CompileJobAction>(JA))
76130b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
76140b57cec5SDimitry Andric 
76150b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_undef);
76160b57cec5SDimitry Andric 
76170b57cec5SDimitry Andric   const char *Exec = D.getClangProgramPath();
76180b57cec5SDimitry Andric 
76190b57cec5SDimitry Andric   // Optionally embed the -cc1 level arguments into the debug info or a
76200b57cec5SDimitry Andric   // section, for build analysis.
76210b57cec5SDimitry Andric   // Also record command line arguments into the debug info if
76220b57cec5SDimitry Andric   // -grecord-gcc-switches options is set on.
76230b57cec5SDimitry Andric   // By default, -gno-record-gcc-switches is set on and no recording.
76240b57cec5SDimitry Andric   auto GRecordSwitches =
76250b57cec5SDimitry Andric       Args.hasFlag(options::OPT_grecord_command_line,
76260b57cec5SDimitry Andric                    options::OPT_gno_record_command_line, false);
76270b57cec5SDimitry Andric   auto FRecordSwitches =
76280b57cec5SDimitry Andric       Args.hasFlag(options::OPT_frecord_command_line,
76290b57cec5SDimitry Andric                    options::OPT_fno_record_command_line, false);
763006c3fb27SDimitry Andric   if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
763106c3fb27SDimitry Andric       !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
76320b57cec5SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt_for_target)
76330b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
76340b57cec5SDimitry Andric         << TripleStr;
76350b57cec5SDimitry Andric   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
76360b57cec5SDimitry Andric     ArgStringList OriginalArgs;
76370b57cec5SDimitry Andric     for (const auto &Arg : Args)
76380b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
76390b57cec5SDimitry Andric 
76400b57cec5SDimitry Andric     SmallString<256> Flags;
76415ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
76420b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
76430b57cec5SDimitry Andric       SmallString<128> EscapedArg;
76440b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
76450b57cec5SDimitry Andric       Flags += " ";
76460b57cec5SDimitry Andric       Flags += EscapedArg;
76470b57cec5SDimitry Andric     }
76480b57cec5SDimitry Andric     auto FlagsArgString = Args.MakeArgString(Flags);
76490b57cec5SDimitry Andric     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
76500b57cec5SDimitry Andric       CmdArgs.push_back("-dwarf-debug-flags");
76510b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
76520b57cec5SDimitry Andric     }
76530b57cec5SDimitry Andric     if (FRecordSwitches) {
76540b57cec5SDimitry Andric       CmdArgs.push_back("-record-command-line");
76550b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
76560b57cec5SDimitry Andric     }
76570b57cec5SDimitry Andric   }
76580b57cec5SDimitry Andric 
7659753f127fSDimitry Andric   // Host-side offloading compilation receives all device-side outputs. Include
7660753f127fSDimitry Andric   // them in the host compilation depending on the target. If the host inputs
7661753f127fSDimitry Andric   // are not empty we use the new-driver scheme, otherwise use the old scheme.
76620b57cec5SDimitry Andric   if ((IsCuda || IsHIP) && CudaDeviceInput) {
76630b57cec5SDimitry Andric     CmdArgs.push_back("-fcuda-include-gpubinary");
76640b57cec5SDimitry Andric     CmdArgs.push_back(CudaDeviceInput->getFilename());
7665753f127fSDimitry Andric   } else if (!HostOffloadingInputs.empty()) {
7666fcaf7f86SDimitry Andric     if ((IsCuda || IsHIP) && !IsRDCMode) {
7667753f127fSDimitry Andric       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7668753f127fSDimitry Andric       CmdArgs.push_back("-fcuda-include-gpubinary");
7669753f127fSDimitry Andric       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7670753f127fSDimitry Andric     } else {
7671753f127fSDimitry Andric       for (const InputInfo Input : HostOffloadingInputs)
7672753f127fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7673753f127fSDimitry Andric                                              TC.getInputFilename(Input)));
7674753f127fSDimitry Andric     }
76750b57cec5SDimitry Andric   }
76760b57cec5SDimitry Andric 
76770b57cec5SDimitry Andric   if (IsCuda) {
76780b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
76790b57cec5SDimitry Andric                      options::OPT_fno_cuda_short_ptr, false))
76800b57cec5SDimitry Andric       CmdArgs.push_back("-fcuda-short-ptr");
76810b57cec5SDimitry Andric   }
76820b57cec5SDimitry Andric 
7683fe6060f1SDimitry Andric   if (IsCuda || IsHIP) {
7684fe6060f1SDimitry Andric     // Determine the original source input.
7685fe6060f1SDimitry Andric     const Action *SourceAction = &JA;
7686fe6060f1SDimitry Andric     while (SourceAction->getKind() != Action::InputClass) {
7687fe6060f1SDimitry Andric       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7688fe6060f1SDimitry Andric       SourceAction = SourceAction->getInputs()[0];
7689fe6060f1SDimitry Andric     }
7690fe6060f1SDimitry Andric     auto CUID = cast<InputAction>(SourceAction)->getId();
7691fe6060f1SDimitry Andric     if (!CUID.empty())
7692fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
76935f757f3fSDimitry Andric 
76945f757f3fSDimitry Andric     // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
76955f757f3fSDimitry Andric     // be overriden by -fno-gpu-approx-transcendentals.
76965f757f3fSDimitry Andric     bool UseApproxTranscendentals = Args.hasFlag(
76975f757f3fSDimitry Andric         options::OPT_ffast_math, options::OPT_fno_fast_math, false);
76985f757f3fSDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
76995f757f3fSDimitry Andric                      options::OPT_fno_gpu_approx_transcendentals,
77005f757f3fSDimitry Andric                      UseApproxTranscendentals))
77015f757f3fSDimitry Andric       CmdArgs.push_back("-fgpu-approx-transcendentals");
77025f757f3fSDimitry Andric   } else {
77035f757f3fSDimitry Andric     Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
77045f757f3fSDimitry Andric                       options::OPT_fno_gpu_approx_transcendentals);
7705fe6060f1SDimitry Andric   }
7706fe6060f1SDimitry Andric 
770781ad6265SDimitry Andric   if (IsHIP) {
7708480093f4SDimitry Andric     CmdArgs.push_back("-fcuda-allow-variadic-functions");
770981ad6265SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
771081ad6265SDimitry Andric   }
7711480093f4SDimitry Andric 
77125f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
77135f757f3fSDimitry Andric                   options::OPT_fno_offload_uniform_block);
77145f757f3fSDimitry Andric 
77155f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
77165f757f3fSDimitry Andric                   options::OPT_fno_offload_implicit_host_device_templates);
77175f757f3fSDimitry Andric 
7718fe6060f1SDimitry Andric   if (IsCudaDevice || IsHIPDevice) {
7719fe6060f1SDimitry Andric     StringRef InlineThresh =
7720fe6060f1SDimitry Andric         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7721fe6060f1SDimitry Andric     if (!InlineThresh.empty()) {
7722fe6060f1SDimitry Andric       std::string ArgStr =
7723fe6060f1SDimitry Andric           std::string("-inline-threshold=") + InlineThresh.str();
7724fe6060f1SDimitry Andric       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7725fe6060f1SDimitry Andric     }
7726fe6060f1SDimitry Andric   }
7727fe6060f1SDimitry Andric 
772806c3fb27SDimitry Andric   if (IsHIPDevice)
772906c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs,
773006c3fb27SDimitry Andric                        options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
773106c3fb27SDimitry Andric                        options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
773206c3fb27SDimitry Andric 
77330b57cec5SDimitry Andric   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
77340b57cec5SDimitry Andric   // to specify the result of the compile phase on the host, so the meaningful
773506c3fb27SDimitry Andric   // device declarations can be identified. Also, -fopenmp-is-target-device is
773606c3fb27SDimitry Andric   // passed along to tell the frontend that it is generating code for a device,
773706c3fb27SDimitry Andric   // so that only the relevant declarations are emitted.
77380b57cec5SDimitry Andric   if (IsOpenMPDevice) {
773906c3fb27SDimitry Andric     CmdArgs.push_back("-fopenmp-is-target-device");
77400b57cec5SDimitry Andric     if (OpenMPDeviceInput) {
77410b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp-host-ir-file-path");
77420b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
77430b57cec5SDimitry Andric     }
77440b57cec5SDimitry Andric   }
77450b57cec5SDimitry Andric 
7746e8d8bef9SDimitry Andric   if (Triple.isAMDGPU()) {
7747e8d8bef9SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7748e8d8bef9SDimitry Andric 
774981ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
775081ad6265SDimitry Andric                       options::OPT_mno_unsafe_fp_atomics);
775106c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
775206c3fb27SDimitry Andric                        options::OPT_mno_amdgpu_ieee);
7753e8d8bef9SDimitry Andric   }
7754e8d8bef9SDimitry Andric 
77550b57cec5SDimitry Andric   // For all the host OpenMP offloading compile jobs we need to pass the targets
77560b57cec5SDimitry Andric   // information using -fopenmp-targets= option.
77570b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
775881ad6265SDimitry Andric     SmallString<128> Targets("-fopenmp-targets=");
77590b57cec5SDimitry Andric 
776081ad6265SDimitry Andric     SmallVector<std::string, 4> Triples;
776181ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
776281ad6265SDimitry Andric     std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
776381ad6265SDimitry Andric                    [](auto TC) { return TC.second->getTripleString(); });
776481ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
77650b57cec5SDimitry Andric   }
77660b57cec5SDimitry Andric 
7767a7dea167SDimitry Andric   bool VirtualFunctionElimination =
7768a7dea167SDimitry Andric       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7769a7dea167SDimitry Andric                    options::OPT_fno_virtual_function_elimination, false);
7770a7dea167SDimitry Andric   if (VirtualFunctionElimination) {
7771a7dea167SDimitry Andric     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7772a7dea167SDimitry Andric     // in the future).
7773fe6060f1SDimitry Andric     if (LTOMode != LTOK_Full)
7774a7dea167SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
7775a7dea167SDimitry Andric           << "-fvirtual-function-elimination"
7776a7dea167SDimitry Andric           << "-flto=full";
7777a7dea167SDimitry Andric 
7778a7dea167SDimitry Andric     CmdArgs.push_back("-fvirtual-function-elimination");
7779a7dea167SDimitry Andric   }
7780a7dea167SDimitry Andric 
7781a7dea167SDimitry Andric   // VFE requires whole-program-vtables, and enables it by default.
7782a7dea167SDimitry Andric   bool WholeProgramVTables = Args.hasFlag(
7783a7dea167SDimitry Andric       options::OPT_fwhole_program_vtables,
7784a7dea167SDimitry Andric       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7785a7dea167SDimitry Andric   if (VirtualFunctionElimination && !WholeProgramVTables) {
7786a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
7787a7dea167SDimitry Andric         << "-fno-whole-program-vtables"
7788a7dea167SDimitry Andric         << "-fvirtual-function-elimination";
7789a7dea167SDimitry Andric   }
7790a7dea167SDimitry Andric 
77910b57cec5SDimitry Andric   if (WholeProgramVTables) {
779206c3fb27SDimitry Andric     // PS4 uses the legacy LTO API, which does not support this feature in
779306c3fb27SDimitry Andric     // ThinLTO mode.
779406c3fb27SDimitry Andric     bool IsPS4 = getToolChain().getTriple().isPS4();
779506c3fb27SDimitry Andric 
7796fe6060f1SDimitry Andric     // Check if we passed LTO options but they were suppressed because this is a
7797fe6060f1SDimitry Andric     // device offloading action, or we passed device offload LTO options which
7798fe6060f1SDimitry Andric     // were suppressed because this is not the device offload action.
779906c3fb27SDimitry Andric     // Check if we are using PS4 in regular LTO mode.
7800fe6060f1SDimitry Andric     // Otherwise, issue an error.
780106c3fb27SDimitry Andric     if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
780206c3fb27SDimitry Andric         (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
78030b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
78040b57cec5SDimitry Andric           << "-fwhole-program-vtables"
780506c3fb27SDimitry Andric           << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
780606c3fb27SDimitry Andric 
780706c3fb27SDimitry Andric     // Propagate -fwhole-program-vtables if this is an LTO compile.
780806c3fb27SDimitry Andric     if (IsUsingLTO)
780906c3fb27SDimitry Andric       CmdArgs.push_back("-fwhole-program-vtables");
78100b57cec5SDimitry Andric   }
78110b57cec5SDimitry Andric 
7812480093f4SDimitry Andric   bool DefaultsSplitLTOUnit =
781306c3fb27SDimitry Andric       ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
781406c3fb27SDimitry Andric           (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
781506c3fb27SDimitry Andric       (!Triple.isPS4() && UnifiedLTO);
78160b57cec5SDimitry Andric   bool SplitLTOUnit =
78170b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_lto_unit,
7818a7dea167SDimitry Andric                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7819349cc55cSDimitry Andric   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7820a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7821a7dea167SDimitry Andric                                                     << "-fsanitize=cfi";
78220b57cec5SDimitry Andric   if (SplitLTOUnit)
78230b57cec5SDimitry Andric     CmdArgs.push_back("-fsplit-lto-unit");
78240b57cec5SDimitry Andric 
78255f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
78265f757f3fSDimitry Andric                                options::OPT_fno_fat_lto_objects)) {
78275f757f3fSDimitry Andric     if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
78285f757f3fSDimitry Andric       assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
78295f757f3fSDimitry Andric       if (!Triple.isOSBinFormatELF()) {
78305f757f3fSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
78315f757f3fSDimitry Andric             << A->getAsString(Args) << TC.getTripleString();
78325f757f3fSDimitry Andric       }
78335f757f3fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
78345f757f3fSDimitry Andric           Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
78355f757f3fSDimitry Andric       CmdArgs.push_back("-flto-unit");
78365f757f3fSDimitry Andric       CmdArgs.push_back("-ffat-lto-objects");
78375f757f3fSDimitry Andric       A->render(Args, CmdArgs);
78385f757f3fSDimitry Andric     }
78395f757f3fSDimitry Andric   }
78405f757f3fSDimitry Andric 
78415ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
78425ffd83dbSDimitry Andric                                options::OPT_fno_global_isel)) {
78430b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
78445ffd83dbSDimitry Andric     if (A->getOption().matches(options::OPT_fglobal_isel)) {
78450b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=1");
78460b57cec5SDimitry Andric 
78470b57cec5SDimitry Andric       // GISel is on by default on AArch64 -O0, so don't bother adding
78480b57cec5SDimitry Andric       // the fallback remarks for it. Other combinations will add a warning of
78490b57cec5SDimitry Andric       // some kind.
78500b57cec5SDimitry Andric       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
78510b57cec5SDimitry Andric       bool IsOptLevelSupported = false;
78520b57cec5SDimitry Andric 
78530b57cec5SDimitry Andric       Arg *A = Args.getLastArg(options::OPT_O_Group);
78540b57cec5SDimitry Andric       if (Triple.getArch() == llvm::Triple::aarch64) {
78550b57cec5SDimitry Andric         if (!A || A->getOption().matches(options::OPT_O0))
78560b57cec5SDimitry Andric           IsOptLevelSupported = true;
78570b57cec5SDimitry Andric       }
78580b57cec5SDimitry Andric       if (!IsArchSupported || !IsOptLevelSupported) {
78590b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
78600b57cec5SDimitry Andric         CmdArgs.push_back("-global-isel-abort=2");
78610b57cec5SDimitry Andric 
78620b57cec5SDimitry Andric         if (!IsArchSupported)
78635ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
78640b57cec5SDimitry Andric         else
78655ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
78660b57cec5SDimitry Andric       }
78670b57cec5SDimitry Andric     } else {
78680b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=0");
78690b57cec5SDimitry Andric     }
78700b57cec5SDimitry Andric   }
78710b57cec5SDimitry Andric 
78720b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
78730b57cec5SDimitry Andric      CmdArgs.push_back("-forder-file-instrumentation");
78740b57cec5SDimitry Andric      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
78750b57cec5SDimitry Andric      // on, we need to pass these flags as linker flags and that will be handled
78760b57cec5SDimitry Andric      // outside of the compiler.
7877fe6060f1SDimitry Andric      if (!IsUsingLTO) {
78780b57cec5SDimitry Andric        CmdArgs.push_back("-mllvm");
78790b57cec5SDimitry Andric        CmdArgs.push_back("-enable-order-file-instrumentation");
78800b57cec5SDimitry Andric      }
78810b57cec5SDimitry Andric   }
78820b57cec5SDimitry Andric 
78830b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
78840b57cec5SDimitry Andric                                options::OPT_fno_force_enable_int128)) {
78850b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fforce_enable_int128))
78860b57cec5SDimitry Andric       CmdArgs.push_back("-fforce-enable-int128");
78870b57cec5SDimitry Andric   }
78880b57cec5SDimitry Andric 
788981ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
789081ad6265SDimitry Andric                     options::OPT_fno_keep_static_consts);
789106c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
789206c3fb27SDimitry Andric                     options::OPT_fno_keep_persistent_storage_variables);
789381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
789481ad6265SDimitry Andric                     options::OPT_fno_complete_member_pointers);
7895bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7896bdd1243dSDimitry Andric                      options::OPT_fno_cxx_static_destructors);
78970b57cec5SDimitry Andric 
7898e8d8bef9SDimitry Andric   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7899e8d8bef9SDimitry Andric 
79000fca6ea1SDimitry Andric   addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
79010b57cec5SDimitry Andric 
7902bdd1243dSDimitry Andric   if (Triple.isAArch64() &&
7903bdd1243dSDimitry Andric       (Args.hasArg(options::OPT_mno_fmv) ||
79045f757f3fSDimitry Andric        (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7905bdd1243dSDimitry Andric        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7906bdd1243dSDimitry Andric     // Disable Function Multiversioning on AArch64 target.
7907bdd1243dSDimitry Andric     CmdArgs.push_back("-target-feature");
7908bdd1243dSDimitry Andric     CmdArgs.push_back("-fmv");
7909bdd1243dSDimitry Andric   }
7910bdd1243dSDimitry Andric 
79110b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
79120b57cec5SDimitry Andric                    (TC.getTriple().isOSBinFormatELF() ||
79130b57cec5SDimitry Andric                     TC.getTriple().isOSBinFormatCOFF()) &&
7914e8d8bef9SDimitry Andric                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
79150b57cec5SDimitry Andric                        !TC.getTriple().isOSNetBSD() &&
7916480093f4SDimitry Andric                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7917e8d8bef9SDimitry Andric                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
79180b57cec5SDimitry Andric     CmdArgs.push_back("-faddrsig");
79190b57cec5SDimitry Andric 
7920fe6060f1SDimitry Andric   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7921bdd1243dSDimitry Andric       (EH || UnwindTables || AsyncUnwindTables ||
792206c3fb27SDimitry Andric        DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7923fe6060f1SDimitry Andric     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7924fe6060f1SDimitry Andric 
79250b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
79260b57cec5SDimitry Andric     std::string Str = A->getAsString(Args);
79270b57cec5SDimitry Andric     if (!TC.getTriple().isOSBinFormatELF())
79280b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
79290b57cec5SDimitry Andric           << Str << TC.getTripleString();
79300b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Str));
79310b57cec5SDimitry Andric   }
79320b57cec5SDimitry Andric 
79330b57cec5SDimitry Andric   // Add the "-o out -x type src.c" flags last. This is done primarily to make
79340b57cec5SDimitry Andric   // the -cc1 command easier to edit when reproducing compiler crashes.
79350b57cec5SDimitry Andric   if (Output.getType() == types::TY_Dependencies) {
79360b57cec5SDimitry Andric     // Handled with other dependency code.
79370b57cec5SDimitry Andric   } else if (Output.isFilename()) {
7938480093f4SDimitry Andric     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7939480093f4SDimitry Andric         Output.getType() == clang::driver::types::TY_IFS) {
7940480093f4SDimitry Andric       SmallString<128> OutputFilename(Output.getFilename());
7941480093f4SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7942480093f4SDimitry Andric       CmdArgs.push_back("-o");
7943480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7944480093f4SDimitry Andric     } else {
79450b57cec5SDimitry Andric       CmdArgs.push_back("-o");
79460b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
7947480093f4SDimitry Andric     }
79480b57cec5SDimitry Andric   } else {
79490b57cec5SDimitry Andric     assert(Output.isNothing() && "Invalid output.");
79500b57cec5SDimitry Andric   }
79510b57cec5SDimitry Andric 
79520b57cec5SDimitry Andric   addDashXForInput(Args, Input, CmdArgs);
79530b57cec5SDimitry Andric 
79540b57cec5SDimitry Andric   ArrayRef<InputInfo> FrontendInputs = Input;
7955bdd1243dSDimitry Andric   if (IsExtractAPI)
795681ad6265SDimitry Andric     FrontendInputs = ExtractAPIInputs;
79570b57cec5SDimitry Andric   else if (Input.isNothing())
79580b57cec5SDimitry Andric     FrontendInputs = {};
79590b57cec5SDimitry Andric 
79600b57cec5SDimitry Andric   for (const InputInfo &Input : FrontendInputs) {
79610b57cec5SDimitry Andric     if (Input.isFilename())
79620b57cec5SDimitry Andric       CmdArgs.push_back(Input.getFilename());
79630b57cec5SDimitry Andric     else
79640b57cec5SDimitry Andric       Input.getInputArg().renderAsInput(Args, CmdArgs);
79650b57cec5SDimitry Andric   }
79660b57cec5SDimitry Andric 
7967fe6060f1SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
7968480093f4SDimitry Andric     // Invoke the CC1 directly in this process
796906c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
797006c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
797106c3fb27SDimitry Andric         Output, D.getPrependArg()));
79720b57cec5SDimitry Andric   } else {
797306c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
797406c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
797506c3fb27SDimitry Andric         Output, D.getPrependArg()));
79760b57cec5SDimitry Andric   }
79770b57cec5SDimitry Andric 
79780b57cec5SDimitry Andric   // Make the compile command echo its inputs for /showFilenames.
79790b57cec5SDimitry Andric   if (Output.getType() == types::TY_Object &&
79800b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_showFilenames,
79810b57cec5SDimitry Andric                    options::OPT__SLASH_showFilenames_, false)) {
798213138422SDimitry Andric     C.getJobs().getJobs().back()->PrintInputFilenames = true;
79830b57cec5SDimitry Andric   }
79840b57cec5SDimitry Andric 
79850b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_pg))
79865ffd83dbSDimitry Andric     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
79875ffd83dbSDimitry Andric         !Args.hasArg(options::OPT_mfentry))
79880b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
79890b57cec5SDimitry Andric                                                       << A->getAsString(Args);
79900b57cec5SDimitry Andric 
79910b57cec5SDimitry Andric   // Claim some arguments which clang supports automatically.
79920b57cec5SDimitry Andric 
79930b57cec5SDimitry Andric   // -fpch-preprocess is used with gcc to add a special marker in the output to
79940b57cec5SDimitry Andric   // include the PCH file.
79950b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
79960b57cec5SDimitry Andric 
79970b57cec5SDimitry Andric   // Claim some arguments which clang doesn't support, but we don't
79980b57cec5SDimitry Andric   // care to warn the user about.
79990b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
80000b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
80010b57cec5SDimitry Andric 
80020b57cec5SDimitry Andric   // Disable warnings for clang -E -emit-llvm foo.c
80030b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
80040b57cec5SDimitry Andric }
80050b57cec5SDimitry Andric 
Clang(const ToolChain & TC,bool HasIntegratedBackend)80060eae32dcSDimitry Andric Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
80070b57cec5SDimitry Andric     // CAUTION! The first constructor argument ("clang") is not arbitrary,
80080b57cec5SDimitry Andric     // as it is for other tools. Some operations on a Tool actually test
80090b57cec5SDimitry Andric     // whether that tool is Clang based on the Tool's Name as a string.
80100eae32dcSDimitry Andric     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
80110b57cec5SDimitry Andric 
~Clang()80120b57cec5SDimitry Andric Clang::~Clang() {}
80130b57cec5SDimitry Andric 
80140b57cec5SDimitry Andric /// Add options related to the Objective-C runtime/ABI.
80150b57cec5SDimitry Andric ///
80160b57cec5SDimitry Andric /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,const InputInfoList & inputs,ArgStringList & cmdArgs,RewriteKind rewriteKind) const80170b57cec5SDimitry Andric ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
80185ffd83dbSDimitry Andric                                       const InputInfoList &inputs,
80190b57cec5SDimitry Andric                                       ArgStringList &cmdArgs,
80200b57cec5SDimitry Andric                                       RewriteKind rewriteKind) const {
80210b57cec5SDimitry Andric   // Look for the controlling runtime option.
80220b57cec5SDimitry Andric   Arg *runtimeArg =
80230b57cec5SDimitry Andric       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
80240b57cec5SDimitry Andric                       options::OPT_fobjc_runtime_EQ);
80250b57cec5SDimitry Andric 
80260b57cec5SDimitry Andric   // Just forward -fobjc-runtime= to the frontend.  This supercedes
80270b57cec5SDimitry Andric   // options about fragility.
80280b57cec5SDimitry Andric   if (runtimeArg &&
80290b57cec5SDimitry Andric       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
80300b57cec5SDimitry Andric     ObjCRuntime runtime;
80310b57cec5SDimitry Andric     StringRef value = runtimeArg->getValue();
80320b57cec5SDimitry Andric     if (runtime.tryParse(value)) {
80330b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
80340b57cec5SDimitry Andric           << value;
80350b57cec5SDimitry Andric     }
80360b57cec5SDimitry Andric     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
80370b57cec5SDimitry Andric         (runtime.getVersion() >= VersionTuple(2, 0)))
80380b57cec5SDimitry Andric       if (!getToolChain().getTriple().isOSBinFormatELF() &&
80390b57cec5SDimitry Andric           !getToolChain().getTriple().isOSBinFormatCOFF()) {
80400b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
80410b57cec5SDimitry Andric             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
80420b57cec5SDimitry Andric           << runtime.getVersion().getMajor();
80430b57cec5SDimitry Andric       }
80440b57cec5SDimitry Andric 
80450b57cec5SDimitry Andric     runtimeArg->render(args, cmdArgs);
80460b57cec5SDimitry Andric     return runtime;
80470b57cec5SDimitry Andric   }
80480b57cec5SDimitry Andric 
80490b57cec5SDimitry Andric   // Otherwise, we'll need the ABI "version".  Version numbers are
80500b57cec5SDimitry Andric   // slightly confusing for historical reasons:
80510b57cec5SDimitry Andric   //   1 - Traditional "fragile" ABI
80520b57cec5SDimitry Andric   //   2 - Non-fragile ABI, version 1
80530b57cec5SDimitry Andric   //   3 - Non-fragile ABI, version 2
80540b57cec5SDimitry Andric   unsigned objcABIVersion = 1;
80550b57cec5SDimitry Andric   // If -fobjc-abi-version= is present, use that to set the version.
80560b57cec5SDimitry Andric   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
80570b57cec5SDimitry Andric     StringRef value = abiArg->getValue();
80580b57cec5SDimitry Andric     if (value == "1")
80590b57cec5SDimitry Andric       objcABIVersion = 1;
80600b57cec5SDimitry Andric     else if (value == "2")
80610b57cec5SDimitry Andric       objcABIVersion = 2;
80620b57cec5SDimitry Andric     else if (value == "3")
80630b57cec5SDimitry Andric       objcABIVersion = 3;
80640b57cec5SDimitry Andric     else
80650b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
80660b57cec5SDimitry Andric   } else {
80670b57cec5SDimitry Andric     // Otherwise, determine if we are using the non-fragile ABI.
80680b57cec5SDimitry Andric     bool nonFragileABIIsDefault =
80690b57cec5SDimitry Andric         (rewriteKind == RK_NonFragile ||
80700b57cec5SDimitry Andric          (rewriteKind == RK_None &&
80710b57cec5SDimitry Andric           getToolChain().IsObjCNonFragileABIDefault()));
80720b57cec5SDimitry Andric     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
80730b57cec5SDimitry Andric                      options::OPT_fno_objc_nonfragile_abi,
80740b57cec5SDimitry Andric                      nonFragileABIIsDefault)) {
80750b57cec5SDimitry Andric // Determine the non-fragile ABI version to use.
80760b57cec5SDimitry Andric #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
80770b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 1;
80780b57cec5SDimitry Andric #else
80790b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 2;
80800b57cec5SDimitry Andric #endif
80810b57cec5SDimitry Andric 
80820b57cec5SDimitry Andric       if (Arg *abiArg =
80830b57cec5SDimitry Andric               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
80840b57cec5SDimitry Andric         StringRef value = abiArg->getValue();
80850b57cec5SDimitry Andric         if (value == "1")
80860b57cec5SDimitry Andric           nonFragileABIVersion = 1;
80870b57cec5SDimitry Andric         else if (value == "2")
80880b57cec5SDimitry Andric           nonFragileABIVersion = 2;
80890b57cec5SDimitry Andric         else
80900b57cec5SDimitry Andric           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
80910b57cec5SDimitry Andric               << value;
80920b57cec5SDimitry Andric       }
80930b57cec5SDimitry Andric 
80940b57cec5SDimitry Andric       objcABIVersion = 1 + nonFragileABIVersion;
80950b57cec5SDimitry Andric     } else {
80960b57cec5SDimitry Andric       objcABIVersion = 1;
80970b57cec5SDimitry Andric     }
80980b57cec5SDimitry Andric   }
80990b57cec5SDimitry Andric 
81000b57cec5SDimitry Andric   // We don't actually care about the ABI version other than whether
81010b57cec5SDimitry Andric   // it's non-fragile.
81020b57cec5SDimitry Andric   bool isNonFragile = objcABIVersion != 1;
81030b57cec5SDimitry Andric 
81040b57cec5SDimitry Andric   // If we have no runtime argument, ask the toolchain for its default runtime.
81050b57cec5SDimitry Andric   // However, the rewriter only really supports the Mac runtime, so assume that.
81060b57cec5SDimitry Andric   ObjCRuntime runtime;
81070b57cec5SDimitry Andric   if (!runtimeArg) {
81080b57cec5SDimitry Andric     switch (rewriteKind) {
81090b57cec5SDimitry Andric     case RK_None:
81100b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
81110b57cec5SDimitry Andric       break;
81120b57cec5SDimitry Andric     case RK_Fragile:
81130b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
81140b57cec5SDimitry Andric       break;
81150b57cec5SDimitry Andric     case RK_NonFragile:
81160b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
81170b57cec5SDimitry Andric       break;
81180b57cec5SDimitry Andric     }
81190b57cec5SDimitry Andric 
81200b57cec5SDimitry Andric     // -fnext-runtime
81210b57cec5SDimitry Andric   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
81220b57cec5SDimitry Andric     // On Darwin, make this use the default behavior for the toolchain.
81230b57cec5SDimitry Andric     if (getToolChain().getTriple().isOSDarwin()) {
81240b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
81250b57cec5SDimitry Andric 
81260b57cec5SDimitry Andric       // Otherwise, build for a generic macosx port.
81270b57cec5SDimitry Andric     } else {
81280b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
81290b57cec5SDimitry Andric     }
81300b57cec5SDimitry Andric 
81310b57cec5SDimitry Andric     // -fgnu-runtime
81320b57cec5SDimitry Andric   } else {
81330b57cec5SDimitry Andric     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
81340b57cec5SDimitry Andric     // Legacy behaviour is to target the gnustep runtime if we are in
81350b57cec5SDimitry Andric     // non-fragile mode or the GCC runtime in fragile mode.
81360b57cec5SDimitry Andric     if (isNonFragile)
81370b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
81380b57cec5SDimitry Andric     else
81390b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
81400b57cec5SDimitry Andric   }
81410b57cec5SDimitry Andric 
81425ffd83dbSDimitry Andric   if (llvm::any_of(inputs, [](const InputInfo &input) {
81435ffd83dbSDimitry Andric         return types::isObjC(input.getType());
81445ffd83dbSDimitry Andric       }))
81450b57cec5SDimitry Andric     cmdArgs.push_back(
81460b57cec5SDimitry Andric         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
81470b57cec5SDimitry Andric   return runtime;
81480b57cec5SDimitry Andric }
81490b57cec5SDimitry Andric 
maybeConsumeDash(const std::string & EH,size_t & I)81500b57cec5SDimitry Andric static bool maybeConsumeDash(const std::string &EH, size_t &I) {
81510b57cec5SDimitry Andric   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
81520b57cec5SDimitry Andric   I += HaveDash;
81530b57cec5SDimitry Andric   return !HaveDash;
81540b57cec5SDimitry Andric }
81550b57cec5SDimitry Andric 
81560b57cec5SDimitry Andric namespace {
81570b57cec5SDimitry Andric struct EHFlags {
81580b57cec5SDimitry Andric   bool Synch = false;
81590b57cec5SDimitry Andric   bool Asynch = false;
81600b57cec5SDimitry Andric   bool NoUnwindC = false;
81610b57cec5SDimitry Andric };
81620b57cec5SDimitry Andric } // end anonymous namespace
81630b57cec5SDimitry Andric 
81640b57cec5SDimitry Andric /// /EH controls whether to run destructor cleanups when exceptions are
81650b57cec5SDimitry Andric /// thrown.  There are three modifiers:
81660b57cec5SDimitry Andric /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
81670b57cec5SDimitry Andric /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
81680b57cec5SDimitry Andric ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
81690b57cec5SDimitry Andric /// - c: Assume that extern "C" functions are implicitly nounwind.
81700b57cec5SDimitry Andric /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args,bool isWindowsMSVC)81710fca6ea1SDimitry Andric static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
81720fca6ea1SDimitry Andric                                    bool isWindowsMSVC) {
81730b57cec5SDimitry Andric   EHFlags EH;
81740b57cec5SDimitry Andric 
81750b57cec5SDimitry Andric   std::vector<std::string> EHArgs =
81760b57cec5SDimitry Andric       Args.getAllArgValues(options::OPT__SLASH_EH);
81770fca6ea1SDimitry Andric   for (const auto &EHVal : EHArgs) {
81780b57cec5SDimitry Andric     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
81790b57cec5SDimitry Andric       switch (EHVal[I]) {
81800b57cec5SDimitry Andric       case 'a':
81810b57cec5SDimitry Andric         EH.Asynch = maybeConsumeDash(EHVal, I);
81820fca6ea1SDimitry Andric         if (EH.Asynch) {
81830fca6ea1SDimitry Andric           // Async exceptions are Windows MSVC only.
81840fca6ea1SDimitry Andric           if (!isWindowsMSVC) {
81850fca6ea1SDimitry Andric             EH.Asynch = false;
81860fca6ea1SDimitry Andric             D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
81870fca6ea1SDimitry Andric             continue;
81880fca6ea1SDimitry Andric           }
81890b57cec5SDimitry Andric           EH.Synch = false;
81900fca6ea1SDimitry Andric         }
81910b57cec5SDimitry Andric         continue;
81920b57cec5SDimitry Andric       case 'c':
81930b57cec5SDimitry Andric         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
81940b57cec5SDimitry Andric         continue;
81950b57cec5SDimitry Andric       case 's':
81960b57cec5SDimitry Andric         EH.Synch = maybeConsumeDash(EHVal, I);
81970b57cec5SDimitry Andric         if (EH.Synch)
81980b57cec5SDimitry Andric           EH.Asynch = false;
81990b57cec5SDimitry Andric         continue;
82000b57cec5SDimitry Andric       default:
82010b57cec5SDimitry Andric         break;
82020b57cec5SDimitry Andric       }
82030b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
82040b57cec5SDimitry Andric       break;
82050b57cec5SDimitry Andric     }
82060b57cec5SDimitry Andric   }
82070b57cec5SDimitry Andric   // The /GX, /GX- flags are only processed if there are not /EH flags.
82080b57cec5SDimitry Andric   // The default is that /GX is not specified.
82090b57cec5SDimitry Andric   if (EHArgs.empty() &&
82100b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
82110b57cec5SDimitry Andric                    /*Default=*/false)) {
82120b57cec5SDimitry Andric     EH.Synch = true;
82130b57cec5SDimitry Andric     EH.NoUnwindC = true;
82140b57cec5SDimitry Andric   }
82150b57cec5SDimitry Andric 
821681ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel)) {
821781ad6265SDimitry Andric     EH.Synch = false;
821881ad6265SDimitry Andric     EH.NoUnwindC = false;
821981ad6265SDimitry Andric     EH.Asynch = false;
822081ad6265SDimitry Andric   }
822181ad6265SDimitry Andric 
82220b57cec5SDimitry Andric   return EH;
82230b57cec5SDimitry Andric }
82240b57cec5SDimitry Andric 
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs) const82250b57cec5SDimitry Andric void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
82265f757f3fSDimitry Andric                            ArgStringList &CmdArgs) const {
82275ffd83dbSDimitry Andric   bool isNVPTX = getToolChain().getTriple().isNVPTX();
82280b57cec5SDimitry Andric 
82290fca6ea1SDimitry Andric   ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
82300b57cec5SDimitry Andric 
82315ffd83dbSDimitry Andric   if (Arg *ShowIncludes =
82325ffd83dbSDimitry Andric           Args.getLastArg(options::OPT__SLASH_showIncludes,
82335ffd83dbSDimitry Andric                           options::OPT__SLASH_showIncludes_user)) {
82345ffd83dbSDimitry Andric     CmdArgs.push_back("--show-includes");
82355ffd83dbSDimitry Andric     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
82365ffd83dbSDimitry Andric       CmdArgs.push_back("-sys-header-deps");
82375ffd83dbSDimitry Andric   }
82380b57cec5SDimitry Andric 
82390b57cec5SDimitry Andric   // This controls whether or not we emit RTTI data for polymorphic types.
82400b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
82410b57cec5SDimitry Andric                    /*Default=*/false))
82420b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti-data");
82430b57cec5SDimitry Andric 
82440b57cec5SDimitry Andric   // This controls whether or not we emit stack-protector instrumentation.
82450b57cec5SDimitry Andric   // In MSVC, Buffer Security Check (/GS) is on by default.
82465ffd83dbSDimitry Andric   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
82470b57cec5SDimitry Andric                                /*Default=*/true)) {
82480b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
82490b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
82500b57cec5SDimitry Andric   }
82510b57cec5SDimitry Andric 
82520b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
825381ad6265SDimitry Andric 
82540fca6ea1SDimitry Andric   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
82550fca6ea1SDimitry Andric   EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
82565ffd83dbSDimitry Andric   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
82570b57cec5SDimitry Andric     if (types::isCXX(InputType))
82580b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
82590b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
826006c3fb27SDimitry Andric     if (EH.Asynch)
826106c3fb27SDimitry Andric       CmdArgs.push_back("-fasync-exceptions");
82620b57cec5SDimitry Andric   }
82630b57cec5SDimitry Andric   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
82640b57cec5SDimitry Andric     CmdArgs.push_back("-fexternc-nounwind");
82650b57cec5SDimitry Andric 
82660b57cec5SDimitry Andric   // /EP should expand to -E -P.
82670b57cec5SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_EP)) {
82680b57cec5SDimitry Andric     CmdArgs.push_back("-E");
82690b57cec5SDimitry Andric     CmdArgs.push_back("-P");
82700b57cec5SDimitry Andric   }
82710b57cec5SDimitry Andric 
82720b57cec5SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
82730b57cec5SDimitry Andric                   options::OPT__SLASH_Zc_dllexportInlines,
82740b57cec5SDimitry Andric                   false)) {
82750b57cec5SDimitry Andric   CmdArgs.push_back("-fno-dllexport-inlines");
82760b57cec5SDimitry Andric  }
82770b57cec5SDimitry Andric 
827881ad6265SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
827981ad6265SDimitry Andric                   options::OPT__SLASH_Zc_wchar_t, false)) {
828081ad6265SDimitry Andric    CmdArgs.push_back("-fno-wchar");
828181ad6265SDimitry Andric  }
828281ad6265SDimitry Andric 
828381ad6265SDimitry Andric  if (Args.hasArg(options::OPT__SLASH_kernel)) {
828481ad6265SDimitry Andric    llvm::Triple::ArchType Arch = getToolChain().getArch();
828581ad6265SDimitry Andric    std::vector<std::string> Values =
828681ad6265SDimitry Andric        Args.getAllArgValues(options::OPT__SLASH_arch);
828781ad6265SDimitry Andric    if (!Values.empty()) {
828881ad6265SDimitry Andric      llvm::SmallSet<std::string, 4> SupportedArches;
828981ad6265SDimitry Andric      if (Arch == llvm::Triple::x86)
829081ad6265SDimitry Andric        SupportedArches.insert("IA32");
829181ad6265SDimitry Andric 
829281ad6265SDimitry Andric      for (auto &V : Values)
829381ad6265SDimitry Andric        if (!SupportedArches.contains(V))
829481ad6265SDimitry Andric          D.Diag(diag::err_drv_argument_not_allowed_with)
829581ad6265SDimitry Andric              << std::string("/arch:").append(V) << "/kernel";
829681ad6265SDimitry Andric    }
829781ad6265SDimitry Andric 
829881ad6265SDimitry Andric    CmdArgs.push_back("-fno-rtti");
829981ad6265SDimitry Andric    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
830081ad6265SDimitry Andric      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
830181ad6265SDimitry Andric                                                      << "/kernel";
830281ad6265SDimitry Andric  }
830381ad6265SDimitry Andric 
83040b57cec5SDimitry Andric   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
83050b57cec5SDimitry Andric   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
83060b57cec5SDimitry Andric   if (MostGeneralArg && BestCaseArg)
83070b57cec5SDimitry Andric     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
83080b57cec5SDimitry Andric         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
83090b57cec5SDimitry Andric 
83100b57cec5SDimitry Andric   if (MostGeneralArg) {
83110b57cec5SDimitry Andric     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
83120b57cec5SDimitry Andric     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
83130b57cec5SDimitry Andric     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
83140b57cec5SDimitry Andric 
83150b57cec5SDimitry Andric     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
83160b57cec5SDimitry Andric     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
83170b57cec5SDimitry Andric     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
83180b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
83190b57cec5SDimitry Andric           << FirstConflict->getAsString(Args)
83200b57cec5SDimitry Andric           << SecondConflict->getAsString(Args);
83210b57cec5SDimitry Andric 
83220b57cec5SDimitry Andric     if (SingleArg)
83230b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=single");
83240b57cec5SDimitry Andric     else if (MultipleArg)
83250b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=multiple");
83260b57cec5SDimitry Andric     else
83270b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=virtual");
83280b57cec5SDimitry Andric   }
83290b57cec5SDimitry Andric 
83305f757f3fSDimitry Andric   if (Args.hasArg(options::OPT_regcall4))
83315f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
83325f757f3fSDimitry Andric 
83330b57cec5SDimitry Andric   // Parse the default calling convention options.
83340b57cec5SDimitry Andric   if (Arg *CCArg =
83350b57cec5SDimitry Andric           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
83360b57cec5SDimitry Andric                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
83370b57cec5SDimitry Andric                           options::OPT__SLASH_Gregcall)) {
83380b57cec5SDimitry Andric     unsigned DCCOptId = CCArg->getOption().getID();
83390b57cec5SDimitry Andric     const char *DCCFlag = nullptr;
83405ffd83dbSDimitry Andric     bool ArchSupported = !isNVPTX;
83410b57cec5SDimitry Andric     llvm::Triple::ArchType Arch = getToolChain().getArch();
83420b57cec5SDimitry Andric     switch (DCCOptId) {
83430b57cec5SDimitry Andric     case options::OPT__SLASH_Gd:
83440b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=cdecl";
83450b57cec5SDimitry Andric       break;
83460b57cec5SDimitry Andric     case options::OPT__SLASH_Gr:
83470b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
83480b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=fastcall";
83490b57cec5SDimitry Andric       break;
83500b57cec5SDimitry Andric     case options::OPT__SLASH_Gz:
83510b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
83520b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=stdcall";
83530b57cec5SDimitry Andric       break;
83540b57cec5SDimitry Andric     case options::OPT__SLASH_Gv:
83550b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
83560b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=vectorcall";
83570b57cec5SDimitry Andric       break;
83580b57cec5SDimitry Andric     case options::OPT__SLASH_Gregcall:
83590b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
83600b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=regcall";
83610b57cec5SDimitry Andric       break;
83620b57cec5SDimitry Andric     }
83630b57cec5SDimitry Andric 
83640b57cec5SDimitry Andric     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
83650b57cec5SDimitry Andric     if (ArchSupported && DCCFlag)
83660b57cec5SDimitry Andric       CmdArgs.push_back(DCCFlag);
83670b57cec5SDimitry Andric   }
83680b57cec5SDimitry Andric 
83695f757f3fSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_Gregcall4))
83705f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
83715f757f3fSDimitry Andric 
83720b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
83730b57cec5SDimitry Andric 
83740b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
83750b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
83760b57cec5SDimitry Andric     CmdArgs.push_back("msvc");
83770b57cec5SDimitry Andric   }
83780b57cec5SDimitry Andric 
837981ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel))
838081ad6265SDimitry Andric     CmdArgs.push_back("-fms-kernel");
838181ad6265SDimitry Andric 
8382a324c340SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8383480093f4SDimitry Andric     StringRef GuardArgs = A->getValue();
8384fe6060f1SDimitry Andric     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8385fe6060f1SDimitry Andric     // "ehcont-".
8386fe6060f1SDimitry Andric     if (GuardArgs.equals_insensitive("cf")) {
8387480093f4SDimitry Andric       // Emit CFG instrumentation and the table of address-taken functions.
83880b57cec5SDimitry Andric       CmdArgs.push_back("-cfguard");
8389fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8390480093f4SDimitry Andric       // Emit only the table of address-taken functions.
8391480093f4SDimitry Andric       CmdArgs.push_back("-cfguard-no-checks");
8392fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("ehcont")) {
8393fe6060f1SDimitry Andric       // Emit EH continuation table.
8394fe6060f1SDimitry Andric       CmdArgs.push_back("-ehcontguard");
8395fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf-") ||
8396fe6060f1SDimitry Andric                GuardArgs.equals_insensitive("ehcont-")) {
8397480093f4SDimitry Andric       // Do nothing, but we might want to emit a security warning in future.
8398480093f4SDimitry Andric     } else {
8399480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8400480093f4SDimitry Andric     }
84012efbaac7SDimitry Andric     A->claim();
84020b57cec5SDimitry Andric   }
84030b57cec5SDimitry Andric }
84040b57cec5SDimitry Andric 
getBaseInputName(const ArgList & Args,const InputInfo & Input)84050b57cec5SDimitry Andric const char *Clang::getBaseInputName(const ArgList &Args,
84060b57cec5SDimitry Andric                                     const InputInfo &Input) {
84070b57cec5SDimitry Andric   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
84080b57cec5SDimitry Andric }
84090b57cec5SDimitry Andric 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)84100b57cec5SDimitry Andric const char *Clang::getBaseInputStem(const ArgList &Args,
84110b57cec5SDimitry Andric                                     const InputInfoList &Inputs) {
84120b57cec5SDimitry Andric   const char *Str = getBaseInputName(Args, Inputs[0]);
84130b57cec5SDimitry Andric 
84140b57cec5SDimitry Andric   if (const char *End = strrchr(Str, '.'))
84150b57cec5SDimitry Andric     return Args.MakeArgString(std::string(Str, End));
84160b57cec5SDimitry Andric 
84170b57cec5SDimitry Andric   return Str;
84180b57cec5SDimitry Andric }
84190b57cec5SDimitry Andric 
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)84200b57cec5SDimitry Andric const char *Clang::getDependencyFileName(const ArgList &Args,
84210b57cec5SDimitry Andric                                          const InputInfoList &Inputs) {
84220b57cec5SDimitry Andric   // FIXME: Think about this more.
84230b57cec5SDimitry Andric 
84240b57cec5SDimitry Andric   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8425a7dea167SDimitry Andric     SmallString<128> OutputFilename(OutputOpt->getValue());
8426a7dea167SDimitry Andric     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8427a7dea167SDimitry Andric     return Args.MakeArgString(OutputFilename);
84280b57cec5SDimitry Andric   }
8429a7dea167SDimitry Andric 
8430a7dea167SDimitry Andric   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
84310b57cec5SDimitry Andric }
84320b57cec5SDimitry Andric 
84330b57cec5SDimitry Andric // Begin ClangAs
84340b57cec5SDimitry Andric 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const84350b57cec5SDimitry Andric void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
84360b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
84370b57cec5SDimitry Andric   StringRef CPUName;
84380b57cec5SDimitry Andric   StringRef ABIName;
84390b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
84400b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
84410b57cec5SDimitry Andric 
84420b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
84430b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
84440b57cec5SDimitry Andric }
84450b57cec5SDimitry Andric 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const84460b57cec5SDimitry Andric void ClangAs::AddX86TargetArgs(const ArgList &Args,
84470b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
84485ffd83dbSDimitry Andric   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
84495ffd83dbSDimitry Andric                         /*IsLTO=*/false);
8450480093f4SDimitry Andric 
84510b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
84520b57cec5SDimitry Andric     StringRef Value = A->getValue();
84530b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
84540b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
84550b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
84560b57cec5SDimitry Andric     } else {
84570b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8458bdd1243dSDimitry Andric           << A->getSpelling() << Value;
84590b57cec5SDimitry Andric     }
84600b57cec5SDimitry Andric   }
84610b57cec5SDimitry Andric }
84620b57cec5SDimitry Andric 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const846306c3fb27SDimitry Andric void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
846406c3fb27SDimitry Andric                                      ArgStringList &CmdArgs) const {
846506c3fb27SDimitry Andric   CmdArgs.push_back("-target-abi");
846606c3fb27SDimitry Andric   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
846706c3fb27SDimitry Andric                                                getToolChain().getTriple())
846806c3fb27SDimitry Andric                         .data());
846906c3fb27SDimitry Andric }
847006c3fb27SDimitry Andric 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const84710b57cec5SDimitry Andric void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
84720b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
84730b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
84740b57cec5SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
84750b57cec5SDimitry Andric 
84760b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
84770b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
847806c3fb27SDimitry Andric 
847906c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_mdefault_build_attributes,
848006c3fb27SDimitry Andric                    options::OPT_mno_default_build_attributes, true)) {
848106c3fb27SDimitry Andric       CmdArgs.push_back("-mllvm");
848206c3fb27SDimitry Andric       CmdArgs.push_back("-riscv-add-build-attributes");
848306c3fb27SDimitry Andric   }
84840b57cec5SDimitry Andric }
84850b57cec5SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const84860b57cec5SDimitry Andric void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
84870b57cec5SDimitry Andric                            const InputInfo &Output, const InputInfoList &Inputs,
84880b57cec5SDimitry Andric                            const ArgList &Args,
84890b57cec5SDimitry Andric                            const char *LinkingOutput) const {
84900b57cec5SDimitry Andric   ArgStringList CmdArgs;
84910b57cec5SDimitry Andric 
84920b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
84930b57cec5SDimitry Andric   const InputInfo &Input = Inputs[0];
84940b57cec5SDimitry Andric 
84950b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
84960b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
84970b57cec5SDimitry Andric   const auto &D = getToolChain().getDriver();
84980b57cec5SDimitry Andric 
84990b57cec5SDimitry Andric   // Don't warn about "clang -w -c foo.s"
85000b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_w);
85010b57cec5SDimitry Andric   // and "clang -emit-llvm -c foo.s"
85020b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
85030b57cec5SDimitry Andric 
85040b57cec5SDimitry Andric   claimNoWarnArgs(Args);
85050b57cec5SDimitry Andric 
85060b57cec5SDimitry Andric   // Invoke ourselves in -cc1as mode.
85070b57cec5SDimitry Andric   //
85080b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
85090b57cec5SDimitry Andric   CmdArgs.push_back("-cc1as");
85100b57cec5SDimitry Andric 
85110b57cec5SDimitry Andric   // Add the "effective" target triple.
85120b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
85130b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
8514bdd1243dSDimitry Andric 
8515bdd1243dSDimitry Andric   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
85160b57cec5SDimitry Andric 
85170b57cec5SDimitry Andric   // Set the output mode, we currently only expect to be used as a real
85180b57cec5SDimitry Andric   // assembler.
85190b57cec5SDimitry Andric   CmdArgs.push_back("-filetype");
85200b57cec5SDimitry Andric   CmdArgs.push_back("obj");
85210b57cec5SDimitry Andric 
85220b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
85230b57cec5SDimitry Andric   // -save-temps or preprocessed assembly.
85240b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
85250b57cec5SDimitry Andric   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
85260b57cec5SDimitry Andric 
85270b57cec5SDimitry Andric   // Add the target cpu
8528349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
85290b57cec5SDimitry Andric   if (!CPU.empty()) {
85300b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
85310b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
85320b57cec5SDimitry Andric   }
85330b57cec5SDimitry Andric 
85340b57cec5SDimitry Andric   // Add the target features
85355ffd83dbSDimitry Andric   getTargetFeatures(D, Triple, Args, CmdArgs, true);
85360b57cec5SDimitry Andric 
85370b57cec5SDimitry Andric   // Ignore explicit -force_cpusubtype_ALL option.
85380b57cec5SDimitry Andric   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
85390b57cec5SDimitry Andric 
85400b57cec5SDimitry Andric   // Pass along any -I options so we get proper .include search paths.
85410b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
85420b57cec5SDimitry Andric 
85430fca6ea1SDimitry Andric   // Pass along any --embed-dir or similar options so we get proper embed paths.
85440fca6ea1SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
85450fca6ea1SDimitry Andric 
85460b57cec5SDimitry Andric   // Determine the original source input.
85470eae32dcSDimitry Andric   auto FindSource = [](const Action *S) -> const Action * {
85480eae32dcSDimitry Andric     while (S->getKind() != Action::InputClass) {
85490eae32dcSDimitry Andric       assert(!S->getInputs().empty() && "unexpected root action!");
85500eae32dcSDimitry Andric       S = S->getInputs()[0];
85510b57cec5SDimitry Andric     }
85520eae32dcSDimitry Andric     return S;
85530eae32dcSDimitry Andric   };
85540eae32dcSDimitry Andric   const Action *SourceAction = FindSource(&JA);
85550b57cec5SDimitry Andric 
85560b57cec5SDimitry Andric   // Forward -g and handle debug info related flags, assuming we are dealing
85570b57cec5SDimitry Andric   // with an actual assembly file.
85580b57cec5SDimitry Andric   bool WantDebug = false;
85590b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_Group);
8560fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
85610b57cec5SDimitry Andric     WantDebug = !A->getOption().matches(options::OPT_g0) &&
85620b57cec5SDimitry Andric                 !A->getOption().matches(options::OPT_ggdb0);
8563480093f4SDimitry Andric 
8564*6e516c87SDimitry Andric   // If a -gdwarf argument appeared, remember it.
8565*6e516c87SDimitry Andric   bool EmitDwarf = false;
8566*6e516c87SDimitry Andric   if (const Arg *A = getDwarfNArg(Args))
8567*6e516c87SDimitry Andric     EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
8568*6e516c87SDimitry Andric 
8569*6e516c87SDimitry Andric   bool EmitCodeView = false;
8570*6e516c87SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
8571*6e516c87SDimitry Andric     EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
8572*6e516c87SDimitry Andric 
8573*6e516c87SDimitry Andric   // If the user asked for debug info but did not explicitly specify -gcodeview
8574*6e516c87SDimitry Andric   // or -gdwarf, ask the toolchain for the default format.
8575*6e516c87SDimitry Andric   if (!EmitCodeView && !EmitDwarf && WantDebug) {
8576*6e516c87SDimitry Andric     switch (getToolChain().getDefaultDebugFormat()) {
8577*6e516c87SDimitry Andric     case llvm::codegenoptions::DIF_CodeView:
8578*6e516c87SDimitry Andric       EmitCodeView = true;
8579*6e516c87SDimitry Andric       break;
8580*6e516c87SDimitry Andric     case llvm::codegenoptions::DIF_DWARF:
8581*6e516c87SDimitry Andric       EmitDwarf = true;
8582*6e516c87SDimitry Andric       break;
8583*6e516c87SDimitry Andric     }
8584*6e516c87SDimitry Andric   }
8585*6e516c87SDimitry Andric 
8586*6e516c87SDimitry Andric   // If the arguments don't imply DWARF, don't emit any debug info here.
8587*6e516c87SDimitry Andric   if (!EmitDwarf)
8588*6e516c87SDimitry Andric     WantDebug = false;
8589*6e516c87SDimitry Andric 
859006c3fb27SDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
859106c3fb27SDimitry Andric       llvm::codegenoptions::NoDebugInfo;
85920b57cec5SDimitry Andric 
85930eae32dcSDimitry Andric   // Add the -fdebug-compilation-dir flag if needed.
85940eae32dcSDimitry Andric   const char *DebugCompilationDir =
85950eae32dcSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
85960eae32dcSDimitry Andric 
85970b57cec5SDimitry Andric   if (SourceAction->getType() == types::TY_Asm ||
85980b57cec5SDimitry Andric       SourceAction->getType() == types::TY_PP_Asm) {
85990b57cec5SDimitry Andric     // You might think that it would be ok to set DebugInfoKind outside of
86000b57cec5SDimitry Andric     // the guard for source type, however there is a test which asserts
86010b57cec5SDimitry Andric     // that some assembler invocation receives no -debug-info-kind,
86020b57cec5SDimitry Andric     // and it's not clear whether that test is just overly restrictive.
860306c3fb27SDimitry Andric     DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
860406c3fb27SDimitry Andric                                : llvm::codegenoptions::NoDebugInfo);
86050b57cec5SDimitry Andric 
860681ad6265SDimitry Andric     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
860781ad6265SDimitry Andric                          CmdArgs);
86080b57cec5SDimitry Andric 
86090b57cec5SDimitry Andric     // Set the AT_producer to the clang version when using the integrated
86100b57cec5SDimitry Andric     // assembler on assembly source files.
86110b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-producer");
86120b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
86130b57cec5SDimitry Andric 
86140b57cec5SDimitry Andric     // And pass along -I options
86150b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_I);
86160b57cec5SDimitry Andric   }
8617bdd1243dSDimitry Andric   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
86180b57cec5SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
86190b57cec5SDimitry Andric                           llvm::DebuggerKind::Default);
8620fe6060f1SDimitry Andric   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
86210b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
86220b57cec5SDimitry Andric 
86230b57cec5SDimitry Andric   // Handle -fPIC et al -- the relocation-model affects the assembler
86240b57cec5SDimitry Andric   // for some targets.
86250b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
86260b57cec5SDimitry Andric   unsigned PICLevel;
86270b57cec5SDimitry Andric   bool IsPIE;
86280b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
86290b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
86300b57cec5SDimitry Andric 
86310b57cec5SDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
86320b57cec5SDimitry Andric   if (RMName) {
86330b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
86340b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
86350b57cec5SDimitry Andric   }
86360b57cec5SDimitry Andric 
86370b57cec5SDimitry Andric   // Optionally embed the -cc1as level arguments into the debug info, for build
86380b57cec5SDimitry Andric   // analysis.
86390b57cec5SDimitry Andric   if (getToolChain().UseDwarfDebugFlags()) {
86400b57cec5SDimitry Andric     ArgStringList OriginalArgs;
86410b57cec5SDimitry Andric     for (const auto &Arg : Args)
86420b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
86430b57cec5SDimitry Andric 
86440b57cec5SDimitry Andric     SmallString<256> Flags;
86450b57cec5SDimitry Andric     const char *Exec = getToolChain().getDriver().getClangProgramPath();
86465ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
86470b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
86480b57cec5SDimitry Andric       SmallString<128> EscapedArg;
86490b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
86500b57cec5SDimitry Andric       Flags += " ";
86510b57cec5SDimitry Andric       Flags += EscapedArg;
86520b57cec5SDimitry Andric     }
86530b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-flags");
86540b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Flags));
86550b57cec5SDimitry Andric   }
86560b57cec5SDimitry Andric 
86570b57cec5SDimitry Andric   // FIXME: Add -static support, once we have it.
86580b57cec5SDimitry Andric 
86590b57cec5SDimitry Andric   // Add target specific flags.
86600b57cec5SDimitry Andric   switch (getToolChain().getArch()) {
86610b57cec5SDimitry Andric   default:
86620b57cec5SDimitry Andric     break;
86630b57cec5SDimitry Andric 
86640b57cec5SDimitry Andric   case llvm::Triple::mips:
86650b57cec5SDimitry Andric   case llvm::Triple::mipsel:
86660b57cec5SDimitry Andric   case llvm::Triple::mips64:
86670b57cec5SDimitry Andric   case llvm::Triple::mips64el:
86680b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
86690b57cec5SDimitry Andric     break;
86700b57cec5SDimitry Andric 
86710b57cec5SDimitry Andric   case llvm::Triple::x86:
86720b57cec5SDimitry Andric   case llvm::Triple::x86_64:
86730b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
86740b57cec5SDimitry Andric     break;
86750b57cec5SDimitry Andric 
86760b57cec5SDimitry Andric   case llvm::Triple::arm:
86770b57cec5SDimitry Andric   case llvm::Triple::armeb:
86780b57cec5SDimitry Andric   case llvm::Triple::thumb:
86790b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
86800b57cec5SDimitry Andric     // This isn't in AddARMTargetArgs because we want to do this for assembly
86810b57cec5SDimitry Andric     // only, not C/C++.
86820b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
86830b57cec5SDimitry Andric                      options::OPT_mno_default_build_attributes, true)) {
86840b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
86850b57cec5SDimitry Andric         CmdArgs.push_back("-arm-add-build-attributes");
86860b57cec5SDimitry Andric     }
86870b57cec5SDimitry Andric     break;
86880b57cec5SDimitry Andric 
8689e8d8bef9SDimitry Andric   case llvm::Triple::aarch64:
8690e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_32:
8691e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_be:
8692e8d8bef9SDimitry Andric     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8693e8d8bef9SDimitry Andric       CmdArgs.push_back("-mllvm");
8694e8d8bef9SDimitry Andric       CmdArgs.push_back("-aarch64-mark-bti-property");
8695e8d8bef9SDimitry Andric     }
8696e8d8bef9SDimitry Andric     break;
8697e8d8bef9SDimitry Andric 
869806c3fb27SDimitry Andric   case llvm::Triple::loongarch32:
869906c3fb27SDimitry Andric   case llvm::Triple::loongarch64:
870006c3fb27SDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
870106c3fb27SDimitry Andric     break;
870206c3fb27SDimitry Andric 
87030b57cec5SDimitry Andric   case llvm::Triple::riscv32:
87040b57cec5SDimitry Andric   case llvm::Triple::riscv64:
87050b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
87060b57cec5SDimitry Andric     break;
87070fca6ea1SDimitry Andric 
87080fca6ea1SDimitry Andric   case llvm::Triple::hexagon:
87090fca6ea1SDimitry Andric     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
87100fca6ea1SDimitry Andric                      options::OPT_mno_default_build_attributes, true)) {
87110fca6ea1SDimitry Andric       CmdArgs.push_back("-mllvm");
87120fca6ea1SDimitry Andric       CmdArgs.push_back("-hexagon-add-build-attributes");
87130fca6ea1SDimitry Andric     }
87140fca6ea1SDimitry Andric     break;
87150b57cec5SDimitry Andric   }
87160b57cec5SDimitry Andric 
87170b57cec5SDimitry Andric   // Consume all the warning flags. Usually this would be handled more
87180b57cec5SDimitry Andric   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
87190b57cec5SDimitry Andric   // doesn't handle that so rather than warning about unused flags that are
87200b57cec5SDimitry Andric   // actually used, we'll lie by omission instead.
87210b57cec5SDimitry Andric   // FIXME: Stop lying and consume only the appropriate driver flags
87220b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_W_Group);
87230b57cec5SDimitry Andric 
87240b57cec5SDimitry Andric   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
87250b57cec5SDimitry Andric                                     getToolChain().getDriver());
87260b57cec5SDimitry Andric 
87270b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
87280b57cec5SDimitry Andric 
872906c3fb27SDimitry Andric   if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
87300eae32dcSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
87310eae32dcSDimitry Andric                        Output.getFilename());
87320eae32dcSDimitry Andric 
87330eae32dcSDimitry Andric   // Fixup any previous commands that use -object-file-name because when we
87340eae32dcSDimitry Andric   // generated them, the final .obj name wasn't yet known.
87350eae32dcSDimitry Andric   for (Command &J : C.getJobs()) {
87360eae32dcSDimitry Andric     if (SourceAction != FindSource(&J.getSource()))
87370eae32dcSDimitry Andric       continue;
87380eae32dcSDimitry Andric     auto &JArgs = J.getArguments();
87390eae32dcSDimitry Andric     for (unsigned I = 0; I < JArgs.size(); ++I) {
87405f757f3fSDimitry Andric       if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
87410eae32dcSDimitry Andric           Output.isFilename()) {
87420eae32dcSDimitry Andric        ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
87430eae32dcSDimitry Andric        addDebugObjectName(Args, NewArgs, DebugCompilationDir,
87440eae32dcSDimitry Andric                           Output.getFilename());
87450eae32dcSDimitry Andric        NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
87460eae32dcSDimitry Andric        J.replaceArguments(NewArgs);
87470eae32dcSDimitry Andric        break;
87480eae32dcSDimitry Andric       }
87490eae32dcSDimitry Andric     }
87500eae32dcSDimitry Andric   }
87510eae32dcSDimitry Andric 
87520b57cec5SDimitry Andric   assert(Output.isFilename() && "Unexpected lipo output.");
87530b57cec5SDimitry Andric   CmdArgs.push_back("-o");
87540b57cec5SDimitry Andric   CmdArgs.push_back(Output.getFilename());
87550b57cec5SDimitry Andric 
87560b57cec5SDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
87570b57cec5SDimitry Andric   Arg *A;
87580b57cec5SDimitry Andric   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
87590b57cec5SDimitry Andric       T.isOSBinFormatELF()) {
87600b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-output");
8761e8d8bef9SDimitry Andric     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
87620b57cec5SDimitry Andric   }
87630b57cec5SDimitry Andric 
8764e8d8bef9SDimitry Andric   if (Triple.isAMDGPU())
876581ad6265SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8766e8d8bef9SDimitry Andric 
87670b57cec5SDimitry Andric   assert(Input.isFilename() && "Invalid input.");
87680b57cec5SDimitry Andric   CmdArgs.push_back(Input.getFilename());
87690b57cec5SDimitry Andric 
87700b57cec5SDimitry Andric   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8771e8d8bef9SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
8772e8d8bef9SDimitry Andric     // Invoke cc1as directly in this process.
877306c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
877406c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
877506c3fb27SDimitry Andric         Output, D.getPrependArg()));
8776e8d8bef9SDimitry Andric   } else {
877706c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
877806c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
877906c3fb27SDimitry Andric         Output, D.getPrependArg()));
8780e8d8bef9SDimitry Andric   }
87810b57cec5SDimitry Andric }
87820b57cec5SDimitry Andric 
87830b57cec5SDimitry Andric // Begin OffloadBundler
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const87840b57cec5SDimitry Andric void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
87850b57cec5SDimitry Andric                                   const InputInfo &Output,
87860b57cec5SDimitry Andric                                   const InputInfoList &Inputs,
87870b57cec5SDimitry Andric                                   const llvm::opt::ArgList &TCArgs,
87880b57cec5SDimitry Andric                                   const char *LinkingOutput) const {
87890b57cec5SDimitry Andric   // The version with only one output is expected to refer to a bundling job.
87900b57cec5SDimitry Andric   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
87910b57cec5SDimitry Andric 
87920b57cec5SDimitry Andric   // The bundling command looks like this:
87930b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
87940b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
879581ad6265SDimitry Andric   //   -output=output_file
879681ad6265SDimitry Andric   //   -input=unbundle_file_host
879781ad6265SDimitry Andric   //   -input=unbundle_file_tgt1
879881ad6265SDimitry Andric   //   -input=unbundle_file_tgt2
87990b57cec5SDimitry Andric 
88000b57cec5SDimitry Andric   ArgStringList CmdArgs;
88010b57cec5SDimitry Andric 
88020b57cec5SDimitry Andric   // Get the type.
88030b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
88040b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
88050b57cec5SDimitry Andric 
88060b57cec5SDimitry Andric   assert(JA.getInputs().size() == Inputs.size() &&
88070b57cec5SDimitry Andric          "Not have inputs for all dependence actions??");
88080b57cec5SDimitry Andric 
88090b57cec5SDimitry Andric   // Get the targets.
88100b57cec5SDimitry Andric   SmallString<128> Triples;
88110b57cec5SDimitry Andric   Triples += "-targets=";
88120b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
88130b57cec5SDimitry Andric     if (I)
88140b57cec5SDimitry Andric       Triples += ',';
88150b57cec5SDimitry Andric 
88160b57cec5SDimitry Andric     // Find ToolChain for this input.
88170b57cec5SDimitry Andric     Action::OffloadKind CurKind = Action::OFK_Host;
88180b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
88190b57cec5SDimitry Andric     const Action *CurDep = JA.getInputs()[I];
88200b57cec5SDimitry Andric 
88210b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
88220b57cec5SDimitry Andric       CurTC = nullptr;
88230b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
88240b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
88250b57cec5SDimitry Andric         CurKind = A->getOffloadingDeviceKind();
88260b57cec5SDimitry Andric         CurTC = TC;
88270b57cec5SDimitry Andric       });
88280b57cec5SDimitry Andric     }
88290b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(CurKind);
8830349cc55cSDimitry Andric     Triples += '-';
8831349cc55cSDimitry Andric     Triples += CurTC->getTriple().normalize();
8832349cc55cSDimitry Andric     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
88330eae32dcSDimitry Andric         !StringRef(CurDep->getOffloadingArch()).empty()) {
8834349cc55cSDimitry Andric       Triples += '-';
88350b57cec5SDimitry Andric       Triples += CurDep->getOffloadingArch();
88360b57cec5SDimitry Andric     }
8837349cc55cSDimitry Andric 
8838349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8839349cc55cSDimitry Andric     //       with each toolchain.
8840349cc55cSDimitry Andric     StringRef GPUArchName;
8841349cc55cSDimitry Andric     if (CurKind == Action::OFK_OpenMP) {
8842349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8843349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8844349cc55cSDimitry Andric         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
884506c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8846349cc55cSDimitry Andric         if (Arch) {
8847349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8848349cc55cSDimitry Andric           Triples += "-";
8849349cc55cSDimitry Andric           break;
8850349cc55cSDimitry Andric         }
8851349cc55cSDimitry Andric       }
8852349cc55cSDimitry Andric       Triples += GPUArchName.str();
8853349cc55cSDimitry Andric     }
88540b57cec5SDimitry Andric   }
88550b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
88560b57cec5SDimitry Andric 
88570b57cec5SDimitry Andric   // Get bundled file command.
88580b57cec5SDimitry Andric   CmdArgs.push_back(
885981ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
88600b57cec5SDimitry Andric 
88610b57cec5SDimitry Andric   // Get unbundled files command.
88620b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
886381ad6265SDimitry Andric     SmallString<128> UB;
886481ad6265SDimitry Andric     UB += "-input=";
88650b57cec5SDimitry Andric 
88660b57cec5SDimitry Andric     // Find ToolChain for this input.
88670b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
88680b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
88690b57cec5SDimitry Andric       CurTC = nullptr;
88700b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
88710b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
88720b57cec5SDimitry Andric         CurTC = TC;
88730b57cec5SDimitry Andric       });
88746e75b2fbSDimitry Andric       UB += C.addTempFile(
88756e75b2fbSDimitry Andric           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
88766e75b2fbSDimitry Andric     } else {
88770b57cec5SDimitry Andric       UB += CurTC->getInputFilename(Inputs[I]);
88780b57cec5SDimitry Andric     }
88790b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
888081ad6265SDimitry Andric   }
88810fca6ea1SDimitry Andric   addOffloadCompressArgs(TCArgs, CmdArgs);
88820b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8883a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
88845ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
88850b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8886bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Output));
88870b57cec5SDimitry Andric }
88880b57cec5SDimitry Andric 
ConstructJobMultipleOutputs(Compilation & C,const JobAction & JA,const InputInfoList & Outputs,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const88890b57cec5SDimitry Andric void OffloadBundler::ConstructJobMultipleOutputs(
88900b57cec5SDimitry Andric     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
88910b57cec5SDimitry Andric     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
88920b57cec5SDimitry Andric     const char *LinkingOutput) const {
88930b57cec5SDimitry Andric   // The version with multiple outputs is expected to refer to a unbundling job.
88940b57cec5SDimitry Andric   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
88950b57cec5SDimitry Andric 
88960b57cec5SDimitry Andric   // The unbundling command looks like this:
88970b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
88980b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
889981ad6265SDimitry Andric   //   -input=input_file
890081ad6265SDimitry Andric   //   -output=unbundle_file_host
890181ad6265SDimitry Andric   //   -output=unbundle_file_tgt1
890281ad6265SDimitry Andric   //   -output=unbundle_file_tgt2
89030b57cec5SDimitry Andric   //   -unbundle
89040b57cec5SDimitry Andric 
89050b57cec5SDimitry Andric   ArgStringList CmdArgs;
89060b57cec5SDimitry Andric 
89070b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
89080b57cec5SDimitry Andric   InputInfo Input = Inputs.front();
89090b57cec5SDimitry Andric 
89100b57cec5SDimitry Andric   // Get the type.
89110b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
89120b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
89130b57cec5SDimitry Andric 
89140b57cec5SDimitry Andric   // Get the targets.
89150b57cec5SDimitry Andric   SmallString<128> Triples;
89160b57cec5SDimitry Andric   Triples += "-targets=";
89170b57cec5SDimitry Andric   auto DepInfo = UA.getDependentActionsInfo();
89180b57cec5SDimitry Andric   for (unsigned I = 0; I < DepInfo.size(); ++I) {
89190b57cec5SDimitry Andric     if (I)
89200b57cec5SDimitry Andric       Triples += ',';
89210b57cec5SDimitry Andric 
89220b57cec5SDimitry Andric     auto &Dep = DepInfo[I];
89230b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8924349cc55cSDimitry Andric     Triples += '-';
8925349cc55cSDimitry Andric     Triples += Dep.DependentToolChain->getTriple().normalize();
8926349cc55cSDimitry Andric     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8927349cc55cSDimitry Andric          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8928349cc55cSDimitry Andric         !Dep.DependentBoundArch.empty()) {
8929349cc55cSDimitry Andric       Triples += '-';
89300b57cec5SDimitry Andric       Triples += Dep.DependentBoundArch;
89310b57cec5SDimitry Andric     }
8932349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8933349cc55cSDimitry Andric     //       with each toolchain.
8934349cc55cSDimitry Andric     StringRef GPUArchName;
8935349cc55cSDimitry Andric     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8936349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8937349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8938349cc55cSDimitry Andric         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
893906c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8940349cc55cSDimitry Andric         if (Arch) {
8941349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8942349cc55cSDimitry Andric           Triples += "-";
8943349cc55cSDimitry Andric           break;
8944349cc55cSDimitry Andric         }
8945349cc55cSDimitry Andric       }
8946349cc55cSDimitry Andric       Triples += GPUArchName.str();
8947349cc55cSDimitry Andric     }
89480b57cec5SDimitry Andric   }
89490b57cec5SDimitry Andric 
89500b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
89510b57cec5SDimitry Andric 
89520b57cec5SDimitry Andric   // Get bundled file command.
89530b57cec5SDimitry Andric   CmdArgs.push_back(
895481ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
89550b57cec5SDimitry Andric 
89560b57cec5SDimitry Andric   // Get unbundled files command.
89570b57cec5SDimitry Andric   for (unsigned I = 0; I < Outputs.size(); ++I) {
895881ad6265SDimitry Andric     SmallString<128> UB;
895981ad6265SDimitry Andric     UB += "-output=";
89600b57cec5SDimitry Andric     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
89610b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
896281ad6265SDimitry Andric   }
89630b57cec5SDimitry Andric   CmdArgs.push_back("-unbundle");
8964e8d8bef9SDimitry Andric   CmdArgs.push_back("-allow-missing-bundles");
89655f757f3fSDimitry Andric   if (TCArgs.hasArg(options::OPT_v))
89665f757f3fSDimitry Andric     CmdArgs.push_back("-verbose");
89670b57cec5SDimitry Andric 
89680b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8969a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
89705ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
89710b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8972bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Outputs));
8973a7dea167SDimitry Andric }
89741fd87a68SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & Args,const char * LinkingOutput) const897581ad6265SDimitry Andric void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
897681ad6265SDimitry Andric                                    const InputInfo &Output,
897781ad6265SDimitry Andric                                    const InputInfoList &Inputs,
897881ad6265SDimitry Andric                                    const llvm::opt::ArgList &Args,
897981ad6265SDimitry Andric                                    const char *LinkingOutput) const {
898081ad6265SDimitry Andric   ArgStringList CmdArgs;
898181ad6265SDimitry Andric 
898281ad6265SDimitry Andric   // Add the output file name.
898381ad6265SDimitry Andric   assert(Output.isFilename() && "Invalid output.");
898481ad6265SDimitry Andric   CmdArgs.push_back("-o");
898581ad6265SDimitry Andric   CmdArgs.push_back(Output.getFilename());
898681ad6265SDimitry Andric 
898781ad6265SDimitry Andric   // Create the inputs to bundle the needed metadata.
898881ad6265SDimitry Andric   for (const InputInfo &Input : Inputs) {
898981ad6265SDimitry Andric     const Action *OffloadAction = Input.getAction();
899081ad6265SDimitry Andric     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
899181ad6265SDimitry Andric     const ArgList &TCArgs =
899281ad6265SDimitry Andric         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
899381ad6265SDimitry Andric                               OffloadAction->getOffloadingDeviceKind());
899481ad6265SDimitry Andric     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
899506c3fb27SDimitry Andric     StringRef Arch = OffloadAction->getOffloadingArch()
899681ad6265SDimitry Andric                          ? OffloadAction->getOffloadingArch()
899781ad6265SDimitry Andric                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
899881ad6265SDimitry Andric     StringRef Kind =
899981ad6265SDimitry Andric       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
900081ad6265SDimitry Andric 
900181ad6265SDimitry Andric     ArgStringList Features;
900281ad6265SDimitry Andric     SmallVector<StringRef> FeatureArgs;
9003753f127fSDimitry Andric     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9004753f127fSDimitry Andric                       false);
900581ad6265SDimitry Andric     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
90065f757f3fSDimitry Andric                   [](StringRef Arg) { return !Arg.starts_with("-target"); });
900781ad6265SDimitry Andric 
900806c3fb27SDimitry Andric     if (TC->getTriple().isAMDGPU()) {
900906c3fb27SDimitry Andric       for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
901006c3fb27SDimitry Andric         FeatureArgs.emplace_back(
901106c3fb27SDimitry Andric             Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
901206c3fb27SDimitry Andric       }
901306c3fb27SDimitry Andric     }
901406c3fb27SDimitry Andric 
901506c3fb27SDimitry Andric     // TODO: We need to pass in the full target-id and handle it properly in the
901606c3fb27SDimitry Andric     // linker wrapper.
901781ad6265SDimitry Andric     SmallVector<std::string> Parts{
901881ad6265SDimitry Andric         "file=" + File.str(),
901981ad6265SDimitry Andric         "triple=" + TC->getTripleString(),
90207a6dacacSDimitry Andric         "arch=" + Arch.str(),
902181ad6265SDimitry Andric         "kind=" + Kind.str(),
902281ad6265SDimitry Andric     };
902381ad6265SDimitry Andric 
902406c3fb27SDimitry Andric     if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
902506c3fb27SDimitry Andric         TC->getTriple().isAMDGPU())
902681ad6265SDimitry Andric       for (StringRef Feature : FeatureArgs)
902781ad6265SDimitry Andric         Parts.emplace_back("feature=" + Feature.str());
902881ad6265SDimitry Andric 
902981ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
903081ad6265SDimitry Andric   }
903181ad6265SDimitry Andric 
903281ad6265SDimitry Andric   C.addCommand(std::make_unique<Command>(
903381ad6265SDimitry Andric       JA, *this, ResponseFileSupport::None(),
903481ad6265SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
903581ad6265SDimitry Andric       CmdArgs, Inputs, Output));
903681ad6265SDimitry Andric }
903781ad6265SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const90381fd87a68SDimitry Andric void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
90391fd87a68SDimitry Andric                                  const InputInfo &Output,
90401fd87a68SDimitry Andric                                  const InputInfoList &Inputs,
90411fd87a68SDimitry Andric                                  const ArgList &Args,
90421fd87a68SDimitry Andric                                  const char *LinkingOutput) const {
9043d56accc7SDimitry Andric   const Driver &D = getToolChain().getDriver();
9044d56accc7SDimitry Andric   const llvm::Triple TheTriple = getToolChain().getTriple();
90451fd87a68SDimitry Andric   ArgStringList CmdArgs;
90461fd87a68SDimitry Andric 
9047d56accc7SDimitry Andric   // Pass the CUDA path to the linker wrapper tool.
904881ad6265SDimitry Andric   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
904981ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains(Kind);
905081ad6265SDimitry Andric     for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
9051d56accc7SDimitry Andric       const ToolChain *TC = I.second;
9052d56accc7SDimitry Andric       if (TC->getTriple().isNVPTX()) {
9053d56accc7SDimitry Andric         CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
9054d56accc7SDimitry Andric         if (CudaInstallation.isValid())
9055d56accc7SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
9056d56accc7SDimitry Andric               "--cuda-path=" + CudaInstallation.getInstallPath()));
9057d56accc7SDimitry Andric         break;
9058d56accc7SDimitry Andric       }
9059d56accc7SDimitry Andric     }
90601fd87a68SDimitry Andric   }
90611fd87a68SDimitry Andric 
90621fd87a68SDimitry Andric   // Pass in the optimization level to use for LTO.
90631fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
90641fd87a68SDimitry Andric     StringRef OOpt;
90651fd87a68SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
90661fd87a68SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
90671fd87a68SDimitry Andric       OOpt = "3";
90681fd87a68SDimitry Andric     else if (A->getOption().matches(options::OPT_O)) {
90691fd87a68SDimitry Andric       OOpt = A->getValue();
90701fd87a68SDimitry Andric       if (OOpt == "g")
90711fd87a68SDimitry Andric         OOpt = "1";
90721fd87a68SDimitry Andric       else if (OOpt == "s" || OOpt == "z")
90731fd87a68SDimitry Andric         OOpt = "2";
90741fd87a68SDimitry Andric     } else if (A->getOption().matches(options::OPT_O0))
90751fd87a68SDimitry Andric       OOpt = "0";
90761fd87a68SDimitry Andric     if (!OOpt.empty())
9077753f127fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
90781fd87a68SDimitry Andric   }
90791fd87a68SDimitry Andric 
9080753f127fSDimitry Andric   CmdArgs.push_back(
9081753f127fSDimitry Andric       Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
90821fd87a68SDimitry Andric   if (Args.hasArg(options::OPT_v))
9083bdd1243dSDimitry Andric     CmdArgs.push_back("--wrapper-verbose");
90841fd87a68SDimitry Andric 
90851fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
9086753f127fSDimitry Andric     if (!A->getOption().matches(options::OPT_g0))
9087753f127fSDimitry Andric       CmdArgs.push_back("--device-debug");
90881fd87a68SDimitry Andric   }
90891fd87a68SDimitry Andric 
90905f757f3fSDimitry Andric   // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
90915f757f3fSDimitry Andric   // that it is used by lld.
90925f757f3fSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
90935f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mllvm"));
90945f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
90955f757f3fSDimitry Andric         Twine("--amdhsa-code-object-version=") + A->getValue()));
90965f757f3fSDimitry Andric   }
90975f757f3fSDimitry Andric 
90981fd87a68SDimitry Andric   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
9099bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
91001fd87a68SDimitry Andric 
91011fd87a68SDimitry Andric   // Forward remarks passes to the LLVM backend in the wrapper.
91021fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
9103fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
9104fcaf7f86SDimitry Andric                                          A->getValue()));
91051fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
9106fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
9107fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
91081fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
9109fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
9110fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
91111fd87a68SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
9112753f127fSDimitry Andric     CmdArgs.push_back("--save-temps");
91131fd87a68SDimitry Andric 
9114d56accc7SDimitry Andric   // Construct the link job so we can wrap around it.
9115d56accc7SDimitry Andric   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9116d56accc7SDimitry Andric   const auto &LinkCommand = C.getJobs().getJobs().back();
9117d56accc7SDimitry Andric 
911881ad6265SDimitry Andric   // Forward -Xoffload-linker<-triple> arguments to the device link job.
9119753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
9120753f127fSDimitry Andric     StringRef Val = A->getValue(0);
912181ad6265SDimitry Andric     if (Val.empty())
912281ad6265SDimitry Andric       CmdArgs.push_back(
9123753f127fSDimitry Andric           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
912481ad6265SDimitry Andric     else
912581ad6265SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
9126753f127fSDimitry Andric           "--device-linker=" +
912781ad6265SDimitry Andric           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
9128753f127fSDimitry Andric           A->getValue(1)));
912981ad6265SDimitry Andric   }
913081ad6265SDimitry Andric   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
913181ad6265SDimitry Andric 
9132bdd1243dSDimitry Andric   // Embed bitcode instead of an object in JIT mode.
9133bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9134bdd1243dSDimitry Andric                    options::OPT_fno_openmp_target_jit, false))
9135bdd1243dSDimitry Andric     CmdArgs.push_back("--embed-bitcode");
9136bdd1243dSDimitry Andric 
9137753f127fSDimitry Andric   // Forward `-mllvm` arguments to the LLVM invocations if present.
9138753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_mllvm)) {
9139753f127fSDimitry Andric     CmdArgs.push_back("-mllvm");
9140753f127fSDimitry Andric     CmdArgs.push_back(A->getValue());
9141753f127fSDimitry Andric     A->claim();
9142753f127fSDimitry Andric   }
9143753f127fSDimitry Andric 
91441fd87a68SDimitry Andric   // Add the linker arguments to be forwarded by the wrapper.
9145753f127fSDimitry Andric   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
9146753f127fSDimitry Andric                                        LinkCommand->getExecutable()));
91471fd87a68SDimitry Andric   for (const char *LinkArg : LinkCommand->getArguments())
91481fd87a68SDimitry Andric     CmdArgs.push_back(LinkArg);
91491fd87a68SDimitry Andric 
91500fca6ea1SDimitry Andric   addOffloadCompressArgs(Args, CmdArgs);
91510fca6ea1SDimitry Andric 
91521fd87a68SDimitry Andric   const char *Exec =
91531fd87a68SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
91541fd87a68SDimitry Andric 
91551fd87a68SDimitry Andric   // Replace the executable and arguments of the link job with the
91561fd87a68SDimitry Andric   // wrapper.
91571fd87a68SDimitry Andric   LinkCommand->replaceExecutable(Exec);
91581fd87a68SDimitry Andric   LinkCommand->replaceArguments(CmdArgs);
91591fd87a68SDimitry Andric }
9160