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"
487a6dacacSDimitry Andric #include "llvm/Object/ObjectFile.h"
490b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
500b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
515ffd83dbSDimitry Andric #include "llvm/Support/Compiler.h"
520b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
5306c3fb27SDimitry Andric #include "llvm/Support/Error.h"
540b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
550b57cec5SDimitry Andric #include "llvm/Support/Path.h"
560b57cec5SDimitry Andric #include "llvm/Support/Process.h"
5706c3fb27SDimitry Andric #include "llvm/Support/RISCVISAInfo.h"
580b57cec5SDimitry Andric #include "llvm/Support/YAMLParser.h"
5906c3fb27SDimitry Andric #include "llvm/TargetParser/ARMTargetParserCommon.h"
6006c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
618a4dda33SDimitry Andric #include "llvm/TargetParser/LoongArchTargetParser.h"
6206c3fb27SDimitry Andric #include "llvm/TargetParser/RISCVTargetParser.h"
63753f127fSDimitry Andric #include <cctype>
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace clang::driver;
660b57cec5SDimitry Andric using namespace clang::driver::tools;
670b57cec5SDimitry Andric using namespace clang;
680b57cec5SDimitry Andric using namespace llvm::opt;
690b57cec5SDimitry Andric 
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)700b57cec5SDimitry Andric static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
72349cc55cSDimitry Andric                                options::OPT_fminimize_whitespace,
735f757f3fSDimitry Andric                                options::OPT_fno_minimize_whitespace,
745f757f3fSDimitry Andric                                options::OPT_fkeep_system_includes,
755f757f3fSDimitry Andric                                options::OPT_fno_keep_system_includes)) {
760b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
770b57cec5SDimitry Andric         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
780b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
790b57cec5SDimitry Andric           << A->getBaseArg().getAsString(Args)
800b57cec5SDimitry Andric           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
810b57cec5SDimitry Andric     }
820b57cec5SDimitry Andric   }
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)850b57cec5SDimitry Andric static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
860b57cec5SDimitry Andric   // In gcc, only ARM checks this, but it seems reasonable to check universally.
870b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
880b57cec5SDimitry Andric     if (const Arg *A =
890b57cec5SDimitry Andric             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
900b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
910b57cec5SDimitry Andric                                                       << "-static";
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric // Add backslashes to escape spaces and other backslashes.
950b57cec5SDimitry Andric // This is used for the space-separated argument list specified with
960b57cec5SDimitry Andric // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)970b57cec5SDimitry Andric static void EscapeSpacesAndBackslashes(const char *Arg,
980b57cec5SDimitry Andric                                        SmallVectorImpl<char> &Res) {
990b57cec5SDimitry Andric   for (; *Arg; ++Arg) {
1000b57cec5SDimitry Andric     switch (*Arg) {
1010b57cec5SDimitry Andric     default:
1020b57cec5SDimitry Andric       break;
1030b57cec5SDimitry Andric     case ' ':
1040b57cec5SDimitry Andric     case '\\':
1050b57cec5SDimitry Andric       Res.push_back('\\');
1060b57cec5SDimitry Andric       break;
1070b57cec5SDimitry Andric     }
1080b57cec5SDimitry Andric     Res.push_back(*Arg);
1090b57cec5SDimitry Andric   }
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric /// Apply \a Work on the current tool chain \a RegularToolChain and any other
1130b57cec5SDimitry Andric /// offloading tool chain that is associated with the current action \a JA.
1140b57cec5SDimitry Andric static void
forAllAssociatedToolChains(Compilation & C,const JobAction & JA,const ToolChain & RegularToolChain,llvm::function_ref<void (const ToolChain &)> Work)1150b57cec5SDimitry Andric forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
1160b57cec5SDimitry Andric                            const ToolChain &RegularToolChain,
1170b57cec5SDimitry Andric                            llvm::function_ref<void(const ToolChain &)> Work) {
1180b57cec5SDimitry Andric   // Apply Work on the current/regular tool chain.
1190b57cec5SDimitry Andric   Work(RegularToolChain);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   // Apply Work on all the offloading tool chains associated with the current
1220b57cec5SDimitry Andric   // action.
1230b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_Cuda))
1240b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1250b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
1260b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1270b57cec5SDimitry Andric   else if (JA.isHostOffloading(Action::OFK_HIP))
1280b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
1290b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_HIP))
1300b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
1330b57cec5SDimitry Andric     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
1340b57cec5SDimitry Andric     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
1350b57cec5SDimitry Andric       Work(*II->second);
1360b57cec5SDimitry Andric   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
1370b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   //
1400b57cec5SDimitry Andric   // TODO: Add support for other offloading programming models here.
1410b57cec5SDimitry Andric   //
1420b57cec5SDimitry Andric }
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric /// This is a helper function for validating the optional refinement step
1450b57cec5SDimitry Andric /// parameter in reciprocal argument strings. Return false if there is an error
1460b57cec5SDimitry Andric /// parsing the refinement step. Otherwise, return true and set the Position
1470b57cec5SDimitry Andric /// of the refinement step in the input string.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)1480b57cec5SDimitry Andric static bool getRefinementStep(StringRef In, const Driver &D,
1490b57cec5SDimitry Andric                               const Arg &A, size_t &Position) {
1500b57cec5SDimitry Andric   const char RefinementStepToken = ':';
1510b57cec5SDimitry Andric   Position = In.find(RefinementStepToken);
1520b57cec5SDimitry Andric   if (Position != StringRef::npos) {
1530b57cec5SDimitry Andric     StringRef Option = A.getOption().getName();
1540b57cec5SDimitry Andric     StringRef RefStep = In.substr(Position + 1);
1550b57cec5SDimitry Andric     // Allow exactly one numeric character for the additional refinement
1560b57cec5SDimitry Andric     // step parameter. This is reasonable for all currently-supported
1570b57cec5SDimitry Andric     // operations and architectures because we would expect that a larger value
1580b57cec5SDimitry Andric     // of refinement steps would cause the estimate "optimization" to
1590b57cec5SDimitry Andric     // under-perform the native operation. Also, if the estimate does not
1600b57cec5SDimitry Andric     // converge quickly, it probably will not ever converge, so further
1610b57cec5SDimitry Andric     // refinement steps will not produce a better answer.
1620b57cec5SDimitry Andric     if (RefStep.size() != 1) {
1630b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1640b57cec5SDimitry Andric       return false;
1650b57cec5SDimitry Andric     }
1660b57cec5SDimitry Andric     char RefStepChar = RefStep[0];
1670b57cec5SDimitry Andric     if (RefStepChar < '0' || RefStepChar > '9') {
1680b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1690b57cec5SDimitry Andric       return false;
1700b57cec5SDimitry Andric     }
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric   return true;
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)1760b57cec5SDimitry Andric static void ParseMRecip(const Driver &D, const ArgList &Args,
1770b57cec5SDimitry Andric                         ArgStringList &OutStrings) {
1780b57cec5SDimitry Andric   StringRef DisabledPrefixIn = "!";
1790b57cec5SDimitry Andric   StringRef DisabledPrefixOut = "!";
1800b57cec5SDimitry Andric   StringRef EnabledPrefixOut = "";
1810b57cec5SDimitry Andric   StringRef Out = "-mrecip=";
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1840b57cec5SDimitry Andric   if (!A)
1850b57cec5SDimitry Andric     return;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   unsigned NumOptions = A->getNumValues();
1880b57cec5SDimitry Andric   if (NumOptions == 0) {
1890b57cec5SDimitry Andric     // No option is the same as "all".
1900b57cec5SDimitry Andric     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1910b57cec5SDimitry Andric     return;
1920b57cec5SDimitry Andric   }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   // Pass through "all", "none", or "default" with an optional refinement step.
1950b57cec5SDimitry Andric   if (NumOptions == 1) {
1960b57cec5SDimitry Andric     StringRef Val = A->getValue(0);
1970b57cec5SDimitry Andric     size_t RefStepLoc;
1980b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStepLoc))
1990b57cec5SDimitry Andric       return;
2000b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStepLoc);
2010b57cec5SDimitry Andric     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2020b57cec5SDimitry Andric       OutStrings.push_back(Args.MakeArgString(Out + Val));
2030b57cec5SDimitry Andric       return;
2040b57cec5SDimitry Andric     }
2050b57cec5SDimitry Andric   }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // Each reciprocal type may be enabled or disabled individually.
2080b57cec5SDimitry Andric   // Check each input value for validity, concatenate them all back together,
2090b57cec5SDimitry Andric   // and pass through.
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   llvm::StringMap<bool> OptionStrings;
2120b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divd", false));
2130b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divf", false));
21481ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("divh", false));
2150b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divd", false));
2160b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divf", false));
21781ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divh", false));
2180b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtd", false));
2190b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtf", false));
22081ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("sqrth", false));
2210b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2220b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
22381ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrth", false));
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOptions; ++i) {
2260b57cec5SDimitry Andric     StringRef Val = A->getValue(i);
2270b57cec5SDimitry Andric 
2285f757f3fSDimitry Andric     bool IsDisabled = Val.starts_with(DisabledPrefixIn);
2290b57cec5SDimitry Andric     // Ignore the disablement token for string matching.
2300b57cec5SDimitry Andric     if (IsDisabled)
2310b57cec5SDimitry Andric       Val = Val.substr(1);
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric     size_t RefStep;
2340b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStep))
2350b57cec5SDimitry Andric       return;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStep);
2380b57cec5SDimitry Andric     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2390b57cec5SDimitry Andric     if (OptionIter == OptionStrings.end()) {
2400b57cec5SDimitry Andric       // Try again specifying float suffix.
2410b57cec5SDimitry Andric       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2420b57cec5SDimitry Andric       if (OptionIter == OptionStrings.end()) {
2430b57cec5SDimitry Andric         // The input name did not match any known option string.
2440b57cec5SDimitry Andric         D.Diag(diag::err_drv_unknown_argument) << Val;
2450b57cec5SDimitry Andric         return;
2460b57cec5SDimitry Andric       }
24781ad6265SDimitry Andric       // The option was specified without a half or float or double suffix.
24881ad6265SDimitry Andric       // Make sure that the double or half entry was not already specified.
2490b57cec5SDimitry Andric       // The float entry will be checked below.
25081ad6265SDimitry Andric       if (OptionStrings[ValBase.str() + 'd'] ||
25181ad6265SDimitry Andric           OptionStrings[ValBase.str() + 'h']) {
2520b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2530b57cec5SDimitry Andric         return;
2540b57cec5SDimitry Andric       }
2550b57cec5SDimitry Andric     }
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     if (OptionIter->second == true) {
2580b57cec5SDimitry Andric       // Duplicate option specified.
2590b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2600b57cec5SDimitry Andric       return;
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     // Mark the matched option as found. Do not allow duplicate specifiers.
2640b57cec5SDimitry Andric     OptionIter->second = true;
2650b57cec5SDimitry Andric 
26681ad6265SDimitry Andric     // If the precision was not specified, also mark the double and half entry
26781ad6265SDimitry Andric     // as found.
26881ad6265SDimitry Andric     if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
2690b57cec5SDimitry Andric       OptionStrings[ValBase.str() + 'd'] = true;
27081ad6265SDimitry Andric       OptionStrings[ValBase.str() + 'h'] = true;
27181ad6265SDimitry Andric     }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     // Build the output string.
2740b57cec5SDimitry Andric     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2750b57cec5SDimitry Andric     Out = Args.MakeArgString(Out + Prefix + Val);
2760b57cec5SDimitry Andric     if (i != NumOptions - 1)
2770b57cec5SDimitry Andric       Out = Args.MakeArgString(Out + ",");
2780b57cec5SDimitry Andric   }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   OutStrings.push_back(Args.MakeArgString(Out));
2810b57cec5SDimitry Andric }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric /// The -mprefer-vector-width option accepts either a positive integer
2840b57cec5SDimitry Andric /// or the string "none".
ParseMPreferVectorWidth(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)2850b57cec5SDimitry Andric static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
2860b57cec5SDimitry Andric                                     ArgStringList &CmdArgs) {
2870b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
2880b57cec5SDimitry Andric   if (!A)
2890b57cec5SDimitry Andric     return;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   StringRef Value = A->getValue();
2920b57cec5SDimitry Andric   if (Value == "none") {
2930b57cec5SDimitry Andric     CmdArgs.push_back("-mprefer-vector-width=none");
2940b57cec5SDimitry Andric   } else {
2950b57cec5SDimitry Andric     unsigned Width;
2960b57cec5SDimitry Andric     if (Value.getAsInteger(10, Width)) {
2970b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
2980b57cec5SDimitry Andric       return;
2990b57cec5SDimitry Andric     }
3000b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)3050b57cec5SDimitry Andric shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
3060b57cec5SDimitry Andric                                           const llvm::Triple &Triple) {
3070b57cec5SDimitry Andric   // We use the zero-cost exception tables for Objective-C if the non-fragile
3080b57cec5SDimitry Andric   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
3090b57cec5SDimitry Andric   // later.
3100b57cec5SDimitry Andric   if (runtime.isNonFragile())
3110b57cec5SDimitry Andric     return true;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   if (!Triple.isMacOSX())
3140b57cec5SDimitry Andric     return false;
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   return (!Triple.isMacOSXVersionLT(10, 5) &&
3170b57cec5SDimitry Andric           (Triple.getArch() == llvm::Triple::x86_64 ||
3180b57cec5SDimitry Andric            Triple.getArch() == llvm::Triple::arm));
3190b57cec5SDimitry Andric }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric /// Adds exception related arguments to the driver command arguments. There's a
3224824e7fdSDimitry Andric /// main flag, -fexceptions and also language specific flags to enable/disable
3230b57cec5SDimitry Andric /// C++ and Objective-C exceptions. This makes it possible to for example
3240b57cec5SDimitry 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)325fe6060f1SDimitry Andric static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
3260b57cec5SDimitry Andric                              const ToolChain &TC, bool KernelOrKext,
3270b57cec5SDimitry Andric                              const ObjCRuntime &objcRuntime,
3280b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
3290b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   if (KernelOrKext) {
3320b57cec5SDimitry Andric     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
3330b57cec5SDimitry Andric     // arguments now to avoid warnings about unused arguments.
3340b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fexceptions);
3350b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_exceptions);
3360b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
3370b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
3380b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
3390b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
340fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
341fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
342fe6060f1SDimitry Andric     return false;
3430b57cec5SDimitry Andric   }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   // See if the user explicitly enabled exceptions.
3460b57cec5SDimitry Andric   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3470b57cec5SDimitry Andric                          false);
3480b57cec5SDimitry Andric 
349fe6060f1SDimitry Andric   bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
350fe6060f1SDimitry Andric                           options::OPT_fno_async_exceptions, false);
351fe6060f1SDimitry Andric   if (EHa) {
352fe6060f1SDimitry Andric     CmdArgs.push_back("-fasync-exceptions");
353fe6060f1SDimitry Andric     EH = true;
354fe6060f1SDimitry Andric   }
355fe6060f1SDimitry Andric 
3560b57cec5SDimitry Andric   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
3570b57cec5SDimitry Andric   // is not necessarily sensible, but follows GCC.
3580b57cec5SDimitry Andric   if (types::isObjC(InputType) &&
3590b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fobjc_exceptions,
3600b57cec5SDimitry Andric                    options::OPT_fno_objc_exceptions, true)) {
3610b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-exceptions");
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   if (types::isCXX(InputType)) {
36781ad6265SDimitry Andric     // Disable C++ EH by default on XCore and PS4/PS5.
36881ad6265SDimitry Andric     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
36981ad6265SDimitry Andric                                 !Triple.isPS() && !Triple.isDriverKit();
3700b57cec5SDimitry Andric     Arg *ExceptionArg = Args.getLastArg(
3710b57cec5SDimitry Andric         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
3720b57cec5SDimitry Andric         options::OPT_fexceptions, options::OPT_fno_exceptions);
3730b57cec5SDimitry Andric     if (ExceptionArg)
3740b57cec5SDimitry Andric       CXXExceptionsEnabled =
3750b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
3760b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fexceptions);
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric     if (CXXExceptionsEnabled) {
3790b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric       EH = true;
3820b57cec5SDimitry Andric     }
3830b57cec5SDimitry Andric   }
3840b57cec5SDimitry Andric 
3855ffd83dbSDimitry Andric   // OPT_fignore_exceptions means exception could still be thrown,
3865ffd83dbSDimitry Andric   // but no clean up or catch would happen in current module.
3875ffd83dbSDimitry Andric   // So we do not set EH to false.
3885ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
3895ffd83dbSDimitry Andric 
3905f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
3915f757f3fSDimitry Andric                     options::OPT_fno_assume_nothrow_exception_dtor);
3925f757f3fSDimitry Andric 
3930b57cec5SDimitry Andric   if (EH)
3940b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
395fe6060f1SDimitry Andric   return EH;
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
ShouldEnableAutolink(const ArgList & Args,const ToolChain & TC,const JobAction & JA)398480093f4SDimitry Andric static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
399480093f4SDimitry Andric                                  const JobAction &JA) {
4000b57cec5SDimitry Andric   bool Default = true;
4010b57cec5SDimitry Andric   if (TC.getTriple().isOSDarwin()) {
4020b57cec5SDimitry Andric     // The native darwin assembler doesn't support the linker_option directives,
4030b57cec5SDimitry Andric     // so we disable them if we think the .s file will be passed to it.
4040b57cec5SDimitry Andric     Default = TC.useIntegratedAs();
4050b57cec5SDimitry Andric   }
406480093f4SDimitry Andric   // The linker_option directives are intended for host compilation.
407480093f4SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
408480093f4SDimitry Andric       JA.isDeviceOffloading(Action::OFK_HIP))
409480093f4SDimitry Andric     Default = false;
410480093f4SDimitry Andric   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
4110b57cec5SDimitry Andric                       Default);
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs,const llvm::vfs::FileSystem & VFS)4150eae32dcSDimitry Andric static const char *addDebugCompDirArg(const ArgList &Args,
4160eae32dcSDimitry Andric                                       ArgStringList &CmdArgs,
417a7dea167SDimitry Andric                                       const llvm::vfs::FileSystem &VFS) {
418fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
419fe6060f1SDimitry Andric                                options::OPT_fdebug_compilation_dir_EQ)) {
420fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
421fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
422fe6060f1SDimitry Andric                                            A->getValue()));
423fe6060f1SDimitry Andric     else
424fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
425a7dea167SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
426a7dea167SDimitry Andric                  VFS.getCurrentWorkingDirectory()) {
427fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
4280b57cec5SDimitry Andric   }
4290eae32dcSDimitry Andric   StringRef Path(CmdArgs.back());
4300eae32dcSDimitry Andric   return Path.substr(Path.find('=') + 1).data();
4310eae32dcSDimitry Andric }
4320eae32dcSDimitry Andric 
addDebugObjectName(const ArgList & Args,ArgStringList & CmdArgs,const char * DebugCompilationDir,const char * OutputFileName)4330eae32dcSDimitry Andric static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
4340eae32dcSDimitry Andric                                const char *DebugCompilationDir,
4350eae32dcSDimitry Andric                                const char *OutputFileName) {
4360eae32dcSDimitry Andric   // No need to generate a value for -object-file-name if it was provided.
4370eae32dcSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
4385f757f3fSDimitry Andric     if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
4390eae32dcSDimitry Andric       return;
4400eae32dcSDimitry Andric 
4410eae32dcSDimitry Andric   if (Args.hasArg(options::OPT_object_file_name_EQ))
4420eae32dcSDimitry Andric     return;
4430eae32dcSDimitry Andric 
4440eae32dcSDimitry Andric   SmallString<128> ObjFileNameForDebug(OutputFileName);
4450eae32dcSDimitry Andric   if (ObjFileNameForDebug != "-" &&
4460eae32dcSDimitry Andric       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
4470eae32dcSDimitry Andric       (!DebugCompilationDir ||
4480eae32dcSDimitry Andric        llvm::sys::path::is_absolute(DebugCompilationDir))) {
4490eae32dcSDimitry Andric     // Make the path absolute in the debug infos like MSVC does.
4500eae32dcSDimitry Andric     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
4510eae32dcSDimitry Andric   }
45206c3fb27SDimitry Andric   // If the object file name is a relative path, then always use Windows
45306c3fb27SDimitry Andric   // backslash style as -object-file-name is used for embedding object file path
45406c3fb27SDimitry Andric   // in codeview and it can only be generated when targeting on Windows.
45506c3fb27SDimitry Andric   // Otherwise, just use native absolute path.
45606c3fb27SDimitry Andric   llvm::sys::path::Style Style =
45706c3fb27SDimitry Andric       llvm::sys::path::is_absolute(ObjFileNameForDebug)
45806c3fb27SDimitry Andric           ? llvm::sys::path::Style::native
45906c3fb27SDimitry Andric           : llvm::sys::path::Style::windows_backslash;
46006c3fb27SDimitry Andric   llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
46106c3fb27SDimitry Andric                                Style);
4620eae32dcSDimitry Andric   CmdArgs.push_back(
4630eae32dcSDimitry Andric       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry 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)46781ad6265SDimitry Andric static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
46881ad6265SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
46981ad6265SDimitry Andric   auto AddOneArg = [&](StringRef Map, StringRef Name) {
470349cc55cSDimitry Andric     if (!Map.contains('='))
47181ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
4720b57cec5SDimitry Andric     else
4730b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
47481ad6265SDimitry Andric   };
47581ad6265SDimitry Andric 
47681ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
47781ad6265SDimitry Andric                                     options::OPT_fdebug_prefix_map_EQ)) {
47881ad6265SDimitry Andric     AddOneArg(A->getValue(), A->getOption().getName());
4790b57cec5SDimitry Andric     A->claim();
4800b57cec5SDimitry Andric   }
48181ad6265SDimitry Andric   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
48281ad6265SDimitry Andric   if (GlobalRemapEntry.empty())
48381ad6265SDimitry Andric     return;
48481ad6265SDimitry Andric   AddOneArg(GlobalRemapEntry, "environment");
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
487480093f4SDimitry Andric /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
addMacroPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)488480093f4SDimitry Andric static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
489480093f4SDimitry Andric                                  ArgStringList &CmdArgs) {
490480093f4SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
491480093f4SDimitry Andric                                     options::OPT_fmacro_prefix_map_EQ)) {
492480093f4SDimitry Andric     StringRef Map = A->getValue();
493349cc55cSDimitry Andric     if (!Map.contains('='))
494480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
495480093f4SDimitry Andric           << Map << A->getOption().getName();
496480093f4SDimitry Andric     else
497480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
498480093f4SDimitry Andric     A->claim();
499480093f4SDimitry Andric   }
500480093f4SDimitry Andric }
501480093f4SDimitry Andric 
502e8d8bef9SDimitry Andric /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
addCoveragePrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)503fe6060f1SDimitry Andric static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
504e8d8bef9SDimitry Andric                                    ArgStringList &CmdArgs) {
505e8d8bef9SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
506fe6060f1SDimitry Andric                                     options::OPT_fcoverage_prefix_map_EQ)) {
507e8d8bef9SDimitry Andric     StringRef Map = A->getValue();
508349cc55cSDimitry Andric     if (!Map.contains('='))
509e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
510e8d8bef9SDimitry Andric           << Map << A->getOption().getName();
511e8d8bef9SDimitry Andric     else
512fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
513e8d8bef9SDimitry Andric     A->claim();
514e8d8bef9SDimitry Andric   }
515e8d8bef9SDimitry Andric }
516e8d8bef9SDimitry Andric 
5170b57cec5SDimitry Andric /// Vectorize at all optimization levels greater than 1 except for -Oz.
5180b57cec5SDimitry Andric /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
5190b57cec5SDimitry Andric /// enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)5200b57cec5SDimitry Andric static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
5210b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5220b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
5230b57cec5SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
5240b57cec5SDimitry Andric       return true;
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O0))
5270b57cec5SDimitry Andric       return false;
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric     // Vectorize -Os.
5320b57cec5SDimitry Andric     StringRef S(A->getValue());
5330b57cec5SDimitry Andric     if (S == "s")
5340b57cec5SDimitry Andric       return true;
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     // Don't vectorize -Oz, unless it's the slp vectorizer.
5370b57cec5SDimitry Andric     if (S == "z")
5380b57cec5SDimitry Andric       return isSlpVec;
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     unsigned OptLevel = 0;
5410b57cec5SDimitry Andric     if (S.getAsInteger(10, OptLevel))
5420b57cec5SDimitry Andric       return false;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric     return OptLevel > 1;
5450b57cec5SDimitry Andric   }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   return false;
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)5510b57cec5SDimitry Andric static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
5520b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
5530b57cec5SDimitry Andric   // When using -verify-pch, we don't want to provide the type
5540b57cec5SDimitry Andric   // 'precompiled-header' if it was inferred from the file extension
5550b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
5560b57cec5SDimitry Andric     return;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   CmdArgs.push_back("-x");
5590b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_rewrite_objc))
5600b57cec5SDimitry Andric     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
5610b57cec5SDimitry Andric   else {
5620b57cec5SDimitry Andric     // Map the driver type to the frontend type. This is mostly an identity
5630b57cec5SDimitry Andric     // mapping, except that the distinction between module interface units
5640b57cec5SDimitry Andric     // and other source files does not exist at the frontend layer.
5650b57cec5SDimitry Andric     const char *ClangType;
5660b57cec5SDimitry Andric     switch (Input.getType()) {
5670b57cec5SDimitry Andric     case types::TY_CXXModule:
5680b57cec5SDimitry Andric       ClangType = "c++";
5690b57cec5SDimitry Andric       break;
5700b57cec5SDimitry Andric     case types::TY_PP_CXXModule:
5710b57cec5SDimitry Andric       ClangType = "c++-cpp-output";
5720b57cec5SDimitry Andric       break;
5730b57cec5SDimitry Andric     default:
5740b57cec5SDimitry Andric       ClangType = types::getTypeName(Input.getType());
5750b57cec5SDimitry Andric       break;
5760b57cec5SDimitry Andric     }
5770b57cec5SDimitry Andric     CmdArgs.push_back(ClangType);
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric 
addPGOAndCoverageFlags(const ToolChain & TC,Compilation & C,const JobAction & JA,const InputInfo & Output,const ArgList & Args,SanitizerArgs & SanArgs,ArgStringList & CmdArgs)5810b57cec5SDimitry Andric static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
58206c3fb27SDimitry Andric                                    const JobAction &JA, const InputInfo &Output,
583349cc55cSDimitry Andric                                    const ArgList &Args, SanitizerArgs &SanArgs,
5840b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
58506c3fb27SDimitry Andric   const Driver &D = TC.getDriver();
5860b57cec5SDimitry Andric   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
5870b57cec5SDimitry Andric                                          options::OPT_fprofile_generate_EQ,
5880b57cec5SDimitry Andric                                          options::OPT_fno_profile_generate);
5890b57cec5SDimitry Andric   if (PGOGenerateArg &&
5900b57cec5SDimitry Andric       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
5910b57cec5SDimitry Andric     PGOGenerateArg = nullptr;
5920b57cec5SDimitry Andric 
59306c3fb27SDimitry Andric   auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   auto *ProfileGenerateArg = Args.getLastArg(
5960b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate,
5970b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate_EQ,
5980b57cec5SDimitry Andric       options::OPT_fno_profile_instr_generate);
5990b57cec5SDimitry Andric   if (ProfileGenerateArg &&
6000b57cec5SDimitry Andric       ProfileGenerateArg->getOption().matches(
6010b57cec5SDimitry Andric           options::OPT_fno_profile_instr_generate))
6020b57cec5SDimitry Andric     ProfileGenerateArg = nullptr;
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileGenerateArg)
6050b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6060b57cec5SDimitry Andric         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   auto *ProfileUseArg = getLastProfileUseArg(Args);
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileUseArg)
6110b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6120b57cec5SDimitry Andric         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   if (ProfileGenerateArg && ProfileUseArg)
6150b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6160b57cec5SDimitry Andric         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
6170b57cec5SDimitry Andric 
618e8d8bef9SDimitry Andric   if (CSPGOGenerateArg && PGOGenerateArg) {
6190b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6200b57cec5SDimitry Andric         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
621e8d8bef9SDimitry Andric     PGOGenerateArg = nullptr;
622e8d8bef9SDimitry Andric   }
6230b57cec5SDimitry Andric 
624fe6060f1SDimitry Andric   if (TC.getTriple().isOSAIX()) {
625fe6060f1SDimitry Andric     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
626fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
627fe6060f1SDimitry Andric           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
628fe6060f1SDimitry Andric   }
629fe6060f1SDimitry Andric 
6300b57cec5SDimitry Andric   if (ProfileGenerateArg) {
6310b57cec5SDimitry Andric     if (ProfileGenerateArg->getOption().matches(
6320b57cec5SDimitry Andric             options::OPT_fprofile_instr_generate_EQ))
6330b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
6340b57cec5SDimitry Andric                                            ProfileGenerateArg->getValue()));
6350b57cec5SDimitry Andric     // The default is to use Clang Instrumentation.
6360b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=clang");
6370b57cec5SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment()) {
6380b57cec5SDimitry Andric       // Add dependent lib for clang_rt.profile
6395ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6405ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric   }
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   Arg *PGOGenArg = nullptr;
6450b57cec5SDimitry Andric   if (PGOGenerateArg) {
6460b57cec5SDimitry Andric     assert(!CSPGOGenerateArg);
6470b57cec5SDimitry Andric     PGOGenArg = PGOGenerateArg;
6480b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=llvm");
6490b57cec5SDimitry Andric   }
6500b57cec5SDimitry Andric   if (CSPGOGenerateArg) {
6510b57cec5SDimitry Andric     assert(!PGOGenerateArg);
6520b57cec5SDimitry Andric     PGOGenArg = CSPGOGenerateArg;
6530b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=csllvm");
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric   if (PGOGenArg) {
6560b57cec5SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment()) {
6575ffd83dbSDimitry Andric       // Add dependent lib for clang_rt.profile
6585ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6595ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6600b57cec5SDimitry Andric     }
6610b57cec5SDimitry Andric     if (PGOGenArg->getOption().matches(
6620b57cec5SDimitry Andric             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
6630b57cec5SDimitry Andric                            : options::OPT_fcs_profile_generate_EQ)) {
6640b57cec5SDimitry Andric       SmallString<128> Path(PGOGenArg->getValue());
6650b57cec5SDimitry Andric       llvm::sys::path::append(Path, "default_%m.profraw");
6660b57cec5SDimitry Andric       CmdArgs.push_back(
6670b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
6680b57cec5SDimitry Andric     }
6690b57cec5SDimitry Andric   }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   if (ProfileUseArg) {
6720b57cec5SDimitry Andric     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
6730b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6740b57cec5SDimitry Andric           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
6750b57cec5SDimitry Andric     else if ((ProfileUseArg->getOption().matches(
6760b57cec5SDimitry Andric                   options::OPT_fprofile_use_EQ) ||
6770b57cec5SDimitry Andric               ProfileUseArg->getOption().matches(
6780b57cec5SDimitry Andric                   options::OPT_fprofile_instr_use))) {
6790b57cec5SDimitry Andric       SmallString<128> Path(
6800b57cec5SDimitry Andric           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
6810b57cec5SDimitry Andric       if (Path.empty() || llvm::sys::fs::is_directory(Path))
6820b57cec5SDimitry Andric         llvm::sys::path::append(Path, "default.profdata");
6830b57cec5SDimitry Andric       CmdArgs.push_back(
6840b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
6850b57cec5SDimitry Andric     }
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric 
6885ffd83dbSDimitry Andric   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
6895ffd83dbSDimitry Andric                                    options::OPT_fno_test_coverage, false) ||
690a7dea167SDimitry Andric                       Args.hasArg(options::OPT_coverage);
6915ffd83dbSDimitry Andric   bool EmitCovData = TC.needsGCovInstrumentation(Args);
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fcoverage_mapping,
6940b57cec5SDimitry Andric                    options::OPT_fno_coverage_mapping, false)) {
6950b57cec5SDimitry Andric     if (!ProfileGenerateArg)
6960b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
6970b57cec5SDimitry Andric           << "-fcoverage-mapping"
6980b57cec5SDimitry Andric           << "-fprofile-instr-generate";
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric     CmdArgs.push_back("-fcoverage-mapping");
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric 
7031db9f3b2SDimitry Andric   if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
7041db9f3b2SDimitry Andric                    false)) {
7051db9f3b2SDimitry Andric     if (!Args.hasFlag(options::OPT_fcoverage_mapping,
7061db9f3b2SDimitry Andric                       options::OPT_fno_coverage_mapping, false))
7071db9f3b2SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7081db9f3b2SDimitry Andric           << "-fcoverage-mcdc"
7091db9f3b2SDimitry Andric           << "-fcoverage-mapping";
7101db9f3b2SDimitry Andric 
7111db9f3b2SDimitry Andric     CmdArgs.push_back("-fcoverage-mcdc");
7121db9f3b2SDimitry Andric   }
7131db9f3b2SDimitry Andric 
714fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
715fe6060f1SDimitry Andric                                options::OPT_fcoverage_compilation_dir_EQ)) {
716fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
717fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
718fe6060f1SDimitry Andric           Twine("-fcoverage-compilation-dir=") + A->getValue()));
719fe6060f1SDimitry Andric     else
720fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
721fe6060f1SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
722fe6060f1SDimitry Andric                  D.getVFS().getCurrentWorkingDirectory()) {
723fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
724fe6060f1SDimitry Andric   }
725fe6060f1SDimitry Andric 
7260b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
7270b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
7280b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7290b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7300b57cec5SDimitry Andric           << "-fprofile-exclude-files="
7310b57cec5SDimitry Andric           << "--coverage";
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7340b57cec5SDimitry Andric     CmdArgs.push_back(
7350b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
7360b57cec5SDimitry Andric   }
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
7390b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
7400b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7410b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7420b57cec5SDimitry Andric           << "-fprofile-filter-files="
7430b57cec5SDimitry Andric           << "--coverage";
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7460b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
7470b57cec5SDimitry Andric   }
7480b57cec5SDimitry Andric 
749e8d8bef9SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
750e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
751e8d8bef9SDimitry Andric     if (Val == "atomic" || Val == "prefer-atomic")
752e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprofile-update=atomic");
753e8d8bef9SDimitry Andric     else if (Val != "single")
754e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
755bdd1243dSDimitry Andric           << A->getSpelling() << Val;
756e8d8bef9SDimitry Andric   }
757e8d8bef9SDimitry Andric 
758fcaf7f86SDimitry Andric   int FunctionGroups = 1;
759fcaf7f86SDimitry Andric   int SelectedFunctionGroup = 0;
760fcaf7f86SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
761fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
762fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
763fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
764fcaf7f86SDimitry Andric   }
765fcaf7f86SDimitry Andric   if (const auto *A =
766fcaf7f86SDimitry Andric           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
767fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
768fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
769fcaf7f86SDimitry Andric         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
770fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
771fcaf7f86SDimitry Andric   }
772fcaf7f86SDimitry Andric   if (FunctionGroups != 1)
773fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
774fcaf7f86SDimitry Andric                                          Twine(FunctionGroups)));
775fcaf7f86SDimitry Andric   if (SelectedFunctionGroup != 0)
776fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
777fcaf7f86SDimitry Andric                                          Twine(SelectedFunctionGroup)));
778fcaf7f86SDimitry Andric 
779a7dea167SDimitry Andric   // Leave -fprofile-dir= an unused argument unless .gcda emission is
780a7dea167SDimitry Andric   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
781a7dea167SDimitry Andric   // the flag used. There is no -fno-profile-dir, so the user has no
782a7dea167SDimitry Andric   // targeted way to suppress the warning.
783a7dea167SDimitry Andric   Arg *FProfileDir = nullptr;
784a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_arcs) ||
785a7dea167SDimitry Andric       Args.hasArg(options::OPT_coverage))
786a7dea167SDimitry Andric     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
787a7dea167SDimitry Andric 
78806c3fb27SDimitry Andric   // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
78906c3fb27SDimitry Andric   // like we warn about -fsyntax-only -E.
79006c3fb27SDimitry Andric   (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
79106c3fb27SDimitry Andric 
79206c3fb27SDimitry Andric   // Put the .gcno and .gcda files (if needed) next to the primary output file,
79306c3fb27SDimitry Andric   // or fall back to a file in the current directory for `clang -c --coverage
79406c3fb27SDimitry Andric   // d/a.c` in the absence of -o.
79506c3fb27SDimitry Andric   if (EmitCovNotes || EmitCovData) {
79606c3fb27SDimitry Andric     SmallString<128> CoverageFilename;
79706c3fb27SDimitry Andric     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
79806c3fb27SDimitry Andric       // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
79906c3fb27SDimitry Andric       // path separator.
80006c3fb27SDimitry Andric       CoverageFilename = DumpDir->getValue();
80106c3fb27SDimitry Andric       CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
80206c3fb27SDimitry Andric     } else if (Arg *FinalOutput =
80306c3fb27SDimitry Andric                    C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
80406c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
80506c3fb27SDimitry Andric     } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
80606c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
80706c3fb27SDimitry Andric     } else {
80806c3fb27SDimitry Andric       CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
80906c3fb27SDimitry Andric     }
810a7dea167SDimitry Andric     if (llvm::sys::path::is_relative(CoverageFilename))
811a7dea167SDimitry Andric       (void)D.getVFS().makeAbsolute(CoverageFilename);
8120b57cec5SDimitry Andric     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
81306c3fb27SDimitry Andric     if (EmitCovNotes) {
8145f757f3fSDimitry Andric       CmdArgs.push_back(
8155f757f3fSDimitry Andric           Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
81606c3fb27SDimitry Andric     }
8170b57cec5SDimitry Andric 
818a7dea167SDimitry Andric     if (EmitCovData) {
819a7dea167SDimitry Andric       if (FProfileDir) {
82006c3fb27SDimitry Andric         SmallString<128> Gcno = std::move(CoverageFilename);
8210b57cec5SDimitry Andric         CoverageFilename = FProfileDir->getValue();
82206c3fb27SDimitry Andric         llvm::sys::path::append(CoverageFilename, Gcno);
8230b57cec5SDimitry Andric       }
8240b57cec5SDimitry Andric       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
8255f757f3fSDimitry Andric       CmdArgs.push_back(
8265f757f3fSDimitry Andric           Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
8270b57cec5SDimitry Andric     }
8280b57cec5SDimitry Andric   }
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric /// Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)8320b57cec5SDimitry Andric static bool ContainsCompileAction(const Action *A) {
8330b57cec5SDimitry Andric   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
8340b57cec5SDimitry Andric     return true;
8350b57cec5SDimitry Andric 
8360eae32dcSDimitry Andric   return llvm::any_of(A->inputs(), ContainsCompileAction);
8370b57cec5SDimitry Andric }
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric /// Check if -relax-all should be passed to the internal assembler.
8400b57cec5SDimitry Andric /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)8410b57cec5SDimitry Andric static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
8420b57cec5SDimitry Andric   bool RelaxDefault = true;
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
8450b57cec5SDimitry Andric     RelaxDefault = A->getOption().matches(options::OPT_O0);
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   if (RelaxDefault) {
8480b57cec5SDimitry Andric     RelaxDefault = false;
8490b57cec5SDimitry Andric     for (const auto &Act : C.getActions()) {
8500b57cec5SDimitry Andric       if (ContainsCompileAction(Act)) {
8510b57cec5SDimitry Andric         RelaxDefault = true;
8520b57cec5SDimitry Andric         break;
8530b57cec5SDimitry Andric       }
8540b57cec5SDimitry Andric     }
8550b57cec5SDimitry Andric   }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
8580b57cec5SDimitry Andric                       RelaxDefault);
8590b57cec5SDimitry Andric }
8600b57cec5SDimitry Andric 
86106c3fb27SDimitry Andric static void
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,llvm::codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)86206c3fb27SDimitry Andric RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
86306c3fb27SDimitry Andric                         llvm::codegenoptions::DebugInfoKind DebugInfoKind,
8640b57cec5SDimitry Andric                         unsigned DwarfVersion,
8650b57cec5SDimitry Andric                         llvm::DebuggerKind DebuggerTuning) {
86606c3fb27SDimitry Andric   addDebugInfoKind(CmdArgs, DebugInfoKind);
8670b57cec5SDimitry Andric   if (DwarfVersion > 0)
8680b57cec5SDimitry Andric     CmdArgs.push_back(
8690b57cec5SDimitry Andric         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
8700b57cec5SDimitry Andric   switch (DebuggerTuning) {
8710b57cec5SDimitry Andric   case llvm::DebuggerKind::GDB:
8720b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=gdb");
8730b57cec5SDimitry Andric     break;
8740b57cec5SDimitry Andric   case llvm::DebuggerKind::LLDB:
8750b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=lldb");
8760b57cec5SDimitry Andric     break;
8770b57cec5SDimitry Andric   case llvm::DebuggerKind::SCE:
8780b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=sce");
8790b57cec5SDimitry Andric     break;
880fe6060f1SDimitry Andric   case llvm::DebuggerKind::DBX:
881fe6060f1SDimitry Andric     CmdArgs.push_back("-debugger-tuning=dbx");
882fe6060f1SDimitry Andric     break;
8830b57cec5SDimitry Andric   default:
8840b57cec5SDimitry Andric     break;
8850b57cec5SDimitry Andric   }
8860b57cec5SDimitry Andric }
8870b57cec5SDimitry Andric 
checkDebugInfoOption(const Arg * A,const ArgList & Args,const Driver & D,const ToolChain & TC)8880b57cec5SDimitry Andric static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
8890b57cec5SDimitry Andric                                  const Driver &D, const ToolChain &TC) {
8900b57cec5SDimitry Andric   assert(A && "Expected non-nullptr argument.");
8910b57cec5SDimitry Andric   if (TC.supportsDebugInfoOption(A))
8920b57cec5SDimitry Andric     return true;
8930b57cec5SDimitry Andric   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
8940b57cec5SDimitry Andric       << A->getAsString(Args) << TC.getTripleString();
8950b57cec5SDimitry Andric   return false;
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric 
RenderDebugInfoCompressionArgs(const ArgList & Args,ArgStringList & CmdArgs,const Driver & D,const ToolChain & TC)8980b57cec5SDimitry Andric static void RenderDebugInfoCompressionArgs(const ArgList &Args,
8990b57cec5SDimitry Andric                                            ArgStringList &CmdArgs,
9000b57cec5SDimitry Andric                                            const Driver &D,
9010b57cec5SDimitry Andric                                            const ToolChain &TC) {
902e8d8bef9SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
9030b57cec5SDimitry Andric   if (!A)
9040b57cec5SDimitry Andric     return;
9050b57cec5SDimitry Andric   if (checkDebugInfoOption(A, Args, D, TC)) {
9060b57cec5SDimitry Andric     StringRef Value = A->getValue();
9070b57cec5SDimitry Andric     if (Value == "none") {
9080b57cec5SDimitry Andric       CmdArgs.push_back("--compress-debug-sections=none");
90904eeddc0SDimitry Andric     } else if (Value == "zlib") {
910753f127fSDimitry Andric       if (llvm::compression::zlib::isAvailable()) {
9110b57cec5SDimitry Andric         CmdArgs.push_back(
9120b57cec5SDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
9130b57cec5SDimitry Andric       } else {
914bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
915bdd1243dSDimitry Andric       }
916bdd1243dSDimitry Andric     } else if (Value == "zstd") {
917bdd1243dSDimitry Andric       if (llvm::compression::zstd::isAvailable()) {
918bdd1243dSDimitry Andric         CmdArgs.push_back(
919bdd1243dSDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
920bdd1243dSDimitry Andric       } else {
921bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
9220b57cec5SDimitry Andric       }
9230b57cec5SDimitry Andric     } else {
9240b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
925bdd1243dSDimitry Andric           << A->getSpelling() << Value;
9260b57cec5SDimitry Andric     }
9270b57cec5SDimitry Andric   }
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric 
handleAMDGPUCodeObjectVersionOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsCC1As=false)930e8d8bef9SDimitry Andric static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
931e8d8bef9SDimitry Andric                                                  const ArgList &Args,
93281ad6265SDimitry Andric                                                  ArgStringList &CmdArgs,
93381ad6265SDimitry Andric                                                  bool IsCC1As = false) {
934fe6060f1SDimitry Andric   // If no version was requested by the user, use the default value from the
935fe6060f1SDimitry Andric   // back end. This is consistent with the value returned from
936fe6060f1SDimitry Andric   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
937fe6060f1SDimitry Andric   // requiring the corresponding llvm to have the AMDGPU target enabled,
938fe6060f1SDimitry Andric   // provided the user (e.g. front end tests) can use the default.
939fe6060f1SDimitry Andric   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
940fe6060f1SDimitry Andric     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
941e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1,
942e8d8bef9SDimitry Andric                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
943e8d8bef9SDimitry Andric                                       Twine(CodeObjVer)));
944e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
94581ad6265SDimitry Andric     // -cc1as does not accept -mcode-object-version option.
94681ad6265SDimitry Andric     if (!IsCC1As)
94781ad6265SDimitry Andric       CmdArgs.insert(CmdArgs.begin() + 1,
94881ad6265SDimitry Andric                      Args.MakeArgString(Twine("-mcode-object-version=") +
94981ad6265SDimitry Andric                                         Twine(CodeObjVer)));
950e8d8bef9SDimitry Andric   }
951fe6060f1SDimitry Andric }
9520b57cec5SDimitry Andric 
maybeHasClangPchSignature(const Driver & D,StringRef Path)9537a6dacacSDimitry Andric static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
9547a6dacacSDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
9557a6dacacSDimitry Andric       D.getVFS().getBufferForFile(Path);
9567a6dacacSDimitry Andric   if (!MemBuf)
9575f757f3fSDimitry Andric     return false;
9587a6dacacSDimitry Andric   llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
9597a6dacacSDimitry Andric   if (Magic == llvm::file_magic::unknown)
9607a6dacacSDimitry Andric     return false;
9617a6dacacSDimitry Andric   // Return true for both raw Clang AST files and object files which may
9627a6dacacSDimitry Andric   // contain a __clangast section.
9637a6dacacSDimitry Andric   if (Magic == llvm::file_magic::clang_ast)
9647a6dacacSDimitry Andric     return true;
9657a6dacacSDimitry Andric   Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
9667a6dacacSDimitry Andric       llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
9677a6dacacSDimitry Andric   return !Obj.takeError();
9685f757f3fSDimitry Andric }
9695f757f3fSDimitry Andric 
gchProbe(const Driver & D,StringRef Path)9705f757f3fSDimitry Andric static bool gchProbe(const Driver &D, StringRef Path) {
9715f757f3fSDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
9725f757f3fSDimitry Andric   if (!Status)
9735f757f3fSDimitry Andric     return false;
9745f757f3fSDimitry Andric 
9755f757f3fSDimitry Andric   if (Status->isDirectory()) {
9765f757f3fSDimitry Andric     std::error_code EC;
9775f757f3fSDimitry Andric     for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
9785f757f3fSDimitry Andric          !EC && DI != DE; DI = DI.increment(EC)) {
9797a6dacacSDimitry Andric       if (maybeHasClangPchSignature(D, DI->path()))
9805f757f3fSDimitry Andric         return true;
9815f757f3fSDimitry Andric     }
9825f757f3fSDimitry Andric     D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
9835f757f3fSDimitry Andric     return false;
9845f757f3fSDimitry Andric   }
9855f757f3fSDimitry Andric 
9867a6dacacSDimitry Andric   if (maybeHasClangPchSignature(D, Path))
9875f757f3fSDimitry Andric     return true;
9885f757f3fSDimitry Andric   D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
9895f757f3fSDimitry Andric   return false;
9905f757f3fSDimitry Andric }
9915f757f3fSDimitry Andric 
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const9920b57cec5SDimitry Andric void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
9930b57cec5SDimitry Andric                                     const Driver &D, const ArgList &Args,
9940b57cec5SDimitry Andric                                     ArgStringList &CmdArgs,
9950b57cec5SDimitry Andric                                     const InputInfo &Output,
9960b57cec5SDimitry Andric                                     const InputInfoList &Inputs) const {
9970b57cec5SDimitry Andric   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   CheckPreprocessingOptions(D, Args);
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_C);
10020b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_CC);
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // Handle dependency file generation.
1005a7dea167SDimitry Andric   Arg *ArgM = Args.getLastArg(options::OPT_MM);
1006a7dea167SDimitry Andric   if (!ArgM)
1007a7dea167SDimitry Andric     ArgM = Args.getLastArg(options::OPT_M);
1008a7dea167SDimitry Andric   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1009a7dea167SDimitry Andric   if (!ArgMD)
1010a7dea167SDimitry Andric     ArgMD = Args.getLastArg(options::OPT_MD);
1011a7dea167SDimitry Andric 
1012a7dea167SDimitry Andric   // -M and -MM imply -w.
1013a7dea167SDimitry Andric   if (ArgM)
1014a7dea167SDimitry Andric     CmdArgs.push_back("-w");
1015a7dea167SDimitry Andric   else
1016a7dea167SDimitry Andric     ArgM = ArgMD;
1017a7dea167SDimitry Andric 
1018a7dea167SDimitry Andric   if (ArgM) {
10190b57cec5SDimitry Andric     // Determine the output location.
10200b57cec5SDimitry Andric     const char *DepFile;
10210b57cec5SDimitry Andric     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
10220b57cec5SDimitry Andric       DepFile = MF->getValue();
10230b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10240b57cec5SDimitry Andric     } else if (Output.getType() == types::TY_Dependencies) {
10250b57cec5SDimitry Andric       DepFile = Output.getFilename();
1026a7dea167SDimitry Andric     } else if (!ArgMD) {
10270b57cec5SDimitry Andric       DepFile = "-";
10280b57cec5SDimitry Andric     } else {
10290b57cec5SDimitry Andric       DepFile = getDependencyFileName(Args, Inputs);
10300b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10310b57cec5SDimitry Andric     }
10320b57cec5SDimitry Andric     CmdArgs.push_back("-dependency-file");
10330b57cec5SDimitry Andric     CmdArgs.push_back(DepFile);
10340b57cec5SDimitry Andric 
1035a7dea167SDimitry Andric     bool HasTarget = false;
1036a7dea167SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1037a7dea167SDimitry Andric       HasTarget = true;
1038a7dea167SDimitry Andric       A->claim();
1039a7dea167SDimitry Andric       if (A->getOption().matches(options::OPT_MT)) {
1040a7dea167SDimitry Andric         A->render(Args, CmdArgs);
1041a7dea167SDimitry Andric       } else {
1042a7dea167SDimitry Andric         CmdArgs.push_back("-MT");
1043a7dea167SDimitry Andric         SmallString<128> Quoted;
1044753f127fSDimitry Andric         quoteMakeTarget(A->getValue(), Quoted);
1045a7dea167SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Quoted));
1046a7dea167SDimitry Andric       }
1047a7dea167SDimitry Andric     }
1048a7dea167SDimitry Andric 
10490b57cec5SDimitry Andric     // Add a default target if one wasn't specified.
1050a7dea167SDimitry Andric     if (!HasTarget) {
10510b57cec5SDimitry Andric       const char *DepTarget;
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       // If user provided -o, that is the dependency target, except
10540b57cec5SDimitry Andric       // when we are only generating a dependency file.
10550b57cec5SDimitry Andric       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
10560b57cec5SDimitry Andric       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
10570b57cec5SDimitry Andric         DepTarget = OutputOpt->getValue();
10580b57cec5SDimitry Andric       } else {
10590b57cec5SDimitry Andric         // Otherwise derive from the base input.
10600b57cec5SDimitry Andric         //
10610b57cec5SDimitry Andric         // FIXME: This should use the computed output file location.
10620b57cec5SDimitry Andric         SmallString<128> P(Inputs[0].getBaseInput());
10630b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "o");
10640b57cec5SDimitry Andric         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
10650b57cec5SDimitry Andric       }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric       CmdArgs.push_back("-MT");
10680b57cec5SDimitry Andric       SmallString<128> Quoted;
1069753f127fSDimitry Andric       quoteMakeTarget(DepTarget, Quoted);
10700b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Quoted));
10710b57cec5SDimitry Andric     }
10720b57cec5SDimitry Andric 
1073a7dea167SDimitry Andric     if (ArgM->getOption().matches(options::OPT_M) ||
1074a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MD))
10750b57cec5SDimitry Andric       CmdArgs.push_back("-sys-header-deps");
10760b57cec5SDimitry Andric     if ((isa<PrecompileJobAction>(JA) &&
10770b57cec5SDimitry Andric          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
10780b57cec5SDimitry Andric         Args.hasArg(options::OPT_fmodule_file_deps))
10790b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-deps");
10800b57cec5SDimitry Andric   }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_MG)) {
1083a7dea167SDimitry Andric     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1084a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MMD))
10850b57cec5SDimitry Andric       D.Diag(diag::err_drv_mg_requires_m_or_mm);
10860b57cec5SDimitry Andric     CmdArgs.push_back("-MG");
10870b57cec5SDimitry Andric   }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MP);
10900b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MV);
10910b57cec5SDimitry Andric 
10925ffd83dbSDimitry Andric   // Add offload include arguments specific for CUDA/HIP.  This must happen
10935ffd83dbSDimitry Andric   // before we -I or -include anything else, because we must pick up the
10945ffd83dbSDimitry Andric   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
10955ffd83dbSDimitry Andric   // from e.g. /usr/local/include.
10960b57cec5SDimitry Andric   if (JA.isOffloading(Action::OFK_Cuda))
10970b57cec5SDimitry Andric     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
10985ffd83dbSDimitry Andric   if (JA.isOffloading(Action::OFK_HIP))
10995ffd83dbSDimitry Andric     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
11000b57cec5SDimitry Andric 
110106c3fb27SDimitry Andric   // If we are compiling for a GPU target we want to override the system headers
110206c3fb27SDimitry Andric   // with ones created by the 'libc' project if present.
110306c3fb27SDimitry Andric   if (!Args.hasArg(options::OPT_nostdinc) &&
110406c3fb27SDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
11055f757f3fSDimitry Andric       !Args.hasArg(options::OPT_nobuiltininc)) {
110606c3fb27SDimitry Andric     // Without an offloading language we will include these headers directly.
110706c3fb27SDimitry Andric     // Offloading languages will instead only use the declarations stored in
110806c3fb27SDimitry Andric     // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
11095f757f3fSDimitry Andric     if ((getToolChain().getTriple().isNVPTX() ||
11105f757f3fSDimitry Andric          getToolChain().getTriple().isAMDGCN()) &&
11115f757f3fSDimitry Andric         C.getActiveOffloadKinds() == Action::OFK_None) {
111206c3fb27SDimitry Andric       SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
111306c3fb27SDimitry Andric       llvm::sys::path::append(P, "include");
111406c3fb27SDimitry Andric       llvm::sys::path::append(P, "gpu-none-llvm");
111506c3fb27SDimitry Andric       CmdArgs.push_back("-c-isystem");
111606c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
111706c3fb27SDimitry Andric     } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
111806c3fb27SDimitry Andric       // TODO: CUDA / HIP include their own headers for some common functions
111906c3fb27SDimitry Andric       // implemented here. We'll need to clean those up so they do not conflict.
112006c3fb27SDimitry Andric       SmallString<128> P(D.ResourceDir);
112106c3fb27SDimitry Andric       llvm::sys::path::append(P, "include");
112206c3fb27SDimitry Andric       llvm::sys::path::append(P, "llvm_libc_wrappers");
112306c3fb27SDimitry Andric       CmdArgs.push_back("-internal-isystem");
112406c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
112506c3fb27SDimitry Andric     }
112606c3fb27SDimitry Andric   }
112706c3fb27SDimitry Andric 
11280b57cec5SDimitry Andric   // If we are offloading to a target via OpenMP we need to include the
11290b57cec5SDimitry Andric   // openmp_wrappers folder which contains alternative system headers.
11300b57cec5SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
113181ad6265SDimitry Andric       !Args.hasArg(options::OPT_nostdinc) &&
1132bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
113369ade1e0SDimitry Andric       (getToolChain().getTriple().isNVPTX() ||
113469ade1e0SDimitry Andric        getToolChain().getTriple().isAMDGCN())) {
11350b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_nobuiltininc)) {
11360b57cec5SDimitry Andric       // Add openmp_wrappers/* to our system include path.  This lets us wrap
11370b57cec5SDimitry Andric       // standard library headers.
11380b57cec5SDimitry Andric       SmallString<128> P(D.ResourceDir);
11390b57cec5SDimitry Andric       llvm::sys::path::append(P, "include");
11400b57cec5SDimitry Andric       llvm::sys::path::append(P, "openmp_wrappers");
11410b57cec5SDimitry Andric       CmdArgs.push_back("-internal-isystem");
11420b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
11430b57cec5SDimitry Andric     }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric     CmdArgs.push_back("-include");
11465ffd83dbSDimitry Andric     CmdArgs.push_back("__clang_openmp_device_functions.h");
11470b57cec5SDimitry Andric   }
11480b57cec5SDimitry Andric 
11490b57cec5SDimitry Andric   // Add -i* options, and automatically translate to
11500b57cec5SDimitry Andric   // -include-pch/-include-pth for transparent PCH support. It's
11510b57cec5SDimitry Andric   // wonky, but we include looking for .gch so we can support seamless
11520b57cec5SDimitry Andric   // replacement into a build system already set up to be generating
11530b57cec5SDimitry Andric   // .gch files.
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   if (getToolChain().getDriver().IsCLMode()) {
11560b57cec5SDimitry Andric     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
11570b57cec5SDimitry Andric     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
11580b57cec5SDimitry Andric     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
11590b57cec5SDimitry Andric         JA.getKind() <= Action::AssembleJobClass) {
11600b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1161f91b0c1cSDimitry Andric       // -fpch-instantiate-templates is the default when creating
1162f91b0c1cSDimitry Andric       // precomp using /Yc
1163f91b0c1cSDimitry Andric       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1164f91b0c1cSDimitry Andric                        options::OPT_fno_pch_instantiate_templates, true))
11655ffd83dbSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
11660b57cec5SDimitry Andric     }
11670b57cec5SDimitry Andric     if (YcArg || YuArg) {
11680b57cec5SDimitry Andric       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
11690b57cec5SDimitry Andric       if (!isa<PrecompileJobAction>(JA)) {
11700b57cec5SDimitry Andric         CmdArgs.push_back("-include-pch");
11710b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
11720b57cec5SDimitry Andric             C, !ThroughHeader.empty()
11730b57cec5SDimitry Andric                    ? ThroughHeader
11740b57cec5SDimitry Andric                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
11750b57cec5SDimitry Andric       }
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric       if (ThroughHeader.empty()) {
11780b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
11790b57cec5SDimitry Andric             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
11800b57cec5SDimitry Andric       } else {
11810b57cec5SDimitry Andric         CmdArgs.push_back(
11820b57cec5SDimitry Andric             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
11830b57cec5SDimitry Andric       }
11840b57cec5SDimitry Andric     }
11850b57cec5SDimitry Andric   }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   bool RenderedImplicitInclude = false;
11880b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
118981ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_include) &&
119081ad6265SDimitry Andric         D.getProbePrecompiled()) {
11910b57cec5SDimitry Andric       // Handling of gcc-style gch precompiled headers.
11920b57cec5SDimitry Andric       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
11930b57cec5SDimitry Andric       RenderedImplicitInclude = true;
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric       bool FoundPCH = false;
11960b57cec5SDimitry Andric       SmallString<128> P(A->getValue());
11970b57cec5SDimitry Andric       // We want the files to have a name like foo.h.pch. Add a dummy extension
11980b57cec5SDimitry Andric       // so that replace_extension does the right thing.
11990b57cec5SDimitry Andric       P += ".dummy";
12000b57cec5SDimitry Andric       llvm::sys::path::replace_extension(P, "pch");
120181ad6265SDimitry Andric       if (D.getVFS().exists(P))
12020b57cec5SDimitry Andric         FoundPCH = true;
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric       if (!FoundPCH) {
12055f757f3fSDimitry Andric         // For GCC compat, probe for a file or directory ending in .gch instead.
12060b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "gch");
12075f757f3fSDimitry Andric         FoundPCH = gchProbe(D, P.str());
12080b57cec5SDimitry Andric       }
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric       if (FoundPCH) {
12110b57cec5SDimitry Andric         if (IsFirstImplicitInclude) {
12120b57cec5SDimitry Andric           A->claim();
12130b57cec5SDimitry Andric           CmdArgs.push_back("-include-pch");
12140b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(P));
12150b57cec5SDimitry Andric           continue;
12160b57cec5SDimitry Andric         } else {
12170b57cec5SDimitry Andric           // Ignore the PCH if not first on command line and emit warning.
12180b57cec5SDimitry Andric           D.Diag(diag::warn_drv_pch_not_first_include) << P
12190b57cec5SDimitry Andric                                                        << A->getAsString(Args);
12200b57cec5SDimitry Andric         }
12210b57cec5SDimitry Andric       }
12220b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_isystem_after)) {
12230b57cec5SDimitry Andric       // Handling of paths which must come late.  These entries are handled by
12240b57cec5SDimitry Andric       // the toolchain itself after the resource dir is inserted in the right
12250b57cec5SDimitry Andric       // search order.
12260b57cec5SDimitry Andric       // Do not claim the argument so that the use of the argument does not
12270b57cec5SDimitry Andric       // silently go unnoticed on toolchains which do not honour the option.
12280b57cec5SDimitry Andric       continue;
1229a7dea167SDimitry Andric     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1230a7dea167SDimitry Andric       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1231a7dea167SDimitry Andric       continue;
123206c3fb27SDimitry Andric     } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
123306c3fb27SDimitry Andric       // This is used only by the driver. No need to pass to cc1.
123406c3fb27SDimitry Andric       continue;
12350b57cec5SDimitry Andric     }
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric     // Not translated, render as usual.
12380b57cec5SDimitry Andric     A->claim();
12390b57cec5SDimitry Andric     A->render(Args, CmdArgs);
12400b57cec5SDimitry Andric   }
12410b57cec5SDimitry Andric 
12425f757f3fSDimitry Andric   Args.addAllArgs(CmdArgs,
12430b57cec5SDimitry Andric                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
12440b57cec5SDimitry Andric                    options::OPT_F, options::OPT_index_header_map});
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric   // Add -Wp, and -Xpreprocessor if using the preprocessor.
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   // FIXME: There is a very unfortunate problem here, some troubled
12490b57cec5SDimitry Andric   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
12500b57cec5SDimitry Andric   // really support that we would have to parse and then translate
12510b57cec5SDimitry Andric   // those options. :(
12520b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
12530b57cec5SDimitry Andric                        options::OPT_Xpreprocessor);
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   // -I- is a deprecated GCC feature, reject it.
12560b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_I_))
12570b57cec5SDimitry Andric     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
12600b57cec5SDimitry Andric   // -isysroot to the CC1 invocation.
12610b57cec5SDimitry Andric   StringRef sysroot = C.getSysRoot();
12620b57cec5SDimitry Andric   if (sysroot != "") {
12630b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_isysroot)) {
12640b57cec5SDimitry Andric       CmdArgs.push_back("-isysroot");
12650b57cec5SDimitry Andric       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
12660b57cec5SDimitry Andric     }
12670b57cec5SDimitry Andric   }
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric   // Parse additional include paths from environment variables.
12700b57cec5SDimitry Andric   // FIXME: We should probably sink the logic for handling these from the
12710b57cec5SDimitry Andric   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
12720b57cec5SDimitry Andric   // CPATH - included following the user specified includes (but prior to
12730b57cec5SDimitry Andric   // builtin and standard includes).
12740b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
12750b57cec5SDimitry Andric   // C_INCLUDE_PATH - system includes enabled when compiling C.
12760b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
12770b57cec5SDimitry Andric   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
12780b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
12790b57cec5SDimitry Andric   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
12800b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
12810b57cec5SDimitry Andric   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
12820b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // While adding the include arguments, we also attempt to retrieve the
12850b57cec5SDimitry Andric   // arguments of related offloading toolchains or arguments that are specific
12860b57cec5SDimitry Andric   // of an offloading programming model.
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   // Add C++ include arguments, if needed.
1289a7dea167SDimitry Andric   if (types::isCXX(Inputs[0].getType())) {
1290a7dea167SDimitry Andric     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1291a7dea167SDimitry Andric     forAllAssociatedToolChains(
1292a7dea167SDimitry Andric         C, JA, getToolChain(),
1293a7dea167SDimitry Andric         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1294a7dea167SDimitry Andric           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1295a7dea167SDimitry Andric                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
12960b57cec5SDimitry Andric         });
1297a7dea167SDimitry Andric   }
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // Add system include arguments for all targets but IAMCU.
13000b57cec5SDimitry Andric   if (!IsIAMCU)
13010b57cec5SDimitry Andric     forAllAssociatedToolChains(C, JA, getToolChain(),
13020b57cec5SDimitry Andric                                [&Args, &CmdArgs](const ToolChain &TC) {
13030b57cec5SDimitry Andric                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
13040b57cec5SDimitry Andric                                });
13050b57cec5SDimitry Andric   else {
13060b57cec5SDimitry Andric     // For IAMCU add special include arguments.
13070b57cec5SDimitry Andric     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
13080b57cec5SDimitry Andric   }
1309480093f4SDimitry Andric 
1310480093f4SDimitry Andric   addMacroPrefixMapArg(D, Args, CmdArgs);
1311fe6060f1SDimitry Andric   addCoveragePrefixMapArg(D, Args, CmdArgs);
131281ad6265SDimitry Andric 
131381ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
131481ad6265SDimitry Andric                   options::OPT_fno_file_reproducible);
1315bdd1243dSDimitry Andric 
1316bdd1243dSDimitry Andric   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1317bdd1243dSDimitry Andric     CmdArgs.push_back("-source-date-epoch");
1318bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Epoch));
1319bdd1243dSDimitry Andric   }
13205f757f3fSDimitry Andric 
13215f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
13225f757f3fSDimitry Andric                     options::OPT_fno_define_target_os_macros);
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)13260b57cec5SDimitry Andric static bool isSignedCharDefault(const llvm::Triple &Triple) {
13270b57cec5SDimitry Andric   switch (Triple.getArch()) {
13280b57cec5SDimitry Andric   default:
13290b57cec5SDimitry Andric     return true;
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1332480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
13330b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
13340b57cec5SDimitry Andric   case llvm::Triple::arm:
13350b57cec5SDimitry Andric   case llvm::Triple::armeb:
13360b57cec5SDimitry Andric   case llvm::Triple::thumb:
13370b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
13380b57cec5SDimitry Andric     if (Triple.isOSDarwin() || Triple.isOSWindows())
13390b57cec5SDimitry Andric       return true;
13400b57cec5SDimitry Andric     return false;
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric   case llvm::Triple::ppc:
13430b57cec5SDimitry Andric   case llvm::Triple::ppc64:
13440b57cec5SDimitry Andric     if (Triple.isOSDarwin())
13450b57cec5SDimitry Andric       return true;
13460b57cec5SDimitry Andric     return false;
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   case llvm::Triple::hexagon:
1349e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
13500b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
13510b57cec5SDimitry Andric   case llvm::Triple::riscv32:
13520b57cec5SDimitry Andric   case llvm::Triple::riscv64:
13530b57cec5SDimitry Andric   case llvm::Triple::systemz:
13540b57cec5SDimitry Andric   case llvm::Triple::xcore:
13550b57cec5SDimitry Andric     return false;
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
hasMultipleInvocations(const llvm::Triple & Triple,const ArgList & Args)1359480093f4SDimitry Andric static bool hasMultipleInvocations(const llvm::Triple &Triple,
1360480093f4SDimitry Andric                                    const ArgList &Args) {
1361480093f4SDimitry Andric   // Supported only on Darwin where we invoke the compiler multiple times
1362480093f4SDimitry Andric   // followed by an invocation to lipo.
1363480093f4SDimitry Andric   if (!Triple.isOSDarwin())
1364480093f4SDimitry Andric     return false;
1365480093f4SDimitry Andric   // If more than one "-arch <arch>" is specified, we're targeting multiple
1366480093f4SDimitry Andric   // architectures resulting in a fat binary.
1367480093f4SDimitry Andric   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1368480093f4SDimitry Andric }
1369480093f4SDimitry Andric 
checkRemarksOptions(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)1370480093f4SDimitry Andric static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1371480093f4SDimitry Andric                                 const llvm::Triple &Triple) {
1372480093f4SDimitry Andric   // When enabling remarks, we need to error if:
1373480093f4SDimitry Andric   // * The remark file is specified but we're targeting multiple architectures,
1374480093f4SDimitry Andric   // which means more than one remark file is being generated.
1375480093f4SDimitry Andric   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1376480093f4SDimitry Andric   bool hasExplicitOutputFile =
1377480093f4SDimitry Andric       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1378480093f4SDimitry Andric   if (hasMultipleInvocations && hasExplicitOutputFile) {
1379480093f4SDimitry Andric     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1380480093f4SDimitry Andric         << "-foptimization-record-file";
1381480093f4SDimitry Andric     return false;
1382480093f4SDimitry Andric   }
1383480093f4SDimitry Andric   return true;
1384480093f4SDimitry Andric }
1385480093f4SDimitry Andric 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const JobAction & JA)1386480093f4SDimitry Andric static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1387480093f4SDimitry Andric                                  const llvm::Triple &Triple,
1388480093f4SDimitry Andric                                  const InputInfo &Input,
1389480093f4SDimitry Andric                                  const InputInfo &Output, const JobAction &JA) {
1390480093f4SDimitry Andric   StringRef Format = "yaml";
1391480093f4SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1392480093f4SDimitry Andric     Format = A->getValue();
1393480093f4SDimitry Andric 
1394480093f4SDimitry Andric   CmdArgs.push_back("-opt-record-file");
1395480093f4SDimitry Andric 
1396480093f4SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1397480093f4SDimitry Andric   if (A) {
1398480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1399480093f4SDimitry Andric   } else {
1400480093f4SDimitry Andric     bool hasMultipleArchs =
1401480093f4SDimitry Andric         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1402480093f4SDimitry Andric         Args.getAllArgValues(options::OPT_arch).size() > 1;
1403480093f4SDimitry Andric 
1404480093f4SDimitry Andric     SmallString<128> F;
1405480093f4SDimitry Andric 
1406480093f4SDimitry Andric     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1407480093f4SDimitry Andric       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1408480093f4SDimitry Andric         F = FinalOutput->getValue();
1409480093f4SDimitry Andric     } else {
1410480093f4SDimitry Andric       if (Format != "yaml" && // For YAML, keep the original behavior.
1411480093f4SDimitry Andric           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1412480093f4SDimitry Andric           Output.isFilename())
1413480093f4SDimitry Andric         F = Output.getFilename();
1414480093f4SDimitry Andric     }
1415480093f4SDimitry Andric 
1416480093f4SDimitry Andric     if (F.empty()) {
1417480093f4SDimitry Andric       // Use the input filename.
1418480093f4SDimitry Andric       F = llvm::sys::path::stem(Input.getBaseInput());
1419480093f4SDimitry Andric 
1420480093f4SDimitry Andric       // If we're compiling for an offload architecture (i.e. a CUDA device),
1421480093f4SDimitry Andric       // we need to make the file name for the device compilation different
1422480093f4SDimitry Andric       // from the host compilation.
1423480093f4SDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1424480093f4SDimitry Andric           !JA.isDeviceOffloading(Action::OFK_Host)) {
1425480093f4SDimitry Andric         llvm::sys::path::replace_extension(F, "");
1426480093f4SDimitry Andric         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1427480093f4SDimitry Andric                                                  Triple.normalize());
1428480093f4SDimitry Andric         F += "-";
1429480093f4SDimitry Andric         F += JA.getOffloadingArch();
1430480093f4SDimitry Andric       }
1431480093f4SDimitry Andric     }
1432480093f4SDimitry Andric 
1433480093f4SDimitry Andric     // If we're having more than one "-arch", we should name the files
1434480093f4SDimitry Andric     // differently so that every cc1 invocation writes to a different file.
1435480093f4SDimitry Andric     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1436480093f4SDimitry Andric     // name from the triple.
1437480093f4SDimitry Andric     if (hasMultipleArchs) {
1438480093f4SDimitry Andric       // First, remember the extension.
1439480093f4SDimitry Andric       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1440480093f4SDimitry Andric       // then, remove it.
1441480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, "");
1442480093f4SDimitry Andric       // attach -<arch> to it.
1443480093f4SDimitry Andric       F += "-";
1444480093f4SDimitry Andric       F += Triple.getArchName();
1445480093f4SDimitry Andric       // put back the extension.
1446480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, OldExtension);
1447480093f4SDimitry Andric     }
1448480093f4SDimitry Andric 
1449480093f4SDimitry Andric     SmallString<32> Extension;
1450480093f4SDimitry Andric     Extension += "opt.";
1451480093f4SDimitry Andric     Extension += Format;
1452480093f4SDimitry Andric 
1453480093f4SDimitry Andric     llvm::sys::path::replace_extension(F, Extension);
1454480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(F));
1455480093f4SDimitry Andric   }
1456480093f4SDimitry Andric 
1457480093f4SDimitry Andric   if (const Arg *A =
1458480093f4SDimitry Andric           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1459480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-passes");
1460480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1461480093f4SDimitry Andric   }
1462480093f4SDimitry Andric 
1463480093f4SDimitry Andric   if (!Format.empty()) {
1464480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-format");
1465480093f4SDimitry Andric     CmdArgs.push_back(Format.data());
1466480093f4SDimitry Andric   }
1467480093f4SDimitry Andric }
1468480093f4SDimitry Andric 
AddAAPCSVolatileBitfieldArgs(const ArgList & Args,ArgStringList & CmdArgs)1469fe6060f1SDimitry Andric void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1470fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1471fe6060f1SDimitry Andric                     options::OPT_fno_aapcs_bitfield_width, true))
1472fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1473fe6060f1SDimitry Andric 
1474fe6060f1SDimitry Andric   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1475fe6060f1SDimitry Andric     CmdArgs.push_back("-faapcs-bitfield-load");
1476fe6060f1SDimitry Andric }
1477fe6060f1SDimitry Andric 
14780b57cec5SDimitry Andric namespace {
RenderARMABI(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1479349cc55cSDimitry Andric void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1480349cc55cSDimitry Andric                   const ArgList &Args, ArgStringList &CmdArgs) {
14810b57cec5SDimitry Andric   // Select the ABI to use.
14820b57cec5SDimitry Andric   // FIXME: Support -meabi.
14830b57cec5SDimitry Andric   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
14840b57cec5SDimitry Andric   const char *ABIName = nullptr;
14850b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
14860b57cec5SDimitry Andric     ABIName = A->getValue();
14870b57cec5SDimitry Andric   } else {
1488349cc55cSDimitry Andric     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
14890b57cec5SDimitry Andric     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
14900b57cec5SDimitry Andric   }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
14930b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
14940b57cec5SDimitry Andric }
149581ad6265SDimitry Andric 
AddUnalignedAccessWarning(ArgStringList & CmdArgs)149681ad6265SDimitry Andric void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
149781ad6265SDimitry Andric   auto StrictAlignIter =
1498bdd1243dSDimitry Andric       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
149981ad6265SDimitry Andric         return Arg == "+strict-align" || Arg == "-strict-align";
150081ad6265SDimitry Andric       });
150181ad6265SDimitry Andric   if (StrictAlignIter != CmdArgs.rend() &&
150281ad6265SDimitry Andric       StringRef(*StrictAlignIter) == "+strict-align")
150381ad6265SDimitry Andric     CmdArgs.push_back("-Wunaligned-access");
150481ad6265SDimitry Andric }
15050b57cec5SDimitry Andric }
15060b57cec5SDimitry Andric 
CollectARMPACBTIOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool isAArch64)15071fd87a68SDimitry Andric static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
15084824e7fdSDimitry Andric                                     ArgStringList &CmdArgs, bool isAArch64) {
15094824e7fdSDimitry Andric   const Arg *A = isAArch64
15104824e7fdSDimitry Andric                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
15114824e7fdSDimitry Andric                                        options::OPT_mbranch_protection_EQ)
15124824e7fdSDimitry Andric                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
15134824e7fdSDimitry Andric   if (!A)
15144824e7fdSDimitry Andric     return;
15154824e7fdSDimitry Andric 
15161fd87a68SDimitry Andric   const Driver &D = TC.getDriver();
15171fd87a68SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
15181fd87a68SDimitry Andric   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1519d56accc7SDimitry Andric     D.Diag(diag::warn_incompatible_branch_protection_option)
15201fd87a68SDimitry Andric         << Triple.getArchName();
15211fd87a68SDimitry Andric 
15224824e7fdSDimitry Andric   StringRef Scope, Key;
1523297eecfbSDimitry Andric   bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
15244824e7fdSDimitry Andric 
15254824e7fdSDimitry Andric   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
15264824e7fdSDimitry Andric     Scope = A->getValue();
152781ad6265SDimitry Andric     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
152881ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1529bdd1243dSDimitry Andric           << A->getSpelling() << Scope;
15304824e7fdSDimitry Andric     Key = "a_key";
15314824e7fdSDimitry Andric     IndirectBranches = false;
1532cb14a3feSDimitry Andric     BranchProtectionPAuthLR = false;
1533297eecfbSDimitry Andric     GuardedControlStack = false;
15344824e7fdSDimitry Andric   } else {
15354824e7fdSDimitry Andric     StringRef DiagMsg;
15364824e7fdSDimitry Andric     llvm::ARM::ParsedBranchProtection PBP;
15374824e7fdSDimitry Andric     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
153881ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1539bdd1243dSDimitry Andric           << A->getSpelling() << DiagMsg;
15404824e7fdSDimitry Andric     if (!isAArch64 && PBP.Key == "b_key")
15414824e7fdSDimitry Andric       D.Diag(diag::warn_unsupported_branch_protection)
15424824e7fdSDimitry Andric           << "b-key" << A->getAsString(Args);
15434824e7fdSDimitry Andric     Scope = PBP.Scope;
15444824e7fdSDimitry Andric     Key = PBP.Key;
1545cb14a3feSDimitry Andric     BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
15464824e7fdSDimitry Andric     IndirectBranches = PBP.BranchTargetEnforcement;
1547297eecfbSDimitry Andric     GuardedControlStack = PBP.GuardedControlStack;
15484824e7fdSDimitry Andric   }
15494824e7fdSDimitry Andric 
15504824e7fdSDimitry Andric   CmdArgs.push_back(
15514824e7fdSDimitry Andric       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
15524824e7fdSDimitry Andric   if (!Scope.equals("none"))
15534824e7fdSDimitry Andric     CmdArgs.push_back(
15544824e7fdSDimitry Andric         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1555cb14a3feSDimitry Andric   if (BranchProtectionPAuthLR)
1556cb14a3feSDimitry Andric     CmdArgs.push_back(
1557cb14a3feSDimitry Andric         Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
15584824e7fdSDimitry Andric   if (IndirectBranches)
15594824e7fdSDimitry Andric     CmdArgs.push_back("-mbranch-target-enforce");
1560297eecfbSDimitry Andric   if (GuardedControlStack)
1561297eecfbSDimitry Andric     CmdArgs.push_back("-mguarded-control-stack");
15624824e7fdSDimitry Andric }
15634824e7fdSDimitry Andric 
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const15640b57cec5SDimitry Andric void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
15650b57cec5SDimitry Andric                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1566349cc55cSDimitry Andric   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric   // Determine floating point ABI from the options & target defaults.
15690b57cec5SDimitry Andric   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
15700b57cec5SDimitry Andric   if (ABI == arm::FloatABI::Soft) {
15710b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
15720b57cec5SDimitry Andric     // FIXME: This changes CPP defines, we need -target-soft-float.
15730b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
15740b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15750b57cec5SDimitry Andric     CmdArgs.push_back("soft");
15760b57cec5SDimitry Andric   } else if (ABI == arm::FloatABI::SoftFP) {
15770b57cec5SDimitry Andric     // Floating point operations are hard, but argument passing is soft.
15780b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15790b57cec5SDimitry Andric     CmdArgs.push_back("soft");
15800b57cec5SDimitry Andric   } else {
15810b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
15820b57cec5SDimitry Andric     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
15830b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15840b57cec5SDimitry Andric     CmdArgs.push_back("hard");
15850b57cec5SDimitry Andric   }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
15880b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
15890b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
15900b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
15910b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
15920b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=false");
15930b57cec5SDimitry Andric     else
15940b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=true");
15950b57cec5SDimitry Andric   }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
15980b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
15990b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mcmse))
16020b57cec5SDimitry Andric     CmdArgs.push_back("-mcmse");
1603fe6060f1SDimitry Andric 
1604fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
16054824e7fdSDimitry Andric 
16064824e7fdSDimitry Andric   // Enable/disable return address signing and indirect branch targets.
16071fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
160881ad6265SDimitry Andric 
160981ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric 
RenderTargetOptions(const llvm::Triple & EffectiveTriple,const ArgList & Args,bool KernelOrKext,ArgStringList & CmdArgs) const16120b57cec5SDimitry Andric void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
16130b57cec5SDimitry Andric                                 const ArgList &Args, bool KernelOrKext,
16140b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
16150b57cec5SDimitry Andric   const ToolChain &TC = getToolChain();
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // Add the target features
16185ffd83dbSDimitry Andric   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric   // Add target specific flags.
16210b57cec5SDimitry Andric   switch (TC.getArch()) {
16220b57cec5SDimitry Andric   default:
16230b57cec5SDimitry Andric     break;
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   case llvm::Triple::arm:
16260b57cec5SDimitry Andric   case llvm::Triple::armeb:
16270b57cec5SDimitry Andric   case llvm::Triple::thumb:
16280b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
16290b57cec5SDimitry Andric     // Use the effective triple, which takes into account the deployment target.
16300b57cec5SDimitry Andric     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
16310b57cec5SDimitry Andric     break;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1634480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
16350b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
16360b57cec5SDimitry Andric     AddAArch64TargetArgs(Args, CmdArgs);
1637bdd1243dSDimitry Andric     break;
1638bdd1243dSDimitry Andric 
1639bdd1243dSDimitry Andric   case llvm::Triple::loongarch32:
1640bdd1243dSDimitry Andric   case llvm::Triple::loongarch64:
1641bdd1243dSDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
16420b57cec5SDimitry Andric     break;
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   case llvm::Triple::mips:
16450b57cec5SDimitry Andric   case llvm::Triple::mipsel:
16460b57cec5SDimitry Andric   case llvm::Triple::mips64:
16470b57cec5SDimitry Andric   case llvm::Triple::mips64el:
16480b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
16490b57cec5SDimitry Andric     break;
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   case llvm::Triple::ppc:
1652e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
16530b57cec5SDimitry Andric   case llvm::Triple::ppc64:
16540b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
16550b57cec5SDimitry Andric     AddPPCTargetArgs(Args, CmdArgs);
16560b57cec5SDimitry Andric     break;
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   case llvm::Triple::riscv32:
16590b57cec5SDimitry Andric   case llvm::Triple::riscv64:
16600b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
16610b57cec5SDimitry Andric     break;
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric   case llvm::Triple::sparc:
16640b57cec5SDimitry Andric   case llvm::Triple::sparcel:
16650b57cec5SDimitry Andric   case llvm::Triple::sparcv9:
16660b57cec5SDimitry Andric     AddSparcTargetArgs(Args, CmdArgs);
16670b57cec5SDimitry Andric     break;
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   case llvm::Triple::systemz:
16700b57cec5SDimitry Andric     AddSystemZTargetArgs(Args, CmdArgs);
16710b57cec5SDimitry Andric     break;
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   case llvm::Triple::x86:
16740b57cec5SDimitry Andric   case llvm::Triple::x86_64:
16750b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
16760b57cec5SDimitry Andric     break;
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   case llvm::Triple::lanai:
16790b57cec5SDimitry Andric     AddLanaiTargetArgs(Args, CmdArgs);
16800b57cec5SDimitry Andric     break;
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   case llvm::Triple::hexagon:
16830b57cec5SDimitry Andric     AddHexagonTargetArgs(Args, CmdArgs);
16840b57cec5SDimitry Andric     break;
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   case llvm::Triple::wasm32:
16870b57cec5SDimitry Andric   case llvm::Triple::wasm64:
16880b57cec5SDimitry Andric     AddWebAssemblyTargetArgs(Args, CmdArgs);
16890b57cec5SDimitry Andric     break;
16905ffd83dbSDimitry Andric 
16915ffd83dbSDimitry Andric   case llvm::Triple::ve:
16925ffd83dbSDimitry Andric     AddVETargetArgs(Args, CmdArgs);
16935ffd83dbSDimitry Andric     break;
16940b57cec5SDimitry Andric   }
16950b57cec5SDimitry Andric }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric namespace {
RenderAArch64ABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)16980b57cec5SDimitry Andric void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
16990b57cec5SDimitry Andric                       ArgStringList &CmdArgs) {
17000b57cec5SDimitry Andric   const char *ABIName = nullptr;
17010b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
17020b57cec5SDimitry Andric     ABIName = A->getValue();
17030b57cec5SDimitry Andric   else if (Triple.isOSDarwin())
17040b57cec5SDimitry Andric     ABIName = "darwinpcs";
17050b57cec5SDimitry Andric   else
17060b57cec5SDimitry Andric     ABIName = "aapcs";
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
17090b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric }
17120b57cec5SDimitry Andric 
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const17130b57cec5SDimitry Andric void Clang::AddAArch64TargetArgs(const ArgList &Args,
17140b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
17150b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
17180b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
17190b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
17200b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
17230b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
17240b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   RenderAArch64ABI(Triple, Args, CmdArgs);
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
17290b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
17300b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
17310b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
17320b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
17330b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=false");
17340b57cec5SDimitry Andric     else
17350b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=true");
17360b57cec5SDimitry Andric   }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   // Enable/disable return address signing and indirect branch targets.
17391fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1740e8d8bef9SDimitry Andric 
1741e8d8bef9SDimitry Andric   // Handle -msve_vector_bits=<bits>
1742e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1743e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
1744e8d8bef9SDimitry Andric     const Driver &D = getToolChain().getDriver();
1745e8d8bef9SDimitry Andric     if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1746349cc55cSDimitry Andric         Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1747349cc55cSDimitry Andric         Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1748349cc55cSDimitry Andric         Val.equals("2048+")) {
1749349cc55cSDimitry Andric       unsigned Bits = 0;
17505f757f3fSDimitry Andric       if (Val.ends_with("+"))
1751349cc55cSDimitry Andric         Val = Val.substr(0, Val.size() - 1);
1752349cc55cSDimitry Andric       else {
1753349cc55cSDimitry Andric         bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1754349cc55cSDimitry Andric         assert(!Invalid && "Failed to parse value");
1755e8d8bef9SDimitry Andric         CmdArgs.push_back(
1756349cc55cSDimitry Andric             Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1757349cc55cSDimitry Andric       }
1758349cc55cSDimitry Andric 
1759349cc55cSDimitry Andric       bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1760349cc55cSDimitry Andric       assert(!Invalid && "Failed to parse value");
1761349cc55cSDimitry Andric       CmdArgs.push_back(
1762349cc55cSDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1763e8d8bef9SDimitry Andric     // Silently drop requests for vector-length agnostic code as it's implied.
1764349cc55cSDimitry Andric     } else if (!Val.equals("scalable"))
1765e8d8bef9SDimitry Andric       // Handle the unsupported values passed to msve-vector-bits.
1766e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1767bdd1243dSDimitry Andric           << A->getSpelling() << Val;
1768e8d8bef9SDimitry Andric   }
1769fe6060f1SDimitry Andric 
1770fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1771349cc55cSDimitry Andric 
1772349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1773349cc55cSDimitry Andric     CmdArgs.push_back("-tune-cpu");
1774fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
1775fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1776fcaf7f86SDimitry Andric     else
1777fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
1778349cc55cSDimitry Andric   }
177981ad6265SDimitry Andric 
178081ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
17810b57cec5SDimitry Andric }
17820b57cec5SDimitry Andric 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1783bdd1243dSDimitry Andric void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1784bdd1243dSDimitry Andric                                    ArgStringList &CmdArgs) const {
17858a4dda33SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
17868a4dda33SDimitry Andric 
1787bdd1243dSDimitry Andric   CmdArgs.push_back("-target-abi");
17888a4dda33SDimitry Andric   CmdArgs.push_back(
17898a4dda33SDimitry Andric       loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1790bdd1243dSDimitry Andric           .data());
17918a4dda33SDimitry Andric 
17928a4dda33SDimitry Andric   // Handle -mtune.
17938a4dda33SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
17948a4dda33SDimitry Andric     std::string TuneCPU = A->getValue();
17958a4dda33SDimitry Andric     TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
17968a4dda33SDimitry Andric     CmdArgs.push_back("-tune-cpu");
17978a4dda33SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
17988a4dda33SDimitry Andric   }
1799bdd1243dSDimitry Andric }
1800bdd1243dSDimitry Andric 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const18010b57cec5SDimitry Andric void Clang::AddMIPSTargetArgs(const ArgList &Args,
18020b57cec5SDimitry Andric                               ArgStringList &CmdArgs) const {
18030b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
18040b57cec5SDimitry Andric   StringRef CPUName;
18050b57cec5SDimitry Andric   StringRef ABIName;
18060b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
18070b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
18100b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
18130b57cec5SDimitry Andric   if (ABI == mips::FloatABI::Soft) {
18140b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
18150b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
18160b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
18170b57cec5SDimitry Andric     CmdArgs.push_back("soft");
18180b57cec5SDimitry Andric   } else {
18190b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
18200b57cec5SDimitry Andric     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
18210b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
18220b57cec5SDimitry Andric     CmdArgs.push_back("hard");
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
18260b57cec5SDimitry Andric                                options::OPT_mno_ldc1_sdc1)) {
18270b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
18280b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18290b57cec5SDimitry Andric       CmdArgs.push_back("-mno-ldc1-sdc1");
18300b57cec5SDimitry Andric     }
18310b57cec5SDimitry Andric   }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
18340b57cec5SDimitry Andric                                options::OPT_mno_check_zero_division)) {
18350b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
18360b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18370b57cec5SDimitry Andric       CmdArgs.push_back("-mno-check-zero-division");
18380b57cec5SDimitry Andric     }
18390b57cec5SDimitry Andric   }
18400b57cec5SDimitry Andric 
184104eeddc0SDimitry Andric   if (Args.getLastArg(options::OPT_mfix4300)) {
184204eeddc0SDimitry Andric     CmdArgs.push_back("-mllvm");
184304eeddc0SDimitry Andric     CmdArgs.push_back("-mfix4300");
184404eeddc0SDimitry Andric   }
184504eeddc0SDimitry Andric 
18460b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_G)) {
18470b57cec5SDimitry Andric     StringRef v = A->getValue();
18480b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
18490b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
18500b57cec5SDimitry Andric     A->claim();
18510b57cec5SDimitry Andric   }
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
18540b57cec5SDimitry Andric   Arg *ABICalls =
18550b57cec5SDimitry Andric       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
18580b57cec5SDimitry Andric   // -mgpopt is the default for static, -fno-pic environments but these two
18590b57cec5SDimitry Andric   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
18600b57cec5SDimitry Andric   // the only case where -mllvm -mgpopt is passed.
18610b57cec5SDimitry Andric   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
18620b57cec5SDimitry Andric   //       passed explicitly when compiling something with -mabicalls
18630b57cec5SDimitry Andric   //       (implictly) in affect. Currently the warning is in the backend.
18640b57cec5SDimitry Andric   //
18650b57cec5SDimitry Andric   // When the ABI in use is  N64, we also need to determine the PIC mode that
18660b57cec5SDimitry Andric   // is in use, as -fno-pic for N64 implies -mno-abicalls.
18670b57cec5SDimitry Andric   bool NoABICalls =
18680b57cec5SDimitry Andric       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
18710b57cec5SDimitry Andric   unsigned PICLevel;
18720b57cec5SDimitry Andric   bool IsPIE;
18730b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
18740b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric   NoABICalls = NoABICalls ||
18770b57cec5SDimitry Andric                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
18800b57cec5SDimitry Andric   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
18810b57cec5SDimitry Andric   if (NoABICalls && (!GPOpt || WantGPOpt)) {
18820b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
18830b57cec5SDimitry Andric     CmdArgs.push_back("-mgpopt");
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
18860b57cec5SDimitry Andric                                       options::OPT_mno_local_sdata);
18870b57cec5SDimitry Andric     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
18880b57cec5SDimitry Andric                                        options::OPT_mno_extern_sdata);
18890b57cec5SDimitry Andric     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
18900b57cec5SDimitry Andric                                         options::OPT_mno_embedded_data);
18910b57cec5SDimitry Andric     if (LocalSData) {
18920b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18930b57cec5SDimitry Andric       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
18940b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=1");
18950b57cec5SDimitry Andric       } else {
18960b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=0");
18970b57cec5SDimitry Andric       }
18980b57cec5SDimitry Andric       LocalSData->claim();
18990b57cec5SDimitry Andric     }
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric     if (ExternSData) {
19020b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19030b57cec5SDimitry Andric       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
19040b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=1");
19050b57cec5SDimitry Andric       } else {
19060b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=0");
19070b57cec5SDimitry Andric       }
19080b57cec5SDimitry Andric       ExternSData->claim();
19090b57cec5SDimitry Andric     }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric     if (EmbeddedData) {
19120b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19130b57cec5SDimitry Andric       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
19140b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=1");
19150b57cec5SDimitry Andric       } else {
19160b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=0");
19170b57cec5SDimitry Andric       }
19180b57cec5SDimitry Andric       EmbeddedData->claim();
19190b57cec5SDimitry Andric     }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
19220b57cec5SDimitry Andric     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   if (GPOpt)
19250b57cec5SDimitry Andric     GPOpt->claim();
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
19280b57cec5SDimitry Andric     StringRef Val = StringRef(A->getValue());
19290b57cec5SDimitry Andric     if (mips::hasCompactBranches(CPUName)) {
19300b57cec5SDimitry Andric       if (Val == "never" || Val == "always" || Val == "optimal") {
19310b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
19320b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
19330b57cec5SDimitry Andric       } else
19340b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
1935bdd1243dSDimitry Andric             << A->getSpelling() << Val;
19360b57cec5SDimitry Andric     } else
19370b57cec5SDimitry Andric       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
19380b57cec5SDimitry Andric   }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
19410b57cec5SDimitry Andric                                options::OPT_mno_relax_pic_calls)) {
19420b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
19430b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19440b57cec5SDimitry Andric       CmdArgs.push_back("-mips-jalr-reloc=0");
19450b57cec5SDimitry Andric     }
19460b57cec5SDimitry Andric   }
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const19490b57cec5SDimitry Andric void Clang::AddPPCTargetArgs(const ArgList &Args,
19500b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
195106c3fb27SDimitry Andric   const Driver &D = getToolChain().getDriver();
19521ac55f4cSDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
195306c3fb27SDimitry Andric   if (Args.getLastArg(options::OPT_mtune_EQ)) {
1954bdd1243dSDimitry Andric     CmdArgs.push_back("-tune-cpu");
19551ac55f4cSDimitry Andric     std::string CPU = ppc::getPPCTuneCPU(Args, T);
19561ac55f4cSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
1957bdd1243dSDimitry Andric   }
1958bdd1243dSDimitry Andric 
19590b57cec5SDimitry Andric   // Select the ABI to use.
19600b57cec5SDimitry Andric   const char *ABIName = nullptr;
1961480093f4SDimitry Andric   if (T.isOSBinFormatELF()) {
19620b57cec5SDimitry Andric     switch (getToolChain().getArch()) {
19630b57cec5SDimitry Andric     case llvm::Triple::ppc64: {
19641ac55f4cSDimitry Andric       if (T.isPPC64ELFv2ABI())
1965480093f4SDimitry Andric         ABIName = "elfv2";
1966480093f4SDimitry Andric       else
19670b57cec5SDimitry Andric         ABIName = "elfv1";
19680b57cec5SDimitry Andric       break;
19690b57cec5SDimitry Andric     }
19700b57cec5SDimitry Andric     case llvm::Triple::ppc64le:
19710b57cec5SDimitry Andric       ABIName = "elfv2";
19720b57cec5SDimitry Andric       break;
19730b57cec5SDimitry Andric     default:
19740b57cec5SDimitry Andric       break;
19750b57cec5SDimitry Andric     }
1976480093f4SDimitry Andric   }
19770b57cec5SDimitry Andric 
197804eeddc0SDimitry Andric   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
197906c3fb27SDimitry Andric   bool VecExtabi = false;
19800b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
19810b57cec5SDimitry Andric     StringRef V = A->getValue();
198206c3fb27SDimitry Andric     if (V == "ieeelongdouble") {
19830b57cec5SDimitry Andric       IEEELongDouble = true;
198406c3fb27SDimitry Andric       A->claim();
198506c3fb27SDimitry Andric     } else if (V == "ibmlongdouble") {
19860b57cec5SDimitry Andric       IEEELongDouble = false;
198706c3fb27SDimitry Andric       A->claim();
198806c3fb27SDimitry Andric     } else if (V == "vec-default") {
198906c3fb27SDimitry Andric       VecExtabi = false;
199006c3fb27SDimitry Andric       A->claim();
199106c3fb27SDimitry Andric     } else if (V == "vec-extabi") {
199206c3fb27SDimitry Andric       VecExtabi = true;
199306c3fb27SDimitry Andric       A->claim();
19948a4dda33SDimitry Andric     } else if (V == "elfv1") {
19958a4dda33SDimitry Andric       ABIName = "elfv1";
19968a4dda33SDimitry Andric       A->claim();
19978a4dda33SDimitry Andric     } else if (V == "elfv2") {
19988a4dda33SDimitry Andric       ABIName = "elfv2";
19998a4dda33SDimitry Andric       A->claim();
200006c3fb27SDimitry Andric     } else if (V != "altivec")
20010b57cec5SDimitry Andric       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
20020b57cec5SDimitry Andric       // the option if given as we don't have backend support for any targets
20030b57cec5SDimitry Andric       // that don't use the altivec abi.
20040b57cec5SDimitry Andric       ABIName = A->getValue();
20050b57cec5SDimitry Andric   }
20060b57cec5SDimitry Andric   if (IEEELongDouble)
20070b57cec5SDimitry Andric     CmdArgs.push_back("-mabi=ieeelongdouble");
200806c3fb27SDimitry Andric   if (VecExtabi) {
200906c3fb27SDimitry Andric     if (!T.isOSAIX())
201006c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
201106c3fb27SDimitry Andric           << "-mabi=vec-extabi" << T.str();
201206c3fb27SDimitry Andric     CmdArgs.push_back("-mabi=vec-extabi");
201306c3fb27SDimitry Andric   }
20140b57cec5SDimitry Andric 
201506c3fb27SDimitry Andric   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
20160b57cec5SDimitry Andric   if (FloatABI == ppc::FloatABI::Soft) {
20170b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
20180b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
20190b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
20200b57cec5SDimitry Andric     CmdArgs.push_back("soft");
20210b57cec5SDimitry Andric   } else {
20220b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
20230b57cec5SDimitry Andric     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
20240b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
20250b57cec5SDimitry Andric     CmdArgs.push_back("hard");
20260b57cec5SDimitry Andric   }
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   if (ABIName) {
20290b57cec5SDimitry Andric     CmdArgs.push_back("-target-abi");
20300b57cec5SDimitry Andric     CmdArgs.push_back(ABIName);
20310b57cec5SDimitry Andric   }
20320b57cec5SDimitry Andric }
20330b57cec5SDimitry Andric 
SetRISCVSmallDataLimit(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)20345ffd83dbSDimitry Andric static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
20355ffd83dbSDimitry Andric                                    ArgStringList &CmdArgs) {
20365ffd83dbSDimitry Andric   const Driver &D = TC.getDriver();
20375ffd83dbSDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
20385ffd83dbSDimitry Andric   // Default small data limitation is eight.
20395ffd83dbSDimitry Andric   const char *SmallDataLimit = "8";
20405ffd83dbSDimitry Andric   // Get small data limitation.
20415ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
20425ffd83dbSDimitry Andric                       options::OPT_fPIC)) {
20435ffd83dbSDimitry Andric     // Not support linker relaxation for PIC.
20445ffd83dbSDimitry Andric     SmallDataLimit = "0";
20455ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
20465ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
20475ffd83dbSDimitry Andric     }
20485ffd83dbSDimitry Andric   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2049fe6060f1SDimitry Andric                  .equals_insensitive("large") &&
20505ffd83dbSDimitry Andric              (Triple.getArch() == llvm::Triple::riscv64)) {
20515ffd83dbSDimitry Andric     // Not support linker relaxation for RV64 with large code model.
20525ffd83dbSDimitry Andric     SmallDataLimit = "0";
20535ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
20545ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
20555ffd83dbSDimitry Andric     }
205606c3fb27SDimitry Andric   } else if (Triple.isAndroid()) {
205706c3fb27SDimitry Andric     // GP relaxation is not supported on Android.
205806c3fb27SDimitry Andric     SmallDataLimit = "0";
205906c3fb27SDimitry Andric     if (Args.hasArg(options::OPT_G)) {
206006c3fb27SDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
206106c3fb27SDimitry Andric     }
20625ffd83dbSDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
20635ffd83dbSDimitry Andric     SmallDataLimit = A->getValue();
20645ffd83dbSDimitry Andric   }
20655ffd83dbSDimitry Andric   // Forward the -msmall-data-limit= option.
20665ffd83dbSDimitry Andric   CmdArgs.push_back("-msmall-data-limit");
20675ffd83dbSDimitry Andric   CmdArgs.push_back(SmallDataLimit);
20685ffd83dbSDimitry Andric }
20695ffd83dbSDimitry Andric 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const20700b57cec5SDimitry Andric void Clang::AddRISCVTargetArgs(const ArgList &Args,
20710b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
20720b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
2073a7dea167SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
2076a7dea167SDimitry Andric   CmdArgs.push_back(ABIName.data());
20775ffd83dbSDimitry Andric 
20785ffd83dbSDimitry Andric   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2079e8d8bef9SDimitry Andric 
2080bdd1243dSDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
2081bdd1243dSDimitry Andric                     options::OPT_mno_implicit_float, true))
2082bdd1243dSDimitry Andric     CmdArgs.push_back("-no-implicit-float");
2083bdd1243dSDimitry Andric 
2084fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2085e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2086bdd1243dSDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2087bdd1243dSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2088bdd1243dSDimitry Andric     else
2089bdd1243dSDimitry Andric       CmdArgs.push_back(A->getValue());
2090e8d8bef9SDimitry Andric   }
209106c3fb27SDimitry Andric 
209206c3fb27SDimitry Andric   // Handle -mrvv-vector-bits=<bits>
209306c3fb27SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
209406c3fb27SDimitry Andric     StringRef Val = A->getValue();
209506c3fb27SDimitry Andric     const Driver &D = getToolChain().getDriver();
209606c3fb27SDimitry Andric 
209706c3fb27SDimitry Andric     // Get minimum VLen from march.
209806c3fb27SDimitry Andric     unsigned MinVLen = 0;
209906c3fb27SDimitry Andric     StringRef Arch = riscv::getRISCVArch(Args, Triple);
210006c3fb27SDimitry Andric     auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
210106c3fb27SDimitry Andric         Arch, /*EnableExperimentalExtensions*/ true);
210206c3fb27SDimitry Andric     // Ignore parsing error.
2103647cbc5dSDimitry Andric     if (!errorToBool(ISAInfo.takeError()))
210406c3fb27SDimitry Andric       MinVLen = (*ISAInfo)->getMinVLen();
210506c3fb27SDimitry Andric 
210606c3fb27SDimitry Andric     // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
210706c3fb27SDimitry Andric     // as integer as long as we have a MinVLen.
210806c3fb27SDimitry Andric     unsigned Bits = 0;
210906c3fb27SDimitry Andric     if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
211006c3fb27SDimitry Andric       Bits = MinVLen;
211106c3fb27SDimitry Andric     } else if (!Val.getAsInteger(10, Bits)) {
211206c3fb27SDimitry Andric       // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
211306c3fb27SDimitry Andric       // at least MinVLen.
211406c3fb27SDimitry Andric       if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
211506c3fb27SDimitry Andric           Bits > 65536 || !llvm::isPowerOf2_32(Bits))
211606c3fb27SDimitry Andric         Bits = 0;
211706c3fb27SDimitry Andric     }
211806c3fb27SDimitry Andric 
211906c3fb27SDimitry Andric     // If we got a valid value try to use it.
212006c3fb27SDimitry Andric     if (Bits != 0) {
212106c3fb27SDimitry Andric       unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
212206c3fb27SDimitry Andric       CmdArgs.push_back(
212306c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
212406c3fb27SDimitry Andric       CmdArgs.push_back(
212506c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
212606c3fb27SDimitry Andric     } else if (!Val.equals("scalable")) {
212706c3fb27SDimitry Andric       // Handle the unsupported values passed to mrvv-vector-bits.
212806c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
212906c3fb27SDimitry Andric           << A->getSpelling() << Val;
213006c3fb27SDimitry Andric     }
213106c3fb27SDimitry Andric   }
21320b57cec5SDimitry Andric }
21330b57cec5SDimitry Andric 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const21340b57cec5SDimitry Andric void Clang::AddSparcTargetArgs(const ArgList &Args,
21350b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
21360b57cec5SDimitry Andric   sparc::FloatABI FloatABI =
21370b57cec5SDimitry Andric       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   if (FloatABI == sparc::FloatABI::Soft) {
21400b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
21410b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
21420b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21430b57cec5SDimitry Andric     CmdArgs.push_back("soft");
21440b57cec5SDimitry Andric   } else {
21450b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
21460b57cec5SDimitry Andric     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
21470b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21480b57cec5SDimitry Andric     CmdArgs.push_back("hard");
21490b57cec5SDimitry Andric   }
215061cfbce3SDimitry Andric 
215161cfbce3SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
215261cfbce3SDimitry Andric     StringRef Name = A->getValue();
215361cfbce3SDimitry Andric     std::string TuneCPU;
215461cfbce3SDimitry Andric     if (Name == "native")
215561cfbce3SDimitry Andric       TuneCPU = std::string(llvm::sys::getHostCPUName());
215661cfbce3SDimitry Andric     else
215761cfbce3SDimitry Andric       TuneCPU = std::string(Name);
215861cfbce3SDimitry Andric 
215961cfbce3SDimitry Andric     CmdArgs.push_back("-tune-cpu");
216061cfbce3SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
216161cfbce3SDimitry Andric   }
21620b57cec5SDimitry Andric }
21630b57cec5SDimitry Andric 
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const21640b57cec5SDimitry Andric void Clang::AddSystemZTargetArgs(const ArgList &Args,
21650b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
2166fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2167753f127fSDimitry Andric     CmdArgs.push_back("-tune-cpu");
2168fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2169fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2170fcaf7f86SDimitry Andric     else
2171fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
2172753f127fSDimitry Andric   }
2173753f127fSDimitry Andric 
2174753f127fSDimitry Andric   bool HasBackchain =
2175753f127fSDimitry Andric       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2176480093f4SDimitry Andric   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2177480093f4SDimitry Andric                                      options::OPT_mno_packed_stack, false);
21785ffd83dbSDimitry Andric   systemz::FloatABI FloatABI =
21795ffd83dbSDimitry Andric       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
21805ffd83dbSDimitry Andric   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
21815ffd83dbSDimitry Andric   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2182480093f4SDimitry Andric     const Driver &D = getToolChain().getDriver();
2183480093f4SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt)
21845ffd83dbSDimitry Andric       << "-mpacked-stack -mbackchain -mhard-float";
2185480093f4SDimitry Andric   }
2186480093f4SDimitry Andric   if (HasBackchain)
21870b57cec5SDimitry Andric     CmdArgs.push_back("-mbackchain");
2188480093f4SDimitry Andric   if (HasPackedStack)
2189480093f4SDimitry Andric     CmdArgs.push_back("-mpacked-stack");
21905ffd83dbSDimitry Andric   if (HasSoftFloat) {
21915ffd83dbSDimitry Andric     // Floating point operations and argument passing are soft.
21925ffd83dbSDimitry Andric     CmdArgs.push_back("-msoft-float");
21935ffd83dbSDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21945ffd83dbSDimitry Andric     CmdArgs.push_back("soft");
2195480093f4SDimitry Andric   }
21960b57cec5SDimitry Andric }
21970b57cec5SDimitry Andric 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const21980b57cec5SDimitry Andric void Clang::AddX86TargetArgs(const ArgList &Args,
21990b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
2200480093f4SDimitry Andric   const Driver &D = getToolChain().getDriver();
22015ffd83dbSDimitry Andric   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2202480093f4SDimitry Andric 
22030b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
22040b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
22050b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
22060b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
22090b57cec5SDimitry Andric                     options::OPT_mno_tls_direct_seg_refs, true))
22100b57cec5SDimitry Andric     CmdArgs.push_back("-mno-tls-direct-seg-refs");
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric   // Default to avoid implicit floating-point for kernel/kext code, but allow
22130b57cec5SDimitry Andric   // that to be overridden with -mno-soft-float.
22140b57cec5SDimitry Andric   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
22150b57cec5SDimitry Andric                           Args.hasArg(options::OPT_fapple_kext));
22160b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(
22170b57cec5SDimitry Andric           options::OPT_msoft_float, options::OPT_mno_soft_float,
22180b57cec5SDimitry Andric           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
22190b57cec5SDimitry Andric     const Option &O = A->getOption();
22200b57cec5SDimitry Andric     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
22210b57cec5SDimitry Andric                        O.matches(options::OPT_msoft_float));
22220b57cec5SDimitry Andric   }
22230b57cec5SDimitry Andric   if (NoImplicitFloat)
22240b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
22270b57cec5SDimitry Andric     StringRef Value = A->getValue();
22280b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
22290b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
22300b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2231349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
22320b57cec5SDimitry Andric     } else {
2233480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
2234bdd1243dSDimitry Andric           << A->getSpelling() << Value;
22350b57cec5SDimitry Andric     }
2236480093f4SDimitry Andric   } else if (D.IsCLMode()) {
22370b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
22380b57cec5SDimitry Andric     CmdArgs.push_back("-x86-asm-syntax=intel");
22390b57cec5SDimitry Andric   }
22400b57cec5SDimitry Andric 
2241349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2242349cc55cSDimitry Andric                                options::OPT_mno_skip_rax_setup))
2243349cc55cSDimitry Andric     if (A->getOption().matches(options::OPT_mskip_rax_setup))
2244349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2245349cc55cSDimitry Andric 
22460b57cec5SDimitry Andric   // Set flags to support MCU ABI.
22470b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
22480b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
22490b57cec5SDimitry Andric     CmdArgs.push_back("soft");
22500b57cec5SDimitry Andric     CmdArgs.push_back("-mstack-alignment=4");
22510b57cec5SDimitry Andric   }
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   // Handle -mtune.
2254e8d8bef9SDimitry Andric 
225581ad6265SDimitry Andric   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2256e8d8bef9SDimitry Andric   std::string TuneCPU;
2257e8d8bef9SDimitry Andric   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
225881ad6265SDimitry Andric       !getToolChain().getTriple().isPS())
2259e8d8bef9SDimitry Andric     TuneCPU = "generic";
2260e8d8bef9SDimitry Andric 
2261e8d8bef9SDimitry Andric   // Override based on -mtune.
2262e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2263e8d8bef9SDimitry Andric     StringRef Name = A->getValue();
2264e8d8bef9SDimitry Andric 
2265e8d8bef9SDimitry Andric     if (Name == "native") {
2266e8d8bef9SDimitry Andric       Name = llvm::sys::getHostCPUName();
2267e8d8bef9SDimitry Andric       if (!Name.empty())
2268e8d8bef9SDimitry Andric         TuneCPU = std::string(Name);
2269e8d8bef9SDimitry Andric     } else
2270e8d8bef9SDimitry Andric       TuneCPU = std::string(Name);
2271e8d8bef9SDimitry Andric   }
2272e8d8bef9SDimitry Andric 
2273e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2274e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2275e8d8bef9SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2276e8d8bef9SDimitry Andric   }
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric 
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const22790b57cec5SDimitry Andric void Clang::AddHexagonTargetArgs(const ArgList &Args,
22800b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
22810b57cec5SDimitry Andric   CmdArgs.push_back("-mqdsp6-compat");
22820b57cec5SDimitry Andric   CmdArgs.push_back("-Wreturn-type");
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
22850b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
2286bdd1243dSDimitry Andric     CmdArgs.push_back(
2287bdd1243dSDimitry Andric         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
22880b57cec5SDimitry Andric   }
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_short_enums))
22910b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
22920b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
22930b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
22940b57cec5SDimitry Andric     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
22950b57cec5SDimitry Andric   }
22960b57cec5SDimitry Andric   CmdArgs.push_back("-mllvm");
22970b57cec5SDimitry Andric   CmdArgs.push_back("-machine-sink-split=0");
22980b57cec5SDimitry Andric }
22990b57cec5SDimitry Andric 
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const23000b57cec5SDimitry Andric void Clang::AddLanaiTargetArgs(const ArgList &Args,
23010b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
23020b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
23030b57cec5SDimitry Andric     StringRef CPUName = A->getValue();
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
23060b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPUName));
23070b57cec5SDimitry Andric   }
23080b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
23090b57cec5SDimitry Andric     StringRef Value = A->getValue();
23100b57cec5SDimitry Andric     // Only support mregparm=4 to support old usage. Report error for all other
23110b57cec5SDimitry Andric     // cases.
23120b57cec5SDimitry Andric     int Mregparm;
23130b57cec5SDimitry Andric     if (Value.getAsInteger(10, Mregparm)) {
23140b57cec5SDimitry Andric       if (Mregparm != 4) {
23150b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
23160b57cec5SDimitry Andric             diag::err_drv_unsupported_option_argument)
2317bdd1243dSDimitry Andric             << A->getSpelling() << Value;
23180b57cec5SDimitry Andric       }
23190b57cec5SDimitry Andric     }
23200b57cec5SDimitry Andric   }
23210b57cec5SDimitry Andric }
23220b57cec5SDimitry Andric 
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const23230b57cec5SDimitry Andric void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
23240b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) const {
23250b57cec5SDimitry Andric   // Default to "hidden" visibility.
23260b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2327bdd1243dSDimitry Andric                    options::OPT_fvisibility_ms_compat))
2328bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=hidden");
23290b57cec5SDimitry Andric }
23300b57cec5SDimitry Andric 
AddVETargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const23315ffd83dbSDimitry Andric void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
23325ffd83dbSDimitry Andric   // Floating point operations and argument passing are hard.
23335ffd83dbSDimitry Andric   CmdArgs.push_back("-mfloat-abi");
23345ffd83dbSDimitry Andric   CmdArgs.push_back("hard");
23355ffd83dbSDimitry Andric }
23365ffd83dbSDimitry Andric 
DumpCompilationDatabase(Compilation & C,StringRef Filename,StringRef Target,const InputInfo & Output,const InputInfo & Input,const ArgList & Args) const23370b57cec5SDimitry Andric void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
23380b57cec5SDimitry Andric                                     StringRef Target, const InputInfo &Output,
23390b57cec5SDimitry Andric                                     const InputInfo &Input, const ArgList &Args) const {
23400b57cec5SDimitry Andric   // If this is a dry run, do not create the compilation database file.
23410b57cec5SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
23420b57cec5SDimitry Andric     return;
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   using llvm::yaml::escape;
23450b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   if (!CompilationDatabase) {
23480b57cec5SDimitry Andric     std::error_code EC;
2349fe6060f1SDimitry Andric     auto File = std::make_unique<llvm::raw_fd_ostream>(
235081ad6265SDimitry Andric         Filename, EC,
235181ad6265SDimitry Andric         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
23520b57cec5SDimitry Andric     if (EC) {
23530b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
23540b57cec5SDimitry Andric                                                        << EC.message();
23550b57cec5SDimitry Andric       return;
23560b57cec5SDimitry Andric     }
23570b57cec5SDimitry Andric     CompilationDatabase = std::move(File);
23580b57cec5SDimitry Andric   }
23590b57cec5SDimitry Andric   auto &CDB = *CompilationDatabase;
2360a7dea167SDimitry Andric   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2361a7dea167SDimitry Andric   if (!CWD)
2362a7dea167SDimitry Andric     CWD = ".";
2363a7dea167SDimitry Andric   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
23640b57cec5SDimitry Andric   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
23655f757f3fSDimitry Andric   if (Output.isFilename())
23660b57cec5SDimitry Andric     CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
23670b57cec5SDimitry Andric   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2368a7dea167SDimitry Andric   SmallString<128> Buf;
23690b57cec5SDimitry Andric   Buf = "-x";
23700b57cec5SDimitry Andric   Buf += types::getTypeName(Input.getType());
23710b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"";
23720b57cec5SDimitry Andric   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
23730b57cec5SDimitry Andric     Buf = "--sysroot=";
23740b57cec5SDimitry Andric     Buf += D.SysRoot;
23750b57cec5SDimitry Andric     CDB << ", \"" << escape(Buf) << "\"";
23760b57cec5SDimitry Andric   }
23770b57cec5SDimitry Andric   CDB << ", \"" << escape(Input.getFilename()) << "\"";
23785f757f3fSDimitry Andric   if (Output.isFilename())
237981ad6265SDimitry Andric     CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
23800b57cec5SDimitry Andric   for (auto &A: Args) {
23810b57cec5SDimitry Andric     auto &O = A->getOption();
23820b57cec5SDimitry Andric     // Skip language selection, which is positional.
23830b57cec5SDimitry Andric     if (O.getID() == options::OPT_x)
23840b57cec5SDimitry Andric       continue;
23850b57cec5SDimitry Andric     // Skip writing dependency output and the compilation database itself.
23860b57cec5SDimitry Andric     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
23870b57cec5SDimitry Andric       continue;
2388a7dea167SDimitry Andric     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2389a7dea167SDimitry Andric       continue;
23900b57cec5SDimitry Andric     // Skip inputs.
23910b57cec5SDimitry Andric     if (O.getKind() == Option::InputClass)
23920b57cec5SDimitry Andric       continue;
239381ad6265SDimitry Andric     // Skip output.
239481ad6265SDimitry Andric     if (O.getID() == options::OPT_o)
239581ad6265SDimitry Andric       continue;
23960b57cec5SDimitry Andric     // All other arguments are quoted and appended.
23970b57cec5SDimitry Andric     ArgStringList ASL;
23980b57cec5SDimitry Andric     A->render(Args, ASL);
23990b57cec5SDimitry Andric     for (auto &it: ASL)
24000b57cec5SDimitry Andric       CDB << ", \"" << escape(it) << "\"";
24010b57cec5SDimitry Andric   }
24020b57cec5SDimitry Andric   Buf = "--target=";
24030b57cec5SDimitry Andric   Buf += Target;
24040b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"]},\n";
24050b57cec5SDimitry Andric }
24060b57cec5SDimitry Andric 
DumpCompilationDatabaseFragmentToDir(StringRef Dir,Compilation & C,StringRef Target,const InputInfo & Output,const InputInfo & Input,const llvm::opt::ArgList & Args) const2407a7dea167SDimitry Andric void Clang::DumpCompilationDatabaseFragmentToDir(
2408a7dea167SDimitry Andric     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2409a7dea167SDimitry Andric     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2410a7dea167SDimitry Andric   // If this is a dry run, do not create the compilation database file.
2411a7dea167SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2412a7dea167SDimitry Andric     return;
2413a7dea167SDimitry Andric 
2414a7dea167SDimitry Andric   if (CompilationDatabase)
2415a7dea167SDimitry Andric     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2416a7dea167SDimitry Andric 
2417a7dea167SDimitry Andric   SmallString<256> Path = Dir;
2418a7dea167SDimitry Andric   const auto &Driver = C.getDriver();
2419a7dea167SDimitry Andric   Driver.getVFS().makeAbsolute(Path);
2420a7dea167SDimitry Andric   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2421a7dea167SDimitry Andric   if (Err) {
2422a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2423a7dea167SDimitry Andric     return;
2424a7dea167SDimitry Andric   }
2425a7dea167SDimitry Andric 
2426a7dea167SDimitry Andric   llvm::sys::path::append(
2427a7dea167SDimitry Andric       Path,
2428a7dea167SDimitry Andric       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2429a7dea167SDimitry Andric   int FD;
2430a7dea167SDimitry Andric   SmallString<256> TempPath;
2431fe6060f1SDimitry Andric   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2432fe6060f1SDimitry Andric                                         llvm::sys::fs::OF_Text);
2433a7dea167SDimitry Andric   if (Err) {
2434a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2435a7dea167SDimitry Andric     return;
2436a7dea167SDimitry Andric   }
2437a7dea167SDimitry Andric   CompilationDatabase =
2438a7dea167SDimitry Andric       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2439a7dea167SDimitry Andric   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2440a7dea167SDimitry Andric }
2441a7dea167SDimitry Andric 
CheckARMImplicitITArg(StringRef Value)2442fe6060f1SDimitry Andric static bool CheckARMImplicitITArg(StringRef Value) {
2443fe6060f1SDimitry Andric   return Value == "always" || Value == "never" || Value == "arm" ||
2444fe6060f1SDimitry Andric          Value == "thumb";
2445fe6060f1SDimitry Andric }
2446fe6060f1SDimitry Andric 
AddARMImplicitITArgs(const ArgList & Args,ArgStringList & CmdArgs,StringRef Value)2447fe6060f1SDimitry Andric static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2448fe6060f1SDimitry Andric                                  StringRef Value) {
2449fe6060f1SDimitry Andric   CmdArgs.push_back("-mllvm");
2450fe6060f1SDimitry Andric   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2451fe6060f1SDimitry Andric }
2452fe6060f1SDimitry Andric 
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)24530b57cec5SDimitry Andric static void CollectArgsForIntegratedAssembler(Compilation &C,
24540b57cec5SDimitry Andric                                               const ArgList &Args,
24550b57cec5SDimitry Andric                                               ArgStringList &CmdArgs,
24560b57cec5SDimitry Andric                                               const Driver &D) {
24570b57cec5SDimitry Andric   if (UseRelaxAll(C, Args))
24580b57cec5SDimitry Andric     CmdArgs.push_back("-mrelax-all");
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric   // Only default to -mincremental-linker-compatible if we think we are
24610b57cec5SDimitry Andric   // targeting the MSVC linker.
24620b57cec5SDimitry Andric   bool DefaultIncrementalLinkerCompatible =
24630b57cec5SDimitry Andric       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
24640b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
24650b57cec5SDimitry Andric                    options::OPT_mno_incremental_linker_compatible,
24660b57cec5SDimitry Andric                    DefaultIncrementalLinkerCompatible))
24670b57cec5SDimitry Andric     CmdArgs.push_back("-mincremental-linker-compatible");
24680b57cec5SDimitry Andric 
246981ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
247081ad6265SDimitry Andric 
247106c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
247206c3fb27SDimitry Andric                     options::OPT_fno_emit_compact_unwind_non_canonical);
247306c3fb27SDimitry Andric 
2474a7dea167SDimitry Andric   // If you add more args here, also add them to the block below that
2475a7dea167SDimitry Andric   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2476a7dea167SDimitry Andric 
24770b57cec5SDimitry Andric   // When passing -I arguments to the assembler we sometimes need to
24780b57cec5SDimitry Andric   // unconditionally take the next argument.  For example, when parsing
24790b57cec5SDimitry Andric   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
24800b57cec5SDimitry Andric   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
24810b57cec5SDimitry Andric   // arg after parsing the '-I' arg.
24820b57cec5SDimitry Andric   bool TakeNextArg = false;
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2485349cc55cSDimitry Andric   bool UseNoExecStack = false;
24860b57cec5SDimitry Andric   const char *MipsTargetFeature = nullptr;
2487fe6060f1SDimitry Andric   StringRef ImplicitIt;
24880b57cec5SDimitry Andric   for (const Arg *A :
2489fe6060f1SDimitry Andric        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2490fe6060f1SDimitry Andric                      options::OPT_mimplicit_it_EQ)) {
24910b57cec5SDimitry Andric     A->claim();
24920b57cec5SDimitry Andric 
2493fe6060f1SDimitry Andric     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2494fe6060f1SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
2495fe6060f1SDimitry Andric       case llvm::Triple::arm:
2496fe6060f1SDimitry Andric       case llvm::Triple::armeb:
2497fe6060f1SDimitry Andric       case llvm::Triple::thumb:
2498fe6060f1SDimitry Andric       case llvm::Triple::thumbeb:
2499fe6060f1SDimitry Andric         // Only store the value; the last value set takes effect.
2500fe6060f1SDimitry Andric         ImplicitIt = A->getValue();
2501fe6060f1SDimitry Andric         if (!CheckARMImplicitITArg(ImplicitIt))
2502fe6060f1SDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
2503bdd1243dSDimitry Andric               << A->getSpelling() << ImplicitIt;
2504fe6060f1SDimitry Andric         continue;
2505fe6060f1SDimitry Andric       default:
2506fe6060f1SDimitry Andric         break;
2507fe6060f1SDimitry Andric       }
2508fe6060f1SDimitry Andric     }
2509fe6060f1SDimitry Andric 
25100b57cec5SDimitry Andric     for (StringRef Value : A->getValues()) {
25110b57cec5SDimitry Andric       if (TakeNextArg) {
25120b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
25130b57cec5SDimitry Andric         TakeNextArg = false;
25140b57cec5SDimitry Andric         continue;
25150b57cec5SDimitry Andric       }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
25180b57cec5SDimitry Andric           Value == "-mbig-obj")
25190b57cec5SDimitry Andric         continue; // LLVM handles bigobj automatically
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
25220b57cec5SDimitry Andric       default:
25230b57cec5SDimitry Andric         break;
2524bdd1243dSDimitry Andric       case llvm::Triple::wasm32:
2525bdd1243dSDimitry Andric       case llvm::Triple::wasm64:
2526bdd1243dSDimitry Andric         if (Value == "--no-type-check") {
2527bdd1243dSDimitry Andric           CmdArgs.push_back("-mno-type-check");
2528bdd1243dSDimitry Andric           continue;
2529bdd1243dSDimitry Andric         }
2530bdd1243dSDimitry Andric         break;
25310b57cec5SDimitry Andric       case llvm::Triple::thumb:
25320b57cec5SDimitry Andric       case llvm::Triple::thumbeb:
25330b57cec5SDimitry Andric       case llvm::Triple::arm:
25340b57cec5SDimitry Andric       case llvm::Triple::armeb:
25355f757f3fSDimitry Andric         if (Value.starts_with("-mimplicit-it=")) {
2536fe6060f1SDimitry Andric           // Only store the value; the last value set takes effect.
2537fe6060f1SDimitry Andric           ImplicitIt = Value.split("=").second;
2538fe6060f1SDimitry Andric           if (CheckARMImplicitITArg(ImplicitIt))
2539fe6060f1SDimitry Andric             continue;
2540fe6060f1SDimitry Andric         }
25410b57cec5SDimitry Andric         if (Value == "-mthumb")
25420b57cec5SDimitry Andric           // -mthumb has already been processed in ComputeLLVMTriple()
25430b57cec5SDimitry Andric           // recognize but skip over here.
25440b57cec5SDimitry Andric           continue;
25450b57cec5SDimitry Andric         break;
25460b57cec5SDimitry Andric       case llvm::Triple::mips:
25470b57cec5SDimitry Andric       case llvm::Triple::mipsel:
25480b57cec5SDimitry Andric       case llvm::Triple::mips64:
25490b57cec5SDimitry Andric       case llvm::Triple::mips64el:
25500b57cec5SDimitry Andric         if (Value == "--trap") {
25510b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25520b57cec5SDimitry Andric           CmdArgs.push_back("+use-tcc-in-div");
25530b57cec5SDimitry Andric           continue;
25540b57cec5SDimitry Andric         }
25550b57cec5SDimitry Andric         if (Value == "--break") {
25560b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25570b57cec5SDimitry Andric           CmdArgs.push_back("-use-tcc-in-div");
25580b57cec5SDimitry Andric           continue;
25590b57cec5SDimitry Andric         }
25605f757f3fSDimitry Andric         if (Value.starts_with("-msoft-float")) {
25610b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25620b57cec5SDimitry Andric           CmdArgs.push_back("+soft-float");
25630b57cec5SDimitry Andric           continue;
25640b57cec5SDimitry Andric         }
25655f757f3fSDimitry Andric         if (Value.starts_with("-mhard-float")) {
25660b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25670b57cec5SDimitry Andric           CmdArgs.push_back("-soft-float");
25680b57cec5SDimitry Andric           continue;
25690b57cec5SDimitry Andric         }
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
25720b57cec5SDimitry Andric                                 .Case("-mips1", "+mips1")
25730b57cec5SDimitry Andric                                 .Case("-mips2", "+mips2")
25740b57cec5SDimitry Andric                                 .Case("-mips3", "+mips3")
25750b57cec5SDimitry Andric                                 .Case("-mips4", "+mips4")
25760b57cec5SDimitry Andric                                 .Case("-mips5", "+mips5")
25770b57cec5SDimitry Andric                                 .Case("-mips32", "+mips32")
25780b57cec5SDimitry Andric                                 .Case("-mips32r2", "+mips32r2")
25790b57cec5SDimitry Andric                                 .Case("-mips32r3", "+mips32r3")
25800b57cec5SDimitry Andric                                 .Case("-mips32r5", "+mips32r5")
25810b57cec5SDimitry Andric                                 .Case("-mips32r6", "+mips32r6")
25820b57cec5SDimitry Andric                                 .Case("-mips64", "+mips64")
25830b57cec5SDimitry Andric                                 .Case("-mips64r2", "+mips64r2")
25840b57cec5SDimitry Andric                                 .Case("-mips64r3", "+mips64r3")
25850b57cec5SDimitry Andric                                 .Case("-mips64r5", "+mips64r5")
25860b57cec5SDimitry Andric                                 .Case("-mips64r6", "+mips64r6")
25870b57cec5SDimitry Andric                                 .Default(nullptr);
25880b57cec5SDimitry Andric         if (MipsTargetFeature)
25890b57cec5SDimitry Andric           continue;
25900b57cec5SDimitry Andric       }
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric       if (Value == "-force_cpusubtype_ALL") {
25930b57cec5SDimitry Andric         // Do nothing, this is the default and we don't support anything else.
25940b57cec5SDimitry Andric       } else if (Value == "-L") {
25950b57cec5SDimitry Andric         CmdArgs.push_back("-msave-temp-labels");
25960b57cec5SDimitry Andric       } else if (Value == "--fatal-warnings") {
25970b57cec5SDimitry Andric         CmdArgs.push_back("-massembler-fatal-warnings");
2598a7dea167SDimitry Andric       } else if (Value == "--no-warn" || Value == "-W") {
2599a7dea167SDimitry Andric         CmdArgs.push_back("-massembler-no-warn");
26000b57cec5SDimitry Andric       } else if (Value == "--noexecstack") {
26010b57cec5SDimitry Andric         UseNoExecStack = true;
26025f757f3fSDimitry Andric       } else if (Value.starts_with("-compress-debug-sections") ||
26035f757f3fSDimitry Andric                  Value.starts_with("--compress-debug-sections") ||
26040b57cec5SDimitry Andric                  Value == "-nocompress-debug-sections" ||
26050b57cec5SDimitry Andric                  Value == "--nocompress-debug-sections") {
26060b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
26070b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=yes" ||
26080b57cec5SDimitry Andric                  Value == "--mrelax-relocations=yes") {
26090b57cec5SDimitry Andric         UseRelaxRelocations = true;
26100b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=no" ||
26110b57cec5SDimitry Andric                  Value == "--mrelax-relocations=no") {
26120b57cec5SDimitry Andric         UseRelaxRelocations = false;
26135f757f3fSDimitry Andric       } else if (Value.starts_with("-I")) {
26140b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
26150b57cec5SDimitry Andric         // We need to consume the next argument if the current arg is a plain
26160b57cec5SDimitry Andric         // -I. The next arg will be the include directory.
26170b57cec5SDimitry Andric         if (Value == "-I")
26180b57cec5SDimitry Andric           TakeNextArg = true;
26195f757f3fSDimitry Andric       } else if (Value.starts_with("-gdwarf-")) {
26200b57cec5SDimitry Andric         // "-gdwarf-N" options are not cc1as options.
26210b57cec5SDimitry Andric         unsigned DwarfVersion = DwarfVersionNum(Value);
26220b57cec5SDimitry Andric         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
26230b57cec5SDimitry Andric           CmdArgs.push_back(Value.data());
26240b57cec5SDimitry Andric         } else {
26250b57cec5SDimitry Andric           RenderDebugEnablingArgs(Args, CmdArgs,
262606c3fb27SDimitry Andric                                   llvm::codegenoptions::DebugInfoConstructor,
26270b57cec5SDimitry Andric                                   DwarfVersion, llvm::DebuggerKind::Default);
26280b57cec5SDimitry Andric         }
26295f757f3fSDimitry Andric       } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
26305f757f3fSDimitry Andric                  Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
26310b57cec5SDimitry Andric         // Do nothing, we'll validate it later.
26320b57cec5SDimitry Andric       } else if (Value == "-defsym") {
26330b57cec5SDimitry Andric         if (A->getNumValues() != 2) {
26340b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << Value;
26350b57cec5SDimitry Andric           break;
26360b57cec5SDimitry Andric         }
26370b57cec5SDimitry Andric         const char *S = A->getValue(1);
26380b57cec5SDimitry Andric         auto Pair = StringRef(S).split('=');
26390b57cec5SDimitry Andric         auto Sym = Pair.first;
26400b57cec5SDimitry Andric         auto SVal = Pair.second;
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric         if (Sym.empty() || SVal.empty()) {
26430b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << S;
26440b57cec5SDimitry Andric           break;
26450b57cec5SDimitry Andric         }
26460b57cec5SDimitry Andric         int64_t IVal;
26470b57cec5SDimitry Andric         if (SVal.getAsInteger(0, IVal)) {
26480b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
26490b57cec5SDimitry Andric           break;
26500b57cec5SDimitry Andric         }
26510b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
26520b57cec5SDimitry Andric         TakeNextArg = true;
26530b57cec5SDimitry Andric       } else if (Value == "-fdebug-compilation-dir") {
26540b57cec5SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
26550b57cec5SDimitry Andric         TakeNextArg = true;
2656480093f4SDimitry Andric       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2657480093f4SDimitry Andric         // The flag is a -Wa / -Xassembler argument and Options doesn't
2658480093f4SDimitry Andric         // parse the argument, so this isn't automatically aliased to
2659480093f4SDimitry Andric         // -fdebug-compilation-dir (without '=') here.
2660480093f4SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
2661480093f4SDimitry Andric         CmdArgs.push_back(Value.data());
2662fe6060f1SDimitry Andric       } else if (Value == "--version") {
2663fe6060f1SDimitry Andric         D.PrintVersion(C, llvm::outs());
26640b57cec5SDimitry Andric       } else {
26650b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2666bdd1243dSDimitry Andric             << A->getSpelling() << Value;
26670b57cec5SDimitry Andric       }
26680b57cec5SDimitry Andric     }
26690b57cec5SDimitry Andric   }
2670fe6060f1SDimitry Andric   if (ImplicitIt.size())
2671fe6060f1SDimitry Andric     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2672bdd1243dSDimitry Andric   if (!UseRelaxRelocations)
2673bdd1243dSDimitry Andric     CmdArgs.push_back("-mrelax-relocations=no");
26740b57cec5SDimitry Andric   if (UseNoExecStack)
26750b57cec5SDimitry Andric     CmdArgs.push_back("-mnoexecstack");
26760b57cec5SDimitry Andric   if (MipsTargetFeature != nullptr) {
26770b57cec5SDimitry Andric     CmdArgs.push_back("-target-feature");
26780b57cec5SDimitry Andric     CmdArgs.push_back(MipsTargetFeature);
26790b57cec5SDimitry Andric   }
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   // forward -fembed-bitcode to assmebler
26820b57cec5SDimitry Andric   if (C.getDriver().embedBitcodeEnabled() ||
26830b57cec5SDimitry Andric       C.getDriver().embedBitcodeMarkerOnly())
26840b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2685bdd1243dSDimitry Andric 
2686bdd1243dSDimitry Andric   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2687bdd1243dSDimitry Andric     CmdArgs.push_back("-as-secure-log-file");
2688bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2689bdd1243dSDimitry Andric   }
26900b57cec5SDimitry Andric }
26910b57cec5SDimitry Andric 
EnumComplexRangeToStr(LangOptions::ComplexRangeKind Range)26925f757f3fSDimitry Andric static StringRef EnumComplexRangeToStr(LangOptions::ComplexRangeKind Range) {
26935f757f3fSDimitry Andric   StringRef RangeStr = "";
26945f757f3fSDimitry Andric   switch (Range) {
26955f757f3fSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Limited:
26965f757f3fSDimitry Andric     return "-fcx-limited-range";
26975f757f3fSDimitry Andric     break;
26985f757f3fSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Fortran:
26995f757f3fSDimitry Andric     return "-fcx-fortran-rules";
27005f757f3fSDimitry Andric     break;
27015f757f3fSDimitry Andric   default:
27025f757f3fSDimitry Andric     return RangeStr;
27035f757f3fSDimitry Andric     break;
27045f757f3fSDimitry Andric   }
27055f757f3fSDimitry Andric }
27065f757f3fSDimitry Andric 
EmitComplexRangeDiag(const Driver & D,LangOptions::ComplexRangeKind Range1,LangOptions::ComplexRangeKind Range2)27075f757f3fSDimitry Andric static void EmitComplexRangeDiag(const Driver &D,
27085f757f3fSDimitry Andric                                  LangOptions::ComplexRangeKind Range1,
27095f757f3fSDimitry Andric                                  LangOptions::ComplexRangeKind Range2) {
27105f757f3fSDimitry Andric   if (Range1 != LangOptions::ComplexRangeKind::CX_Full)
27115f757f3fSDimitry Andric     D.Diag(clang::diag::warn_drv_overriding_option)
27125f757f3fSDimitry Andric         << EnumComplexRangeToStr(Range1) << EnumComplexRangeToStr(Range2);
27135f757f3fSDimitry Andric }
27145f757f3fSDimitry Andric 
27157a6dacacSDimitry Andric static std::string
RenderComplexRangeOption(LangOptions::ComplexRangeKind Range)27167a6dacacSDimitry Andric RenderComplexRangeOption(LangOptions::ComplexRangeKind Range) {
27175f757f3fSDimitry Andric   std::string ComplexRangeStr = "-complex-range=";
27187a6dacacSDimitry Andric   switch (Range) {
27197a6dacacSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Full:
27207a6dacacSDimitry Andric     ComplexRangeStr += "full";
27217a6dacacSDimitry Andric     break;
27227a6dacacSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Limited:
27237a6dacacSDimitry Andric     ComplexRangeStr += "limited";
27247a6dacacSDimitry Andric     break;
27257a6dacacSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Fortran:
27267a6dacacSDimitry Andric     ComplexRangeStr += "fortran";
27277a6dacacSDimitry Andric     break;
27287a6dacacSDimitry Andric   default:
27297a6dacacSDimitry Andric     assert(0 && "Unexpected range option");
27307a6dacacSDimitry Andric   }
27315f757f3fSDimitry Andric   return ComplexRangeStr;
27325f757f3fSDimitry Andric }
27335f757f3fSDimitry Andric 
RenderFloatingPointOptions(const ToolChain & TC,const Driver & D,bool OFastEnabled,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)27340b57cec5SDimitry Andric static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
27350b57cec5SDimitry Andric                                        bool OFastEnabled, const ArgList &Args,
27365ffd83dbSDimitry Andric                                        ArgStringList &CmdArgs,
27375ffd83dbSDimitry Andric                                        const JobAction &JA) {
27380b57cec5SDimitry Andric   // Handle various floating point optimization flags, mapping them to the
27390b57cec5SDimitry Andric   // appropriate LLVM code generation flags. This is complicated by several
27400b57cec5SDimitry Andric   // "umbrella" flags, so we do this by stepping through the flags incrementally
27410b57cec5SDimitry Andric   // adjusting what we think is enabled/disabled, then at the end setting the
27420b57cec5SDimitry Andric   // LLVM flags based on the final state.
27430b57cec5SDimitry Andric   bool HonorINFs = true;
27440b57cec5SDimitry Andric   bool HonorNaNs = true;
2745349cc55cSDimitry Andric   bool ApproxFunc = false;
27460b57cec5SDimitry Andric   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
27470b57cec5SDimitry Andric   bool MathErrno = TC.IsMathErrnoDefault();
27480b57cec5SDimitry Andric   bool AssociativeMath = false;
27490b57cec5SDimitry Andric   bool ReciprocalMath = false;
27500b57cec5SDimitry Andric   bool SignedZeros = true;
2751480093f4SDimitry Andric   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2752480093f4SDimitry Andric   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2753480093f4SDimitry Andric                                     // overriden by ffp-exception-behavior?
2754480093f4SDimitry Andric   bool RoundingFPMath = false;
2755480093f4SDimitry Andric   bool RoundingMathPresent = false; // Is rounding-math in args?
2756480093f4SDimitry Andric   // -ffp-model values: strict, fast, precise
2757480093f4SDimitry Andric   StringRef FPModel = "";
2758480093f4SDimitry Andric   // -ffp-exception-behavior options: strict, maytrap, ignore
2759480093f4SDimitry Andric   StringRef FPExceptionBehavior = "";
276081ad6265SDimitry Andric   // -ffp-eval-method options: double, extended, source
276181ad6265SDimitry Andric   StringRef FPEvalMethod = "";
27625ffd83dbSDimitry Andric   const llvm::DenormalMode DefaultDenormalFPMath =
27635ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA);
27645ffd83dbSDimitry Andric   const llvm::DenormalMode DefaultDenormalFP32Math =
27655ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
27665ffd83dbSDimitry Andric 
27675ffd83dbSDimitry Andric   llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
27685ffd83dbSDimitry Andric   llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2769349cc55cSDimitry Andric   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2770349cc55cSDimitry Andric   // If one wasn't given by the user, don't pass it here.
2771349cc55cSDimitry Andric   StringRef FPContract;
2772bdd1243dSDimitry Andric   StringRef LastSeenFfpContractOption;
2773bdd1243dSDimitry Andric   bool SeenUnsafeMathModeOption = false;
2774349cc55cSDimitry Andric   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2775349cc55cSDimitry Andric       !JA.isOffloading(Action::OFK_HIP))
2776349cc55cSDimitry Andric     FPContract = "on";
2777480093f4SDimitry Andric   bool StrictFPModel = false;
2778bdd1243dSDimitry Andric   StringRef Float16ExcessPrecision = "";
277906c3fb27SDimitry Andric   StringRef BFloat16ExcessPrecision = "";
27807a6dacacSDimitry Andric   LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
27817a6dacacSDimitry Andric   std::string ComplexRangeStr = "";
27820b57cec5SDimitry Andric 
27830b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
27840b57cec5SDimitry Andric     CmdArgs.push_back("-mlimit-float-precision");
27850b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
27860b57cec5SDimitry Andric   }
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric   for (const Arg *A : Args) {
2789480093f4SDimitry Andric     auto optID = A->getOption().getID();
2790480093f4SDimitry Andric     bool PreciseFPModel = false;
2791480093f4SDimitry Andric     switch (optID) {
2792480093f4SDimitry Andric     default:
2793480093f4SDimitry Andric       break;
27945f757f3fSDimitry Andric     case options::OPT_fcx_limited_range: {
27955f757f3fSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Limited);
27965f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Limited;
27975f757f3fSDimitry Andric       break;
27985f757f3fSDimitry Andric     }
27995f757f3fSDimitry Andric     case options::OPT_fno_cx_limited_range:
28007a6dacacSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Full);
28015f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
28025f757f3fSDimitry Andric       break;
28035f757f3fSDimitry Andric     case options::OPT_fcx_fortran_rules: {
28045f757f3fSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Fortran);
28055f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Fortran;
28065f757f3fSDimitry Andric       break;
28075f757f3fSDimitry Andric     }
28085f757f3fSDimitry Andric     case options::OPT_fno_cx_fortran_rules:
28097a6dacacSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Full);
28105f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
28115f757f3fSDimitry Andric       break;
2812480093f4SDimitry Andric     case options::OPT_ffp_model_EQ: {
2813480093f4SDimitry Andric       // If -ffp-model= is seen, reset to fno-fast-math
2814480093f4SDimitry Andric       HonorINFs = true;
2815480093f4SDimitry Andric       HonorNaNs = true;
2816bdd1243dSDimitry Andric       ApproxFunc = false;
2817480093f4SDimitry Andric       // Turning *off* -ffast-math restores the toolchain default.
2818480093f4SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
2819480093f4SDimitry Andric       AssociativeMath = false;
2820480093f4SDimitry Andric       ReciprocalMath = false;
2821480093f4SDimitry Andric       SignedZeros = true;
2822480093f4SDimitry Andric       // -fno_fast_math restores default denormal and fpcontract handling
2823349cc55cSDimitry Andric       FPContract = "on";
28245ffd83dbSDimitry Andric       DenormalFPMath = llvm::DenormalMode::getIEEE();
28255ffd83dbSDimitry Andric 
28265ffd83dbSDimitry Andric       // FIXME: The target may have picked a non-IEEE default mode here based on
28275ffd83dbSDimitry Andric       // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
28285ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
28295ffd83dbSDimitry Andric 
2830480093f4SDimitry Andric       StringRef Val = A->getValue();
2831480093f4SDimitry Andric       if (OFastEnabled && !Val.equals("fast")) {
2832480093f4SDimitry Andric           // Only -ffp-model=fast is compatible with OFast, ignore.
28335f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
28345f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2835480093f4SDimitry Andric         break;
2836480093f4SDimitry Andric       }
2837480093f4SDimitry Andric       StrictFPModel = false;
2838480093f4SDimitry Andric       PreciseFPModel = true;
2839480093f4SDimitry Andric       // ffp-model= is a Driver option, it is entirely rewritten into more
2840480093f4SDimitry Andric       // granular options before being passed into cc1.
2841480093f4SDimitry Andric       // Use the gcc option in the switch below.
2842349cc55cSDimitry Andric       if (!FPModel.empty() && !FPModel.equals(Val))
28435f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
2844480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + FPModel)
2845480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val);
2846480093f4SDimitry Andric       if (Val.equals("fast")) {
2847480093f4SDimitry Andric         optID = options::OPT_ffast_math;
2848480093f4SDimitry Andric         FPModel = Val;
28496e75b2fbSDimitry Andric         FPContract = "fast";
2850480093f4SDimitry Andric       } else if (Val.equals("precise")) {
2851480093f4SDimitry Andric         optID = options::OPT_ffp_contract;
2852480093f4SDimitry Andric         FPModel = Val;
2853349cc55cSDimitry Andric         FPContract = "on";
2854480093f4SDimitry Andric         PreciseFPModel = true;
2855480093f4SDimitry Andric       } else if (Val.equals("strict")) {
2856480093f4SDimitry Andric         StrictFPModel = true;
2857480093f4SDimitry Andric         optID = options::OPT_frounding_math;
2858480093f4SDimitry Andric         FPExceptionBehavior = "strict";
2859480093f4SDimitry Andric         FPModel = Val;
28605ffd83dbSDimitry Andric         FPContract = "off";
2861480093f4SDimitry Andric         TrappingMath = true;
2862480093f4SDimitry Andric       } else
2863480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2864bdd1243dSDimitry Andric             << A->getSpelling() << Val;
2865480093f4SDimitry Andric       break;
2866480093f4SDimitry Andric     }
2867480093f4SDimitry Andric     }
2868480093f4SDimitry Andric 
2869480093f4SDimitry Andric     switch (optID) {
28700b57cec5SDimitry Andric     // If this isn't an FP option skip the claim below
28710b57cec5SDimitry Andric     default: continue;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric     // Options controlling individual features
28740b57cec5SDimitry Andric     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
28750b57cec5SDimitry Andric     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
28760b57cec5SDimitry Andric     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
28770b57cec5SDimitry Andric     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2878349cc55cSDimitry Andric     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
2879349cc55cSDimitry Andric     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
28800b57cec5SDimitry Andric     case options::OPT_fmath_errno:          MathErrno = true;         break;
28810b57cec5SDimitry Andric     case options::OPT_fno_math_errno:       MathErrno = false;        break;
28820b57cec5SDimitry Andric     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
28830b57cec5SDimitry Andric     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
28840b57cec5SDimitry Andric     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
28850b57cec5SDimitry Andric     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
28860b57cec5SDimitry Andric     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
28870b57cec5SDimitry Andric     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2888480093f4SDimitry Andric     case options::OPT_ftrapping_math:
2889480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2890480093f4SDimitry Andric           !FPExceptionBehavior.equals("strict"))
2891480093f4SDimitry Andric         // Warn that previous value of option is overridden.
28925f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
28935f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
28945f757f3fSDimitry Andric                                   FPExceptionBehavior)
2895480093f4SDimitry Andric             << "-ftrapping-math";
2896480093f4SDimitry Andric       TrappingMath = true;
2897480093f4SDimitry Andric       TrappingMathPresent = true;
2898480093f4SDimitry Andric       FPExceptionBehavior = "strict";
2899480093f4SDimitry Andric       break;
2900480093f4SDimitry Andric     case options::OPT_fno_trapping_math:
2901480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2902480093f4SDimitry Andric           !FPExceptionBehavior.equals("ignore"))
2903480093f4SDimitry Andric         // Warn that previous value of option is overridden.
29045f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
29055f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
29065f757f3fSDimitry Andric                                   FPExceptionBehavior)
2907480093f4SDimitry Andric             << "-fno-trapping-math";
2908480093f4SDimitry Andric       TrappingMath = false;
2909480093f4SDimitry Andric       TrappingMathPresent = true;
2910480093f4SDimitry Andric       FPExceptionBehavior = "ignore";
2911480093f4SDimitry Andric       break;
2912480093f4SDimitry Andric 
2913480093f4SDimitry Andric     case options::OPT_frounding_math:
2914480093f4SDimitry Andric       RoundingFPMath = true;
2915480093f4SDimitry Andric       RoundingMathPresent = true;
2916480093f4SDimitry Andric       break;
2917480093f4SDimitry Andric 
2918480093f4SDimitry Andric     case options::OPT_fno_rounding_math:
2919480093f4SDimitry Andric       RoundingFPMath = false;
2920480093f4SDimitry Andric       RoundingMathPresent = false;
2921480093f4SDimitry Andric       break;
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric     case options::OPT_fdenormal_fp_math_EQ:
29245ffd83dbSDimitry Andric       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
292581ad6265SDimitry Andric       DenormalFP32Math = DenormalFPMath;
29265ffd83dbSDimitry Andric       if (!DenormalFPMath.isValid()) {
29275ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
29285ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
29295ffd83dbSDimitry Andric       }
29305ffd83dbSDimitry Andric       break;
29315ffd83dbSDimitry Andric 
29325ffd83dbSDimitry Andric     case options::OPT_fdenormal_fp_math_f32_EQ:
29335ffd83dbSDimitry Andric       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
29345ffd83dbSDimitry Andric       if (!DenormalFP32Math.isValid()) {
29355ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
29365ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
29375ffd83dbSDimitry Andric       }
29380b57cec5SDimitry Andric       break;
29390b57cec5SDimitry Andric 
2940480093f4SDimitry Andric     // Validate and pass through -ffp-contract option.
29410b57cec5SDimitry Andric     case options::OPT_ffp_contract: {
29420b57cec5SDimitry Andric       StringRef Val = A->getValue();
2943480093f4SDimitry Andric       if (PreciseFPModel) {
2944349cc55cSDimitry Andric         // -ffp-model=precise enables ffp-contract=on.
2945349cc55cSDimitry Andric         // -ffp-model=precise sets PreciseFPModel to on and Val to
2946349cc55cSDimitry Andric         // "precise". FPContract is set.
2947480093f4SDimitry Andric         ;
29485f757f3fSDimitry Andric       } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off") ||
29495f757f3fSDimitry Andric                  Val.equals("fast-honor-pragmas")) {
29500b57cec5SDimitry Andric         FPContract = Val;
2951bdd1243dSDimitry Andric         LastSeenFfpContractOption = Val;
2952bdd1243dSDimitry Andric       } else
29530b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2954bdd1243dSDimitry Andric             << A->getSpelling() << Val;
29550b57cec5SDimitry Andric       break;
29560b57cec5SDimitry Andric     }
29570b57cec5SDimitry Andric 
2958480093f4SDimitry Andric     // Validate and pass through -ffp-model option.
2959480093f4SDimitry Andric     case options::OPT_ffp_model_EQ:
2960480093f4SDimitry Andric       // This should only occur in the error case
2961480093f4SDimitry Andric       // since the optID has been replaced by a more granular
2962480093f4SDimitry Andric       // floating point option.
2963480093f4SDimitry Andric       break;
2964480093f4SDimitry Andric 
2965480093f4SDimitry Andric     // Validate and pass through -ffp-exception-behavior option.
2966480093f4SDimitry Andric     case options::OPT_ffp_exception_behavior_EQ: {
2967480093f4SDimitry Andric       StringRef Val = A->getValue();
2968480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2969480093f4SDimitry Andric           !FPExceptionBehavior.equals(Val))
2970480093f4SDimitry Andric         // Warn that previous value of option is overridden.
29715f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
29725f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
29735f757f3fSDimitry Andric                                   FPExceptionBehavior)
2974480093f4SDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2975480093f4SDimitry Andric       TrappingMath = TrappingMathPresent = false;
2976480093f4SDimitry Andric       if (Val.equals("ignore") || Val.equals("maytrap"))
2977480093f4SDimitry Andric         FPExceptionBehavior = Val;
2978480093f4SDimitry Andric       else if (Val.equals("strict")) {
2979480093f4SDimitry Andric         FPExceptionBehavior = Val;
2980480093f4SDimitry Andric         TrappingMath = TrappingMathPresent = true;
2981480093f4SDimitry Andric       } else
2982480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2983bdd1243dSDimitry Andric             << A->getSpelling() << Val;
2984480093f4SDimitry Andric       break;
2985480093f4SDimitry Andric     }
2986480093f4SDimitry Andric 
298781ad6265SDimitry Andric     // Validate and pass through -ffp-eval-method option.
298881ad6265SDimitry Andric     case options::OPT_ffp_eval_method_EQ: {
298981ad6265SDimitry Andric       StringRef Val = A->getValue();
299081ad6265SDimitry Andric       if (Val.equals("double") || Val.equals("extended") ||
299181ad6265SDimitry Andric           Val.equals("source"))
299281ad6265SDimitry Andric         FPEvalMethod = Val;
299381ad6265SDimitry Andric       else
299481ad6265SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2995bdd1243dSDimitry Andric             << A->getSpelling() << Val;
299681ad6265SDimitry Andric       break;
299781ad6265SDimitry Andric     }
299881ad6265SDimitry Andric 
2999bdd1243dSDimitry Andric     case options::OPT_fexcess_precision_EQ: {
3000bdd1243dSDimitry Andric       StringRef Val = A->getValue();
3001bdd1243dSDimitry Andric       const llvm::Triple::ArchType Arch = TC.getArch();
3002bdd1243dSDimitry Andric       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3003bdd1243dSDimitry Andric         if (Val.equals("standard") || Val.equals("fast"))
3004bdd1243dSDimitry Andric           Float16ExcessPrecision = Val;
3005bdd1243dSDimitry Andric         // To make it GCC compatible, allow the value of "16" which
3006bdd1243dSDimitry Andric         // means disable excess precision, the same meaning than clang's
3007bdd1243dSDimitry Andric         // equivalent value "none".
3008bdd1243dSDimitry Andric         else if (Val.equals("16"))
3009bdd1243dSDimitry Andric           Float16ExcessPrecision = "none";
3010bdd1243dSDimitry Andric         else
3011bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
3012bdd1243dSDimitry Andric               << A->getSpelling() << Val;
3013bdd1243dSDimitry Andric       } else {
3014bdd1243dSDimitry Andric         if (!(Val.equals("standard") || Val.equals("fast")))
3015bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
3016bdd1243dSDimitry Andric               << A->getSpelling() << Val;
3017bdd1243dSDimitry Andric       }
301806c3fb27SDimitry Andric       BFloat16ExcessPrecision = Float16ExcessPrecision;
3019bdd1243dSDimitry Andric       break;
3020bdd1243dSDimitry Andric     }
30210b57cec5SDimitry Andric     case options::OPT_ffinite_math_only:
30220b57cec5SDimitry Andric       HonorINFs = false;
30230b57cec5SDimitry Andric       HonorNaNs = false;
30240b57cec5SDimitry Andric       break;
30250b57cec5SDimitry Andric     case options::OPT_fno_finite_math_only:
30260b57cec5SDimitry Andric       HonorINFs = true;
30270b57cec5SDimitry Andric       HonorNaNs = true;
30280b57cec5SDimitry Andric       break;
30290b57cec5SDimitry Andric 
30300b57cec5SDimitry Andric     case options::OPT_funsafe_math_optimizations:
30310b57cec5SDimitry Andric       AssociativeMath = true;
30320b57cec5SDimitry Andric       ReciprocalMath = true;
30330b57cec5SDimitry Andric       SignedZeros = false;
303404eeddc0SDimitry Andric       ApproxFunc = true;
30350b57cec5SDimitry Andric       TrappingMath = false;
3036480093f4SDimitry Andric       FPExceptionBehavior = "";
3037bdd1243dSDimitry Andric       FPContract = "fast";
3038bdd1243dSDimitry Andric       SeenUnsafeMathModeOption = true;
30390b57cec5SDimitry Andric       break;
30400b57cec5SDimitry Andric     case options::OPT_fno_unsafe_math_optimizations:
30410b57cec5SDimitry Andric       AssociativeMath = false;
30420b57cec5SDimitry Andric       ReciprocalMath = false;
30430b57cec5SDimitry Andric       SignedZeros = true;
304404eeddc0SDimitry Andric       ApproxFunc = false;
30450b57cec5SDimitry Andric       TrappingMath = true;
3046480093f4SDimitry Andric       FPExceptionBehavior = "strict";
30475ffd83dbSDimitry Andric 
30485ffd83dbSDimitry Andric       // The target may have opted to flush by default, so force IEEE.
30495ffd83dbSDimitry Andric       DenormalFPMath = llvm::DenormalMode::getIEEE();
30505ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3051bdd1243dSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3052bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3053bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3054bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3055bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3056bdd1243dSDimitry Andric           FPContract = "on";
3057bdd1243dSDimitry Andric       }
30580b57cec5SDimitry Andric       break;
30590b57cec5SDimitry Andric 
30600b57cec5SDimitry Andric     case options::OPT_Ofast:
30610b57cec5SDimitry Andric       // If -Ofast is the optimization level, then -ffast-math should be enabled
30620b57cec5SDimitry Andric       if (!OFastEnabled)
30630b57cec5SDimitry Andric         continue;
3064bdd1243dSDimitry Andric       [[fallthrough]];
30655f757f3fSDimitry Andric     case options::OPT_ffast_math: {
30660b57cec5SDimitry Andric       HonorINFs = false;
30670b57cec5SDimitry Andric       HonorNaNs = false;
30680b57cec5SDimitry Andric       MathErrno = false;
30690b57cec5SDimitry Andric       AssociativeMath = true;
30700b57cec5SDimitry Andric       ReciprocalMath = true;
307104eeddc0SDimitry Andric       ApproxFunc = true;
30720b57cec5SDimitry Andric       SignedZeros = false;
30730b57cec5SDimitry Andric       TrappingMath = false;
3074480093f4SDimitry Andric       RoundingFPMath = false;
3075bdd1243dSDimitry Andric       FPExceptionBehavior = "";
30760b57cec5SDimitry Andric       // If fast-math is set then set the fp-contract mode to fast.
30770b57cec5SDimitry Andric       FPContract = "fast";
3078bdd1243dSDimitry Andric       SeenUnsafeMathModeOption = true;
30795f757f3fSDimitry Andric       // ffast-math enables fortran rules for complex multiplication and
30805f757f3fSDimitry Andric       // division.
30817a6dacacSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Limited;
30820b57cec5SDimitry Andric       break;
30835f757f3fSDimitry Andric     }
30840b57cec5SDimitry Andric     case options::OPT_fno_fast_math:
30850b57cec5SDimitry Andric       HonorINFs = true;
30860b57cec5SDimitry Andric       HonorNaNs = true;
30870b57cec5SDimitry Andric       // Turning on -ffast-math (with either flag) removes the need for
30880b57cec5SDimitry Andric       // MathErrno. However, turning *off* -ffast-math merely restores the
30890b57cec5SDimitry Andric       // toolchain default (which may be false).
30900b57cec5SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
30910b57cec5SDimitry Andric       AssociativeMath = false;
30920b57cec5SDimitry Andric       ReciprocalMath = false;
309304eeddc0SDimitry Andric       ApproxFunc = false;
30940b57cec5SDimitry Andric       SignedZeros = true;
30950b57cec5SDimitry Andric       // -fno_fast_math restores default denormal and fpcontract handling
30965ffd83dbSDimitry Andric       DenormalFPMath = DefaultDenormalFPMath;
30975ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3098349cc55cSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3099bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3100bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3101bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3102bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3103349cc55cSDimitry Andric           FPContract = "on";
3104349cc55cSDimitry Andric       }
31050b57cec5SDimitry Andric       break;
31060b57cec5SDimitry Andric     }
3107480093f4SDimitry Andric     if (StrictFPModel) {
3108480093f4SDimitry Andric       // If -ffp-model=strict has been specified on command line but
3109480093f4SDimitry Andric       // subsequent options conflict then emit warning diagnostic.
3110349cc55cSDimitry Andric       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
311104eeddc0SDimitry Andric           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
31125ffd83dbSDimitry Andric           DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3113349cc55cSDimitry Andric           DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3114349cc55cSDimitry Andric           FPContract.equals("off"))
3115480093f4SDimitry Andric         // OK: Current Arg doesn't conflict with -ffp-model=strict
3116480093f4SDimitry Andric         ;
3117480093f4SDimitry Andric       else {
3118480093f4SDimitry Andric         StrictFPModel = false;
3119480093f4SDimitry Andric         FPModel = "";
3120bdd1243dSDimitry Andric         auto RHS = (A->getNumValues() == 0)
3121bdd1243dSDimitry Andric                        ? A->getSpelling()
3122bdd1243dSDimitry Andric                        : Args.MakeArgString(A->getSpelling() + A->getValue());
3123bdd1243dSDimitry Andric         if (RHS != "-ffp-model=strict")
31245f757f3fSDimitry Andric           D.Diag(clang::diag::warn_drv_overriding_option)
3125bdd1243dSDimitry Andric               << "-ffp-model=strict" << RHS;
3126480093f4SDimitry Andric       }
3127480093f4SDimitry Andric     }
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric     // If we handled this option claim it
31300b57cec5SDimitry Andric     A->claim();
31310b57cec5SDimitry Andric   }
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric   if (!HonorINFs)
31340b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-infs");
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric   if (!HonorNaNs)
31370b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-nans");
31380b57cec5SDimitry Andric 
3139349cc55cSDimitry Andric   if (ApproxFunc)
3140349cc55cSDimitry Andric     CmdArgs.push_back("-fapprox-func");
3141349cc55cSDimitry Andric 
31420b57cec5SDimitry Andric   if (MathErrno)
31430b57cec5SDimitry Andric     CmdArgs.push_back("-fmath-errno");
31440b57cec5SDimitry Andric 
3145bdd1243dSDimitry Andric  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3146bdd1243dSDimitry Andric      !TrappingMath)
3147bdd1243dSDimitry Andric     CmdArgs.push_back("-funsafe-math-optimizations");
31480b57cec5SDimitry Andric 
31490b57cec5SDimitry Andric   if (!SignedZeros)
31500b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-zeros");
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric   if (AssociativeMath && !SignedZeros && !TrappingMath)
31530b57cec5SDimitry Andric     CmdArgs.push_back("-mreassociate");
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric   if (ReciprocalMath)
31560b57cec5SDimitry Andric     CmdArgs.push_back("-freciprocal-math");
31570b57cec5SDimitry Andric 
3158480093f4SDimitry Andric   if (TrappingMath) {
3159480093f4SDimitry Andric     // FP Exception Behavior is also set to strict
3160480093f4SDimitry Andric     assert(FPExceptionBehavior.equals("strict"));
3161e8d8bef9SDimitry Andric   }
31620b57cec5SDimitry Andric 
31635ffd83dbSDimitry Andric   // The default is IEEE.
31645ffd83dbSDimitry Andric   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
31655ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
31665ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
31675ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
31685ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
31695ffd83dbSDimitry Andric   }
31705ffd83dbSDimitry Andric 
31715ffd83dbSDimitry Andric   // Add f32 specific denormal mode flag if it's different.
31725ffd83dbSDimitry Andric   if (DenormalFP32Math != DenormalFPMath) {
31735ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
31745ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
31755ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
31765ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
31775ffd83dbSDimitry Andric   }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   if (!FPContract.empty())
31800b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
31810b57cec5SDimitry Andric 
3182480093f4SDimitry Andric   if (!RoundingFPMath)
3183480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3184480093f4SDimitry Andric 
3185480093f4SDimitry Andric   if (RoundingFPMath && RoundingMathPresent)
3186480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3187480093f4SDimitry Andric 
3188480093f4SDimitry Andric   if (!FPExceptionBehavior.empty())
3189480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3190480093f4SDimitry Andric                       FPExceptionBehavior));
3191480093f4SDimitry Andric 
319281ad6265SDimitry Andric   if (!FPEvalMethod.empty())
319381ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
319481ad6265SDimitry Andric 
3195bdd1243dSDimitry Andric   if (!Float16ExcessPrecision.empty())
3196bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3197bdd1243dSDimitry Andric                                          Float16ExcessPrecision));
319806c3fb27SDimitry Andric   if (!BFloat16ExcessPrecision.empty())
319906c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
320006c3fb27SDimitry Andric                                          BFloat16ExcessPrecision));
3201bdd1243dSDimitry Andric 
32020b57cec5SDimitry Andric   ParseMRecip(D, Args, CmdArgs);
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
32050b57cec5SDimitry Andric   // individual features enabled by -ffast-math instead of the option itself as
32060b57cec5SDimitry Andric   // that's consistent with gcc's behaviour.
320704eeddc0SDimitry Andric   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3208480093f4SDimitry Andric       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
32090b57cec5SDimitry Andric     CmdArgs.push_back("-ffast-math");
3210480093f4SDimitry Andric     if (FPModel.equals("fast")) {
3211480093f4SDimitry Andric       if (FPContract.equals("fast"))
3212480093f4SDimitry Andric         // All set, do nothing.
3213480093f4SDimitry Andric         ;
3214480093f4SDimitry Andric       else if (FPContract.empty())
3215480093f4SDimitry Andric         // Enable -ffp-contract=fast
3216480093f4SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3217480093f4SDimitry Andric       else
32185f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
3219480093f4SDimitry Andric             << "-ffp-model=fast"
3220480093f4SDimitry Andric             << Args.MakeArgString("-ffp-contract=" + FPContract);
3221480093f4SDimitry Andric     }
3222480093f4SDimitry Andric   }
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric   // Handle __FINITE_MATH_ONLY__ similarly.
32250b57cec5SDimitry Andric   if (!HonorINFs && !HonorNaNs)
32260b57cec5SDimitry Andric     CmdArgs.push_back("-ffinite-math-only");
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
32290b57cec5SDimitry Andric     CmdArgs.push_back("-mfpmath");
32300b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
32310b57cec5SDimitry Andric   }
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   // Disable a codegen optimization for floating-point casts.
32340b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
32350b57cec5SDimitry Andric                    options::OPT_fstrict_float_cast_overflow, false))
32360b57cec5SDimitry Andric     CmdArgs.push_back("-fno-strict-float-cast-overflow");
32375f757f3fSDimitry Andric 
32387a6dacacSDimitry Andric   if (Range != LangOptions::ComplexRangeKind::CX_None)
32397a6dacacSDimitry Andric     ComplexRangeStr = RenderComplexRangeOption(Range);
32407a6dacacSDimitry Andric   if (!ComplexRangeStr.empty())
32417a6dacacSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3242cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_limited_range))
32435f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-limited-range");
3244cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_fortran_rules))
32455f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-fortran-rules");
3246cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_limited_range))
32475f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-limited-range");
3248cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
32495f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-fortran-rules");
32500b57cec5SDimitry Andric }
32510b57cec5SDimitry Andric 
RenderAnalyzerOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input)32520b57cec5SDimitry Andric static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
32530b57cec5SDimitry Andric                                   const llvm::Triple &Triple,
32540b57cec5SDimitry Andric                                   const InputInfo &Input) {
32550b57cec5SDimitry Andric   // Add default argument set.
32560b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
32570b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=core");
32580b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=apiModeling");
32590b57cec5SDimitry Andric 
32600b57cec5SDimitry Andric     if (!Triple.isWindowsMSVCEnvironment()) {
32610b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix");
32620b57cec5SDimitry Andric     } else {
32630b57cec5SDimitry Andric       // Enable "unix" checkers that also work on Windows.
32640b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.API");
32650b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
32660b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
32670b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
32680b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
32690b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
32700b57cec5SDimitry Andric     }
32710b57cec5SDimitry Andric 
327281ad6265SDimitry Andric     // Disable some unix checkers for PS4/PS5.
327381ad6265SDimitry Andric     if (Triple.isPS()) {
32740b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
32750b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
32760b57cec5SDimitry Andric     }
32770b57cec5SDimitry Andric 
3278480093f4SDimitry Andric     if (Triple.isOSDarwin()) {
32790b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=osx");
3280480093f4SDimitry Andric       CmdArgs.push_back(
3281480093f4SDimitry Andric           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3282480093f4SDimitry Andric     }
3283480093f4SDimitry Andric     else if (Triple.isOSFuchsia())
3284480093f4SDimitry Andric       CmdArgs.push_back("-analyzer-checker=fuchsia");
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=deadcode");
32870b57cec5SDimitry Andric 
32880b57cec5SDimitry Andric     if (types::isCXX(Input.getType()))
32890b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=cplusplus");
32900b57cec5SDimitry Andric 
329181ad6265SDimitry Andric     if (!Triple.isPS()) {
32920b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
32930b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
32940b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
32950b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
32960b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
32970b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
32980b57cec5SDimitry Andric     }
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric     // Default nullability checks.
33010b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
33020b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
33030b57cec5SDimitry Andric   }
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric   // Set the output format. The default is plist, for (lame) historical reasons.
33060b57cec5SDimitry Andric   CmdArgs.push_back("-analyzer-output");
33070b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
33080b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
33090b57cec5SDimitry Andric   else
33100b57cec5SDimitry Andric     CmdArgs.push_back("plist");
33110b57cec5SDimitry Andric 
33120b57cec5SDimitry Andric   // Disable the presentation of standard compiler warnings when using
33130b57cec5SDimitry Andric   // --analyze.  We only want to show static analyzer diagnostics or frontend
33140b57cec5SDimitry Andric   // errors.
33150b57cec5SDimitry Andric   CmdArgs.push_back("-w");
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric   // Add -Xanalyzer arguments when running as analyzer.
33180b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
33190b57cec5SDimitry Andric }
33200b57cec5SDimitry Andric 
isValidSymbolName(StringRef S)3321753f127fSDimitry Andric static bool isValidSymbolName(StringRef S) {
3322753f127fSDimitry Andric   if (S.empty())
3323753f127fSDimitry Andric     return false;
3324753f127fSDimitry Andric 
3325753f127fSDimitry Andric   if (std::isdigit(S[0]))
3326753f127fSDimitry Andric     return false;
3327753f127fSDimitry Andric 
3328753f127fSDimitry Andric   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3329753f127fSDimitry Andric }
3330753f127fSDimitry Andric 
RenderSSPOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext)3331e8d8bef9SDimitry Andric static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3332e8d8bef9SDimitry Andric                              const ArgList &Args, ArgStringList &CmdArgs,
3333e8d8bef9SDimitry Andric                              bool KernelOrKext) {
33340b57cec5SDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
33350b57cec5SDimitry Andric 
33360b57cec5SDimitry Andric   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
33370b57cec5SDimitry Andric   // doesn't even have a stack!
33380b57cec5SDimitry Andric   if (EffectiveTriple.isNVPTX())
33390b57cec5SDimitry Andric     return;
33400b57cec5SDimitry Andric 
33410b57cec5SDimitry Andric   // -stack-protector=0 is default.
3342e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3343e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
33440b57cec5SDimitry Andric       TC.GetDefaultStackProtectorLevel(KernelOrKext);
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
33470b57cec5SDimitry Andric                                options::OPT_fstack_protector_all,
33480b57cec5SDimitry Andric                                options::OPT_fstack_protector_strong,
33490b57cec5SDimitry Andric                                options::OPT_fstack_protector)) {
33500b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fstack_protector))
33510b57cec5SDimitry Andric       StackProtectorLevel =
3352e8d8bef9SDimitry Andric           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
33530b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
33540b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPStrong;
33550b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_all))
33560b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPReq;
3357bdd1243dSDimitry Andric 
3358bdd1243dSDimitry Andric     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3359bdd1243dSDimitry Andric       D.Diag(diag::warn_drv_unsupported_option_for_target)
3360bdd1243dSDimitry Andric           << A->getSpelling() << EffectiveTriple.getTriple();
3361bdd1243dSDimitry Andric       StackProtectorLevel = DefaultStackProtectorLevel;
3362bdd1243dSDimitry Andric     }
33630b57cec5SDimitry Andric   } else {
33640b57cec5SDimitry Andric     StackProtectorLevel = DefaultStackProtectorLevel;
33650b57cec5SDimitry Andric   }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric   if (StackProtectorLevel) {
33680b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
33690b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
33700b57cec5SDimitry Andric   }
33710b57cec5SDimitry Andric 
33720b57cec5SDimitry Andric   // --param ssp-buffer-size=
33730b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__param)) {
33740b57cec5SDimitry Andric     StringRef Str(A->getValue());
33755f757f3fSDimitry Andric     if (Str.starts_with("ssp-buffer-size=")) {
33760b57cec5SDimitry Andric       if (StackProtectorLevel) {
33770b57cec5SDimitry Andric         CmdArgs.push_back("-stack-protector-buffer-size");
33780b57cec5SDimitry Andric         // FIXME: Verify the argument is a valid integer.
33790b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
33800b57cec5SDimitry Andric       }
33810b57cec5SDimitry Andric       A->claim();
33820b57cec5SDimitry Andric     }
33830b57cec5SDimitry Andric   }
3384e8d8bef9SDimitry Andric 
3385e8d8bef9SDimitry Andric   const std::string &TripleStr = EffectiveTriple.getTriple();
3386e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3387e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3388349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3389349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3390e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3391e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3392349cc55cSDimitry Andric     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3393349cc55cSDimitry Andric          EffectiveTriple.isThumb()) &&
3394349cc55cSDimitry Andric         Value != "tls" && Value != "global") {
3395e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3396fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "tls global";
3397fe6060f1SDimitry Andric       return;
3398fe6060f1SDimitry Andric     }
3399349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3400349cc55cSDimitry Andric         Value == "tls") {
3401349cc55cSDimitry Andric       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3402349cc55cSDimitry Andric         D.Diag(diag::err_drv_ssp_missing_offset_argument)
3403349cc55cSDimitry Andric             << A->getAsString(Args);
3404349cc55cSDimitry Andric         return;
3405349cc55cSDimitry Andric       }
3406349cc55cSDimitry Andric       // Check whether the target subarch supports the hardware TLS register
340704eeddc0SDimitry Andric       if (!arm::isHardTPSupported(EffectiveTriple)) {
3408349cc55cSDimitry Andric         D.Diag(diag::err_target_unsupported_tp_hard)
3409349cc55cSDimitry Andric             << EffectiveTriple.getArchName();
3410349cc55cSDimitry Andric         return;
3411349cc55cSDimitry Andric       }
3412349cc55cSDimitry Andric       // Check whether the user asked for something other than -mtp=cp15
3413349cc55cSDimitry Andric       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3414349cc55cSDimitry Andric         StringRef Value = A->getValue();
3415349cc55cSDimitry Andric         if (Value != "cp15") {
3416349cc55cSDimitry Andric           D.Diag(diag::err_drv_argument_not_allowed_with)
3417349cc55cSDimitry Andric               << A->getAsString(Args) << "-mstack-protector-guard=tls";
3418349cc55cSDimitry Andric           return;
3419349cc55cSDimitry Andric         }
3420349cc55cSDimitry Andric       }
3421349cc55cSDimitry Andric       CmdArgs.push_back("-target-feature");
342206c3fb27SDimitry Andric       CmdArgs.push_back("+read-tp-tpidruro");
3423349cc55cSDimitry Andric     }
3424fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3425fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3426fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "sysreg global";
3427e8d8bef9SDimitry Andric       return;
3428e8d8bef9SDimitry Andric     }
3429e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3430e8d8bef9SDimitry Andric   }
3431e8d8bef9SDimitry Andric 
3432e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3433e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3434349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3435349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3436e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3437e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3438fe6060f1SDimitry Andric     int Offset;
3439e8d8bef9SDimitry Andric     if (Value.getAsInteger(10, Offset)) {
3440e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3441e8d8bef9SDimitry Andric       return;
3442e8d8bef9SDimitry Andric     }
3443349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3444349cc55cSDimitry Andric         (Offset < 0 || Offset > 0xfffff)) {
3445349cc55cSDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
3446349cc55cSDimitry Andric           << A->getOption().getName() << Value;
3447349cc55cSDimitry Andric       return;
3448349cc55cSDimitry Andric     }
3449e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3450e8d8bef9SDimitry Andric   }
3451e8d8bef9SDimitry Andric 
3452e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3453e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3454fe6060f1SDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3455e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3456e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3457e8d8bef9SDimitry Andric     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3458e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3459fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "fs gs";
3460fe6060f1SDimitry Andric       return;
3461fe6060f1SDimitry Andric     }
3462fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3463fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3464e8d8bef9SDimitry Andric       return;
3465e8d8bef9SDimitry Andric     }
3466e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3467e8d8bef9SDimitry Andric   }
3468753f127fSDimitry Andric 
3469753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3470753f127fSDimitry Andric     StringRef Value = A->getValue();
3471753f127fSDimitry Andric     if (!isValidSymbolName(Value)) {
3472753f127fSDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
3473753f127fSDimitry Andric           << A->getOption().getName() << "legal symbol name";
3474753f127fSDimitry Andric       return;
3475753f127fSDimitry Andric     }
3476753f127fSDimitry Andric     A->render(Args, CmdArgs);
3477753f127fSDimitry Andric   }
34780b57cec5SDimitry Andric }
34790b57cec5SDimitry Andric 
RenderSCPOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)34805ffd83dbSDimitry Andric static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
34815ffd83dbSDimitry Andric                              ArgStringList &CmdArgs) {
34825ffd83dbSDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
34835ffd83dbSDimitry Andric 
34843063e1e5SEd Maste   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
34855ffd83dbSDimitry Andric     return;
34865ffd83dbSDimitry Andric 
34875ffd83dbSDimitry Andric   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
34885f757f3fSDimitry Andric       !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
34895ffd83dbSDimitry Andric     return;
34905ffd83dbSDimitry Andric 
349181ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
349281ad6265SDimitry Andric                     options::OPT_fno_stack_clash_protection);
34935ffd83dbSDimitry Andric }
34945ffd83dbSDimitry Andric 
RenderTrivialAutoVarInitOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)34950b57cec5SDimitry Andric static void RenderTrivialAutoVarInitOptions(const Driver &D,
34960b57cec5SDimitry Andric                                             const ToolChain &TC,
34970b57cec5SDimitry Andric                                             const ArgList &Args,
34980b57cec5SDimitry Andric                                             ArgStringList &CmdArgs) {
34990b57cec5SDimitry Andric   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
35000b57cec5SDimitry Andric   StringRef TrivialAutoVarInit = "";
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   for (const Arg *A : Args) {
35030b57cec5SDimitry Andric     switch (A->getOption().getID()) {
35040b57cec5SDimitry Andric     default:
35050b57cec5SDimitry Andric       continue;
35060b57cec5SDimitry Andric     case options::OPT_ftrivial_auto_var_init: {
35070b57cec5SDimitry Andric       A->claim();
35080b57cec5SDimitry Andric       StringRef Val = A->getValue();
35090b57cec5SDimitry Andric       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
35100b57cec5SDimitry Andric         TrivialAutoVarInit = Val;
35110b57cec5SDimitry Andric       else
35120b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3513bdd1243dSDimitry Andric             << A->getSpelling() << Val;
35140b57cec5SDimitry Andric       break;
35150b57cec5SDimitry Andric     }
35160b57cec5SDimitry Andric     }
35170b57cec5SDimitry Andric   }
35180b57cec5SDimitry Andric 
35190b57cec5SDimitry Andric   if (TrivialAutoVarInit.empty())
35200b57cec5SDimitry Andric     switch (DefaultTrivialAutoVarInit) {
35210b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
35220b57cec5SDimitry Andric       break;
35230b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Pattern:
35240b57cec5SDimitry Andric       TrivialAutoVarInit = "pattern";
35250b57cec5SDimitry Andric       break;
35260b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Zero:
35270b57cec5SDimitry Andric       TrivialAutoVarInit = "zero";
35280b57cec5SDimitry Andric       break;
35290b57cec5SDimitry Andric     }
35300b57cec5SDimitry Andric 
35310b57cec5SDimitry Andric   if (!TrivialAutoVarInit.empty()) {
35320b57cec5SDimitry Andric     CmdArgs.push_back(
35330b57cec5SDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
35340b57cec5SDimitry Andric   }
35355ffd83dbSDimitry Andric 
35365ffd83dbSDimitry Andric   if (Arg *A =
35375ffd83dbSDimitry Andric           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
35385ffd83dbSDimitry Andric     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
35395ffd83dbSDimitry Andric         StringRef(
35405ffd83dbSDimitry Andric             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
35415ffd83dbSDimitry Andric             "uninitialized")
35425ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
35435ffd83dbSDimitry Andric     A->claim();
35445ffd83dbSDimitry Andric     StringRef Val = A->getValue();
35455ffd83dbSDimitry Andric     if (std::stoi(Val.str()) <= 0)
35465ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
35475ffd83dbSDimitry Andric     CmdArgs.push_back(
35485ffd83dbSDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
35495ffd83dbSDimitry Andric   }
35507a6dacacSDimitry Andric 
35517a6dacacSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
35527a6dacacSDimitry Andric     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
35537a6dacacSDimitry Andric         StringRef(
35547a6dacacSDimitry Andric             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
35557a6dacacSDimitry Andric             "uninitialized")
35567a6dacacSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
35577a6dacacSDimitry Andric     A->claim();
35587a6dacacSDimitry Andric     StringRef Val = A->getValue();
35597a6dacacSDimitry Andric     if (std::stoi(Val.str()) <= 0)
35607a6dacacSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
35617a6dacacSDimitry Andric     CmdArgs.push_back(
35627a6dacacSDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
35637a6dacacSDimitry Andric   }
35640b57cec5SDimitry Andric }
35650b57cec5SDimitry Andric 
RenderOpenCLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3566fe6060f1SDimitry Andric static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3567fe6060f1SDimitry Andric                                 types::ID InputType) {
35685ffd83dbSDimitry Andric   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
35695ffd83dbSDimitry Andric   // for denormal flushing handling based on the target.
35700b57cec5SDimitry Andric   const unsigned ForwardedArguments[] = {
35710b57cec5SDimitry Andric       options::OPT_cl_opt_disable,
35720b57cec5SDimitry Andric       options::OPT_cl_strict_aliasing,
35730b57cec5SDimitry Andric       options::OPT_cl_single_precision_constant,
35740b57cec5SDimitry Andric       options::OPT_cl_finite_math_only,
35750b57cec5SDimitry Andric       options::OPT_cl_kernel_arg_info,
35760b57cec5SDimitry Andric       options::OPT_cl_unsafe_math_optimizations,
35770b57cec5SDimitry Andric       options::OPT_cl_fast_relaxed_math,
35780b57cec5SDimitry Andric       options::OPT_cl_mad_enable,
35790b57cec5SDimitry Andric       options::OPT_cl_no_signed_zeros,
35800b57cec5SDimitry Andric       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
35810b57cec5SDimitry Andric       options::OPT_cl_uniform_work_group_size
35820b57cec5SDimitry Andric   };
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
35850b57cec5SDimitry Andric     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
35860b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
358781ad6265SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
358881ad6265SDimitry Andric     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
358981ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
35900b57cec5SDimitry Andric   }
35910b57cec5SDimitry Andric 
35920b57cec5SDimitry Andric   for (const auto &Arg : ForwardedArguments)
35930b57cec5SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
35940b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3595fe6060f1SDimitry Andric 
3596fe6060f1SDimitry Andric   // Only add the default headers if we are compiling OpenCL sources.
3597fe6060f1SDimitry Andric   if ((types::isOpenCL(InputType) ||
3598fe6060f1SDimitry Andric        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3599fe6060f1SDimitry Andric       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3600fe6060f1SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
3601fe6060f1SDimitry Andric     CmdArgs.push_back("-fdeclare-opencl-builtins");
3602fe6060f1SDimitry Andric   }
36030b57cec5SDimitry Andric }
36040b57cec5SDimitry Andric 
RenderHLSLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)360581ad6265SDimitry Andric static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
360681ad6265SDimitry Andric                               types::ID InputType) {
360781ad6265SDimitry Andric   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
360881ad6265SDimitry Andric                                          options::OPT_D,
3609fcaf7f86SDimitry Andric                                          options::OPT_I,
361081ad6265SDimitry Andric                                          options::OPT_S,
3611bdd1243dSDimitry Andric                                          options::OPT_O,
361281ad6265SDimitry Andric                                          options::OPT_emit_llvm,
3613bdd1243dSDimitry Andric                                          options::OPT_emit_obj,
361481ad6265SDimitry Andric                                          options::OPT_disable_llvm_passes,
3615bdd1243dSDimitry Andric                                          options::OPT_fnative_half_type,
3616bdd1243dSDimitry Andric                                          options::OPT_hlsl_entrypoint};
3617bdd1243dSDimitry Andric   if (!types::isHLSL(InputType))
3618bdd1243dSDimitry Andric     return;
361981ad6265SDimitry Andric   for (const auto &Arg : ForwardedArguments)
362081ad6265SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
362181ad6265SDimitry Andric       A->renderAsInput(Args, CmdArgs);
362281ad6265SDimitry Andric   // Add the default headers if dxc_no_stdinc is not set.
3623bdd1243dSDimitry Andric   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3624bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nostdinc))
362581ad6265SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
362681ad6265SDimitry Andric }
362781ad6265SDimitry Andric 
RenderOpenACCOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)36285f757f3fSDimitry Andric static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
36295f757f3fSDimitry Andric                                  ArgStringList &CmdArgs, types::ID InputType) {
36305f757f3fSDimitry Andric   if (!Args.hasArg(options::OPT_fopenacc))
36315f757f3fSDimitry Andric     return;
36325f757f3fSDimitry Andric 
36335f757f3fSDimitry Andric   CmdArgs.push_back("-fopenacc");
36345f757f3fSDimitry Andric 
36355f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
36365f757f3fSDimitry Andric     StringRef Value = A->getValue();
36375f757f3fSDimitry Andric     int Version;
36385f757f3fSDimitry Andric     if (!Value.getAsInteger(10, Version))
36395f757f3fSDimitry Andric       A->renderAsInput(Args, CmdArgs);
36405f757f3fSDimitry Andric     else
36415f757f3fSDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << Value;
36425f757f3fSDimitry Andric   }
36435f757f3fSDimitry Andric }
36445f757f3fSDimitry Andric 
RenderARCMigrateToolOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)36450b57cec5SDimitry Andric static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
36460b57cec5SDimitry Andric                                         ArgStringList &CmdArgs) {
36470b57cec5SDimitry Andric   bool ARCMTEnabled = false;
36480b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
36490b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
36500b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_modify,
36510b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_migrate)) {
36520b57cec5SDimitry Andric       ARCMTEnabled = true;
36530b57cec5SDimitry Andric       switch (A->getOption().getID()) {
36540b57cec5SDimitry Andric       default: llvm_unreachable("missed a case");
36550b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_check:
3656e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=check");
36570b57cec5SDimitry Andric         break;
36580b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_modify:
3659e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=modify");
36600b57cec5SDimitry Andric         break;
36610b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_migrate:
3662e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=migrate");
36630b57cec5SDimitry Andric         CmdArgs.push_back("-mt-migrate-directory");
36640b57cec5SDimitry Andric         CmdArgs.push_back(A->getValue());
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
36670b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
36680b57cec5SDimitry Andric         break;
36690b57cec5SDimitry Andric       }
36700b57cec5SDimitry Andric     }
36710b57cec5SDimitry Andric   } else {
36720b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
36730b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
36740b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
36750b57cec5SDimitry Andric   }
36760b57cec5SDimitry Andric 
36770b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
36780b57cec5SDimitry Andric     if (ARCMTEnabled)
36790b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
36800b57cec5SDimitry Andric           << A->getAsString(Args) << "-ccc-arcmt-migrate";
36810b57cec5SDimitry Andric 
36820b57cec5SDimitry Andric     CmdArgs.push_back("-mt-migrate-directory");
36830b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
36860b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_subscripting,
36870b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_property)) {
36880b57cec5SDimitry Andric       // None specified, means enable them all.
36890b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-literals");
36900b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-subscripting");
36910b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-property");
36920b57cec5SDimitry Andric     } else {
36930b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
36940b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
36950b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
36960b57cec5SDimitry Andric     }
36970b57cec5SDimitry Andric   } else {
36980b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
36990b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
37000b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
37010b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
37020b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
37030b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
37040b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
37050b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
37060b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
37070b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
37080b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
37090b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
37100b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
37110b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
37120b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3713349cc55cSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
37140b57cec5SDimitry Andric   }
37150b57cec5SDimitry Andric }
37160b57cec5SDimitry Andric 
RenderBuiltinOptions(const ToolChain & TC,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs)37170b57cec5SDimitry Andric static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
37180b57cec5SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
37190b57cec5SDimitry Andric   // -fbuiltin is default unless -mkernel is used.
37200b57cec5SDimitry Andric   bool UseBuiltins =
37210b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
37220b57cec5SDimitry Andric                    !Args.hasArg(options::OPT_mkernel));
37230b57cec5SDimitry Andric   if (!UseBuiltins)
37240b57cec5SDimitry Andric     CmdArgs.push_back("-fno-builtin");
37250b57cec5SDimitry Andric 
37260b57cec5SDimitry Andric   // -ffreestanding implies -fno-builtin.
37270b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_ffreestanding))
37280b57cec5SDimitry Andric     UseBuiltins = false;
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric   // Process the -fno-builtin-* options.
373181ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
373281ad6265SDimitry Andric     A->claim();
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric     // If -fno-builtin is specified, then there's no need to pass the option to
37350b57cec5SDimitry Andric     // the frontend.
373681ad6265SDimitry Andric     if (UseBuiltins)
373781ad6265SDimitry Andric       A->render(Args, CmdArgs);
37380b57cec5SDimitry Andric   }
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   // le32-specific flags:
37410b57cec5SDimitry Andric   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
37420b57cec5SDimitry Andric   //                     by default.
37430b57cec5SDimitry Andric   if (TC.getArch() == llvm::Triple::le32)
37440b57cec5SDimitry Andric     CmdArgs.push_back("-fno-math-builtin");
37450b57cec5SDimitry Andric }
37460b57cec5SDimitry Andric 
getDefaultModuleCachePath(SmallVectorImpl<char> & Result)37475ffd83dbSDimitry Andric bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
374881ad6265SDimitry Andric   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
374981ad6265SDimitry Andric     Twine Path{Str};
375081ad6265SDimitry Andric     Path.toVector(Result);
375181ad6265SDimitry Andric     return Path.getSingleStringRef() != "";
375281ad6265SDimitry Andric   }
37535ffd83dbSDimitry Andric   if (llvm::sys::path::cache_directory(Result)) {
37545ffd83dbSDimitry Andric     llvm::sys::path::append(Result, "clang");
37550b57cec5SDimitry Andric     llvm::sys::path::append(Result, "ModuleCache");
37565ffd83dbSDimitry Andric     return true;
37575ffd83dbSDimitry Andric   }
37585ffd83dbSDimitry Andric   return false;
37590b57cec5SDimitry Andric }
37600b57cec5SDimitry Andric 
RenderModulesOptions(Compilation & C,const Driver & D,const ArgList & Args,const InputInfo & Input,const InputInfo & Output,bool HaveStd20,ArgStringList & CmdArgs)3761bdd1243dSDimitry Andric static bool RenderModulesOptions(Compilation &C, const Driver &D,
37620b57cec5SDimitry Andric                                  const ArgList &Args, const InputInfo &Input,
37635f757f3fSDimitry Andric                                  const InputInfo &Output, bool HaveStd20,
3764bdd1243dSDimitry Andric                                  ArgStringList &CmdArgs) {
3765bdd1243dSDimitry Andric   bool IsCXX = types::isCXX(Input.getType());
37665f757f3fSDimitry Andric   bool HaveStdCXXModules = IsCXX && HaveStd20;
3767bdd1243dSDimitry Andric   bool HaveModules = HaveStdCXXModules;
3768bdd1243dSDimitry Andric 
37690b57cec5SDimitry Andric   // -fmodules enables the use of precompiled modules (off by default).
37700b57cec5SDimitry Andric   // Users can pass -fno-cxx-modules to turn off modules support for
37710b57cec5SDimitry Andric   // C++/Objective-C++ programs.
37720b57cec5SDimitry Andric   bool HaveClangModules = false;
37730b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
37740b57cec5SDimitry Andric     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
37750b57cec5SDimitry Andric                                      options::OPT_fno_cxx_modules, true);
3776bdd1243dSDimitry Andric     if (AllowedInCXX || !IsCXX) {
37770b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules");
37780b57cec5SDimitry Andric       HaveClangModules = true;
37790b57cec5SDimitry Andric     }
37800b57cec5SDimitry Andric   }
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric   HaveModules |= HaveClangModules;
37830b57cec5SDimitry Andric 
37840b57cec5SDimitry Andric   // -fmodule-maps enables implicit reading of module map files. By default,
37850b57cec5SDimitry Andric   // this is enabled if we are using Clang's flavor of precompiled modules.
37860b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
37870b57cec5SDimitry Andric                    options::OPT_fno_implicit_module_maps, HaveClangModules))
37880b57cec5SDimitry Andric     CmdArgs.push_back("-fimplicit-module-maps");
37890b57cec5SDimitry Andric 
37900b57cec5SDimitry Andric   // -fmodules-decluse checks that modules used are declared so (off by default)
379181ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
379281ad6265SDimitry Andric                     options::OPT_fno_modules_decluse);
37930b57cec5SDimitry Andric 
37940b57cec5SDimitry Andric   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
37950b57cec5SDimitry Andric   // all #included headers are part of modules.
37960b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
37970b57cec5SDimitry Andric                    options::OPT_fno_modules_strict_decluse, false))
37980b57cec5SDimitry Andric     CmdArgs.push_back("-fmodules-strict-decluse");
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric   // -fno-implicit-modules turns off implicitly compiling modules on demand.
38010b57cec5SDimitry Andric   bool ImplicitModules = false;
38020b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fimplicit_modules,
38030b57cec5SDimitry Andric                     options::OPT_fno_implicit_modules, HaveClangModules)) {
38040b57cec5SDimitry Andric     if (HaveModules)
38050b57cec5SDimitry Andric       CmdArgs.push_back("-fno-implicit-modules");
38060b57cec5SDimitry Andric   } else if (HaveModules) {
38070b57cec5SDimitry Andric     ImplicitModules = true;
38080b57cec5SDimitry Andric     // -fmodule-cache-path specifies where our implicitly-built module files
38090b57cec5SDimitry Andric     // should be written.
38100b57cec5SDimitry Andric     SmallString<128> Path;
38110b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
38120b57cec5SDimitry Andric       Path = A->getValue();
38130b57cec5SDimitry Andric 
38145ffd83dbSDimitry Andric     bool HasPath = true;
38150b57cec5SDimitry Andric     if (C.isForDiagnostics()) {
38160b57cec5SDimitry Andric       // When generating crash reports, we want to emit the modules along with
38170b57cec5SDimitry Andric       // the reproduction sources, so we ignore any provided module path.
38180b57cec5SDimitry Andric       Path = Output.getFilename();
38190b57cec5SDimitry Andric       llvm::sys::path::replace_extension(Path, ".cache");
38200b57cec5SDimitry Andric       llvm::sys::path::append(Path, "modules");
38210b57cec5SDimitry Andric     } else if (Path.empty()) {
38220b57cec5SDimitry Andric       // No module path was provided: use the default.
38235ffd83dbSDimitry Andric       HasPath = Driver::getDefaultModuleCachePath(Path);
38240b57cec5SDimitry Andric     }
38250b57cec5SDimitry Andric 
38265ffd83dbSDimitry Andric     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
38275ffd83dbSDimitry Andric     // That being said, that failure is unlikely and not caching is harmless.
38285ffd83dbSDimitry Andric     if (HasPath) {
38290b57cec5SDimitry Andric       const char Arg[] = "-fmodules-cache-path=";
38300b57cec5SDimitry Andric       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
38310b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Path));
38320b57cec5SDimitry Andric     }
38335ffd83dbSDimitry Andric   }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric   if (HaveModules) {
3836e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3837e8d8bef9SDimitry Andric                      options::OPT_fno_prebuilt_implicit_modules, false))
3838e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprebuilt-implicit-modules");
3839a7dea167SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3840a7dea167SDimitry Andric                      options::OPT_fno_modules_validate_input_files_content,
3841a7dea167SDimitry Andric                      false))
3842a7dea167SDimitry Andric       CmdArgs.push_back("-fvalidate-ast-input-files-content");
38430b57cec5SDimitry Andric   }
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric   // -fmodule-name specifies the module that is currently being built (or
38460b57cec5SDimitry Andric   // used for header checking by -fmodule-maps).
38470b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
38480b57cec5SDimitry Andric 
38490b57cec5SDimitry Andric   // -fmodule-map-file can be used to specify files containing module
38500b57cec5SDimitry Andric   // definitions.
38510b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric   // -fbuiltin-module-map can be used to load the clang
38540b57cec5SDimitry Andric   // builtin headers modulemap file.
38550b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
38560b57cec5SDimitry Andric     SmallString<128> BuiltinModuleMap(D.ResourceDir);
38570b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "include");
38580b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
38590b57cec5SDimitry Andric     if (llvm::sys::fs::exists(BuiltinModuleMap))
38600b57cec5SDimitry Andric       CmdArgs.push_back(
38610b57cec5SDimitry Andric           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
38620b57cec5SDimitry Andric   }
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric   // The -fmodule-file=<name>=<file> form specifies the mapping of module
38650b57cec5SDimitry Andric   // names to precompiled module files (the module is loaded only if used).
38660b57cec5SDimitry Andric   // The -fmodule-file=<file> form can be used to unconditionally load
38670b57cec5SDimitry Andric   // precompiled module files (whether used or not).
386806c3fb27SDimitry Andric   if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
38690b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
387006c3fb27SDimitry Andric 
387106c3fb27SDimitry Andric     // -fprebuilt-module-path specifies where to load the prebuilt module files.
387206c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
387306c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
387406c3fb27SDimitry Andric           std::string("-fprebuilt-module-path=") + A->getValue()));
387506c3fb27SDimitry Andric       A->claim();
387606c3fb27SDimitry Andric     }
387706c3fb27SDimitry Andric   } else
38780b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodule_file);
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric   // When building modules and generating crashdumps, we need to dump a module
38810b57cec5SDimitry Andric   // dependency VFS alongside the output.
38820b57cec5SDimitry Andric   if (HaveClangModules && C.isForDiagnostics()) {
38830b57cec5SDimitry Andric     SmallString<128> VFSDir(Output.getFilename());
38840b57cec5SDimitry Andric     llvm::sys::path::replace_extension(VFSDir, ".cache");
38850b57cec5SDimitry Andric     // Add the cache directory as a temp so the crash diagnostics pick it up.
38860b57cec5SDimitry Andric     C.addTempFile(Args.MakeArgString(VFSDir));
38870b57cec5SDimitry Andric 
38880b57cec5SDimitry Andric     llvm::sys::path::append(VFSDir, "vfs");
38890b57cec5SDimitry Andric     CmdArgs.push_back("-module-dependency-dir");
38900b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(VFSDir));
38910b57cec5SDimitry Andric   }
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric   if (HaveClangModules)
38940b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
38950b57cec5SDimitry Andric 
38960b57cec5SDimitry Andric   // Pass through all -fmodules-ignore-macro arguments.
38970b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
38980b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
38990b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
39000b57cec5SDimitry Andric 
3901753f127fSDimitry Andric   if (HaveClangModules) {
39020b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
39030b57cec5SDimitry Andric 
39040b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
39050b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
39060b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
39070b57cec5SDimitry Andric             << A->getAsString(Args) << "-fbuild-session-timestamp";
39080b57cec5SDimitry Andric 
39090b57cec5SDimitry Andric       llvm::sys::fs::file_status Status;
39100b57cec5SDimitry Andric       if (llvm::sys::fs::status(A->getValue(), Status))
39110b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << A->getValue();
3912349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
3913349cc55cSDimitry Andric           "-fbuild-session-timestamp=" +
3914349cc55cSDimitry Andric           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3915349cc55cSDimitry Andric                     Status.getLastModificationTime().time_since_epoch())
39160b57cec5SDimitry Andric                     .count())));
39170b57cec5SDimitry Andric     }
39180b57cec5SDimitry Andric 
3919753f127fSDimitry Andric     if (Args.getLastArg(
3920753f127fSDimitry Andric             options::OPT_fmodules_validate_once_per_build_session)) {
39210b57cec5SDimitry Andric       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
39220b57cec5SDimitry Andric                            options::OPT_fbuild_session_file))
39230b57cec5SDimitry Andric         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
39240b57cec5SDimitry Andric 
39250b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs,
39260b57cec5SDimitry Andric                       options::OPT_fmodules_validate_once_per_build_session);
39270b57cec5SDimitry Andric     }
39280b57cec5SDimitry Andric 
39290b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
39300b57cec5SDimitry Andric                      options::OPT_fno_modules_validate_system_headers,
39310b57cec5SDimitry Andric                      ImplicitModules))
39320b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules-validate-system-headers");
39330b57cec5SDimitry Andric 
3934753f127fSDimitry Andric     Args.AddLastArg(CmdArgs,
3935753f127fSDimitry Andric                     options::OPT_fmodules_disable_diagnostic_validation);
3936753f127fSDimitry Andric   } else {
3937753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3938753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3939753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3940753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3941753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3942753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3943753f127fSDimitry Andric   }
3944bdd1243dSDimitry Andric 
3945b3edf446SDimitry Andric   // FIXME: We provisionally don't check ODR violations for decls in the global
3946b3edf446SDimitry Andric   // module fragment.
3947b3edf446SDimitry Andric   CmdArgs.push_back("-fskip-odr-check-in-gmf");
3948b3edf446SDimitry Andric 
3949bdd1243dSDimitry Andric   // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3950bdd1243dSDimitry Andric   Args.ClaimAllArgs(options::OPT_fmodule_output);
3951bdd1243dSDimitry Andric   Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3952bdd1243dSDimitry Andric 
3953bdd1243dSDimitry Andric   return HaveModules;
39540b57cec5SDimitry Andric }
39550b57cec5SDimitry Andric 
RenderCharacterOptions(const ArgList & Args,const llvm::Triple & T,ArgStringList & CmdArgs)39560b57cec5SDimitry Andric static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
39570b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
39580b57cec5SDimitry Andric   // -fsigned-char is default.
39590b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
39600b57cec5SDimitry Andric                                      options::OPT_fno_signed_char,
39610b57cec5SDimitry Andric                                      options::OPT_funsigned_char,
39620b57cec5SDimitry Andric                                      options::OPT_fno_unsigned_char)) {
39630b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_funsigned_char) ||
39640b57cec5SDimitry Andric         A->getOption().matches(options::OPT_fno_signed_char)) {
39650b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-char");
39660b57cec5SDimitry Andric     }
39670b57cec5SDimitry Andric   } else if (!isSignedCharDefault(T)) {
39680b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-char");
39690b57cec5SDimitry Andric   }
39700b57cec5SDimitry Andric 
39710b57cec5SDimitry Andric   // The default depends on the language standard.
39720b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
39750b57cec5SDimitry Andric                                      options::OPT_fno_short_wchar)) {
39760b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fshort_wchar)) {
39770b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=short");
39780b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-wchar");
39790b57cec5SDimitry Andric     } else {
39800b57cec5SDimitry Andric       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
39810b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=int");
3982e8d8bef9SDimitry Andric       if (T.isOSzOS() ||
3983e8d8bef9SDimitry Andric           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
39840b57cec5SDimitry Andric         CmdArgs.push_back("-fno-signed-wchar");
39850b57cec5SDimitry Andric       else
39860b57cec5SDimitry Andric         CmdArgs.push_back("-fsigned-wchar");
39870b57cec5SDimitry Andric     }
398806c3fb27SDimitry Andric   } else if (T.isOSzOS())
398906c3fb27SDimitry Andric     CmdArgs.push_back("-fno-signed-wchar");
39900b57cec5SDimitry Andric }
39910b57cec5SDimitry Andric 
RenderObjCOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,ObjCRuntime & Runtime,bool InferCovariantReturns,const InputInfo & Input,ArgStringList & CmdArgs)39920b57cec5SDimitry Andric static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
39930b57cec5SDimitry Andric                               const llvm::Triple &T, const ArgList &Args,
39940b57cec5SDimitry Andric                               ObjCRuntime &Runtime, bool InferCovariantReturns,
39950b57cec5SDimitry Andric                               const InputInfo &Input, ArgStringList &CmdArgs) {
39960b57cec5SDimitry Andric   const llvm::Triple::ArchType Arch = TC.getArch();
39970b57cec5SDimitry Andric 
39980b57cec5SDimitry Andric   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
39990b57cec5SDimitry Andric   // is the default. Except for deployment target of 10.5, next runtime is
40000b57cec5SDimitry Andric   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
40010b57cec5SDimitry Andric   if (Runtime.isNonFragile()) {
40020b57cec5SDimitry Andric     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
40030b57cec5SDimitry Andric                       options::OPT_fno_objc_legacy_dispatch,
40040b57cec5SDimitry Andric                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
40050b57cec5SDimitry Andric       if (TC.UseObjCMixedDispatch())
40060b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
40070b57cec5SDimitry Andric       else
40080b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
40090b57cec5SDimitry Andric     }
40100b57cec5SDimitry Andric   }
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
40130b57cec5SDimitry Andric   // to do Array/Dictionary subscripting by default.
40140b57cec5SDimitry Andric   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
40150b57cec5SDimitry Andric       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
40160b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
40170b57cec5SDimitry Andric 
40180b57cec5SDimitry Andric   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
40190b57cec5SDimitry Andric   // NOTE: This logic is duplicated in ToolChains.cpp.
40200b57cec5SDimitry Andric   if (isObjCAutoRefCount(Args)) {
40210b57cec5SDimitry Andric     TC.CheckObjCARC();
40220b57cec5SDimitry Andric 
40230b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-arc");
40240b57cec5SDimitry Andric 
40250b57cec5SDimitry Andric     // FIXME: It seems like this entire block, and several around it should be
40260b57cec5SDimitry Andric     // wrapped in isObjC, but for now we just use it here as this is where it
40270b57cec5SDimitry Andric     // was being used previously.
40280b57cec5SDimitry Andric     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
40290b57cec5SDimitry Andric       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
40300b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
40310b57cec5SDimitry Andric       else
40320b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
40330b57cec5SDimitry Andric     }
40340b57cec5SDimitry Andric 
40350b57cec5SDimitry Andric     // Allow the user to enable full exceptions code emission.
40360b57cec5SDimitry Andric     // We default off for Objective-C, on for Objective-C++.
40370b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
40380b57cec5SDimitry Andric                      options::OPT_fno_objc_arc_exceptions,
40390b57cec5SDimitry Andric                      /*Default=*/types::isCXX(Input.getType())))
40400b57cec5SDimitry Andric       CmdArgs.push_back("-fobjc-arc-exceptions");
40410b57cec5SDimitry Andric   }
40420b57cec5SDimitry Andric 
40430b57cec5SDimitry Andric   // Silence warning for full exception code emission options when explicitly
40440b57cec5SDimitry Andric   // set to use no ARC.
40450b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fno_objc_arc)) {
40460b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
40470b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
40480b57cec5SDimitry Andric   }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   // Allow the user to control whether messages can be converted to runtime
40510b57cec5SDimitry Andric   // functions.
40520b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
40530b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(
40540b57cec5SDimitry Andric         options::OPT_fobjc_convert_messages_to_runtime_calls,
40550b57cec5SDimitry Andric         options::OPT_fno_objc_convert_messages_to_runtime_calls);
40560b57cec5SDimitry Andric     if (Arg &&
40570b57cec5SDimitry Andric         Arg->getOption().matches(
40580b57cec5SDimitry Andric             options::OPT_fno_objc_convert_messages_to_runtime_calls))
40590b57cec5SDimitry Andric       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
40600b57cec5SDimitry Andric   }
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric   // -fobjc-infer-related-result-type is the default, except in the Objective-C
40630b57cec5SDimitry Andric   // rewriter.
40640b57cec5SDimitry Andric   if (InferCovariantReturns)
40650b57cec5SDimitry Andric     CmdArgs.push_back("-fno-objc-infer-related-result-type");
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   // Pass down -fobjc-weak or -fno-objc-weak if present.
40680b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
40690b57cec5SDimitry Andric     auto WeakArg =
40700b57cec5SDimitry Andric         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
40710b57cec5SDimitry Andric     if (!WeakArg) {
40720b57cec5SDimitry Andric       // nothing to do
40730b57cec5SDimitry Andric     } else if (!Runtime.allowsWeak()) {
40740b57cec5SDimitry Andric       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
40750b57cec5SDimitry Andric         D.Diag(diag::err_objc_weak_unsupported);
40760b57cec5SDimitry Andric     } else {
40770b57cec5SDimitry Andric       WeakArg->render(Args, CmdArgs);
40780b57cec5SDimitry Andric     }
40790b57cec5SDimitry Andric   }
4080fe6060f1SDimitry Andric 
4081fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4082fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
40830b57cec5SDimitry Andric }
40840b57cec5SDimitry Andric 
RenderDiagnosticsOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)40850b57cec5SDimitry Andric static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
40860b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) {
40870b57cec5SDimitry Andric   bool CaretDefault = true;
40880b57cec5SDimitry Andric   bool ColumnDefault = true;
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
40910b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_column,
40920b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_caret)) {
40930b57cec5SDimitry Andric     switch (A->getOption().getID()) {
40940b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_caret:
40950b57cec5SDimitry Andric       CaretDefault = true;
40960b57cec5SDimitry Andric       ColumnDefault = true;
40970b57cec5SDimitry Andric       break;
40980b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_column:
40990b57cec5SDimitry Andric       CaretDefault = false;
41000b57cec5SDimitry Andric       ColumnDefault = true;
41010b57cec5SDimitry Andric       break;
41020b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_classic:
41030b57cec5SDimitry Andric       CaretDefault = false;
41040b57cec5SDimitry Andric       ColumnDefault = false;
41050b57cec5SDimitry Andric       break;
41060b57cec5SDimitry Andric     }
41070b57cec5SDimitry Andric   }
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   // -fcaret-diagnostics is default.
41100b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
41110b57cec5SDimitry Andric                     options::OPT_fno_caret_diagnostics, CaretDefault))
41120b57cec5SDimitry Andric     CmdArgs.push_back("-fno-caret-diagnostics");
41130b57cec5SDimitry Andric 
411481ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
411581ad6265SDimitry Andric                      options::OPT_fno_diagnostics_fixit_info);
411681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
411781ad6265SDimitry Andric                      options::OPT_fno_diagnostics_show_option);
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   if (const Arg *A =
41200b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
41210b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-show-category");
41220b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
41230b57cec5SDimitry Andric   }
41240b57cec5SDimitry Andric 
412581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
412681ad6265SDimitry Andric                     options::OPT_fno_diagnostics_show_hotness);
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric   if (const Arg *A =
41290b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
41300b57cec5SDimitry Andric     std::string Opt =
41310b57cec5SDimitry Andric         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
41320b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
41330b57cec5SDimitry Andric   }
41340b57cec5SDimitry Andric 
413506c3fb27SDimitry Andric   if (const Arg *A =
413606c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
413706c3fb27SDimitry Andric     std::string Opt =
413806c3fb27SDimitry Andric         std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
413906c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
414006c3fb27SDimitry Andric   }
414106c3fb27SDimitry Andric 
41420b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
41430b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
41440b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
4145fcaf7f86SDimitry Andric     if (StringRef(A->getValue()) == "sarif" ||
4146fcaf7f86SDimitry Andric         StringRef(A->getValue()) == "SARIF")
4147fcaf7f86SDimitry Andric       D.Diag(diag::warn_drv_sarif_format_unstable);
41480b57cec5SDimitry Andric   }
41490b57cec5SDimitry Andric 
41500b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(
41510b57cec5SDimitry Andric           options::OPT_fdiagnostics_show_note_include_stack,
41520b57cec5SDimitry Andric           options::OPT_fno_diagnostics_show_note_include_stack)) {
41530b57cec5SDimitry Andric     const Option &O = A->getOption();
41540b57cec5SDimitry Andric     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
41550b57cec5SDimitry Andric       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
41560b57cec5SDimitry Andric     else
41570b57cec5SDimitry Andric       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
41580b57cec5SDimitry Andric   }
41590b57cec5SDimitry Andric 
41600b57cec5SDimitry Andric   // Color diagnostics are parsed by the driver directly from argv and later
41610b57cec5SDimitry Andric   // re-parsed to construct this job; claim any possible color diagnostic here
41620b57cec5SDimitry Andric   // to avoid warn_drv_unused_argument and diagnose bad
41630b57cec5SDimitry Andric   // OPT_fdiagnostics_color_EQ values.
416481ad6265SDimitry Andric   Args.getLastArg(options::OPT_fcolor_diagnostics,
416581ad6265SDimitry Andric                   options::OPT_fno_color_diagnostics);
416681ad6265SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
41670b57cec5SDimitry Andric     StringRef Value(A->getValue());
41680b57cec5SDimitry Andric     if (Value != "always" && Value != "never" && Value != "auto")
416981ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
417081ad6265SDimitry Andric           << Value << A->getOption().getName();
41710b57cec5SDimitry Andric   }
41720b57cec5SDimitry Andric 
41730b57cec5SDimitry Andric   if (D.getDiags().getDiagnosticOptions().ShowColors)
41740b57cec5SDimitry Andric     CmdArgs.push_back("-fcolor-diagnostics");
41750b57cec5SDimitry Andric 
41760b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fansi_escape_codes))
41770b57cec5SDimitry Andric     CmdArgs.push_back("-fansi-escape-codes");
41780b57cec5SDimitry Andric 
417981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
418081ad6265SDimitry Andric                      options::OPT_fno_show_source_location);
41810b57cec5SDimitry Andric 
418206c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
418306c3fb27SDimitry Andric                      options::OPT_fno_diagnostics_show_line_numbers);
418406c3fb27SDimitry Andric 
41850b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
41860b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-absolute-paths");
41870b57cec5SDimitry Andric 
41880b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
41890b57cec5SDimitry Andric                     ColumnDefault))
41900b57cec5SDimitry Andric     CmdArgs.push_back("-fno-show-column");
41910b57cec5SDimitry Andric 
419281ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
419381ad6265SDimitry Andric                      options::OPT_fno_spell_checking);
41940b57cec5SDimitry Andric }
41950b57cec5SDimitry Andric 
getDebugFissionKind(const Driver & D,const ArgList & Args,Arg * & Arg)4196fcaf7f86SDimitry Andric DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
41970b57cec5SDimitry Andric                                             const ArgList &Args, Arg *&Arg) {
4198e8d8bef9SDimitry Andric   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4199e8d8bef9SDimitry Andric                         options::OPT_gno_split_dwarf);
4200e8d8bef9SDimitry Andric   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
42010b57cec5SDimitry Andric     return DwarfFissionKind::None;
42020b57cec5SDimitry Andric 
42030b57cec5SDimitry Andric   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
42040b57cec5SDimitry Andric     return DwarfFissionKind::Split;
42050b57cec5SDimitry Andric 
42060b57cec5SDimitry Andric   StringRef Value = Arg->getValue();
42070b57cec5SDimitry Andric   if (Value == "split")
42080b57cec5SDimitry Andric     return DwarfFissionKind::Split;
42090b57cec5SDimitry Andric   if (Value == "single")
42100b57cec5SDimitry Andric     return DwarfFissionKind::Single;
42110b57cec5SDimitry Andric 
42120b57cec5SDimitry Andric   D.Diag(diag::err_drv_unsupported_option_argument)
4213bdd1243dSDimitry Andric       << Arg->getSpelling() << Arg->getValue();
42140b57cec5SDimitry Andric   return DwarfFissionKind::None;
42150b57cec5SDimitry Andric }
42160b57cec5SDimitry Andric 
renderDwarfFormat(const Driver & D,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs,unsigned DwarfVersion)4217fe6060f1SDimitry Andric static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4218fe6060f1SDimitry Andric                               const ArgList &Args, ArgStringList &CmdArgs,
4219fe6060f1SDimitry Andric                               unsigned DwarfVersion) {
4220fe6060f1SDimitry Andric   auto *DwarfFormatArg =
4221fe6060f1SDimitry Andric       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4222fe6060f1SDimitry Andric   if (!DwarfFormatArg)
4223fe6060f1SDimitry Andric     return;
4224fe6060f1SDimitry Andric 
4225fe6060f1SDimitry Andric   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4226fe6060f1SDimitry Andric     if (DwarfVersion < 3)
4227fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4228fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4229fe6060f1SDimitry Andric     else if (!T.isArch64Bit())
4230fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4231fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4232fe6060f1SDimitry Andric     else if (!T.isOSBinFormatELF())
4233fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4234fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4235fe6060f1SDimitry Andric   }
4236fe6060f1SDimitry Andric 
4237fe6060f1SDimitry Andric   DwarfFormatArg->render(Args, CmdArgs);
4238fe6060f1SDimitry Andric }
4239fe6060f1SDimitry Andric 
424006c3fb27SDimitry 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)424106c3fb27SDimitry Andric renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
42425f757f3fSDimitry Andric                    const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
42435f757f3fSDimitry Andric                    const InputInfo &Output,
424406c3fb27SDimitry Andric                    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
42450b57cec5SDimitry Andric                    DwarfFissionKind &DwarfFission) {
42460b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
42470b57cec5SDimitry Andric                    options::OPT_fno_debug_info_for_profiling, false) &&
42480b57cec5SDimitry Andric       checkDebugInfoOption(
42490b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
42500b57cec5SDimitry Andric     CmdArgs.push_back("-fdebug-info-for-profiling");
42510b57cec5SDimitry Andric 
42520b57cec5SDimitry Andric   // The 'g' groups options involve a somewhat intricate sequence of decisions
42530b57cec5SDimitry Andric   // about what to pass from the driver to the frontend, but by the time they
42540b57cec5SDimitry Andric   // reach cc1 they've been factored into three well-defined orthogonal choices:
42550b57cec5SDimitry Andric   //  * what level of debug info to generate
42560b57cec5SDimitry Andric   //  * what dwarf version to write
42570b57cec5SDimitry Andric   //  * what debugger tuning to use
42580b57cec5SDimitry Andric   // This avoids having to monkey around further in cc1 other than to disable
42590b57cec5SDimitry Andric   // codeview if not running in a Windows environment. Perhaps even that
42600b57cec5SDimitry Andric   // decision should be made in the driver as well though.
42610b57cec5SDimitry Andric   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
42620b57cec5SDimitry Andric 
42630b57cec5SDimitry Andric   bool SplitDWARFInlining =
42640b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4265480093f4SDimitry Andric                    options::OPT_fno_split_dwarf_inlining, false);
42660b57cec5SDimitry Andric 
4267e8d8bef9SDimitry Andric   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4268e8d8bef9SDimitry Andric   // object file generation and no IR generation, -gN should not be needed. So
4269e8d8bef9SDimitry Andric   // allow -gsplit-dwarf with either -gN or IR input.
4270e8d8bef9SDimitry Andric   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
42710b57cec5SDimitry Andric     Arg *SplitDWARFArg;
42720b57cec5SDimitry Andric     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
42730b57cec5SDimitry Andric     if (DwarfFission != DwarfFissionKind::None &&
42740b57cec5SDimitry Andric         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
42750b57cec5SDimitry Andric       DwarfFission = DwarfFissionKind::None;
42760b57cec5SDimitry Andric       SplitDWARFInlining = false;
42770b57cec5SDimitry Andric     }
4278e8d8bef9SDimitry Andric   }
4279e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
428006c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
42810b57cec5SDimitry Andric 
42820b57cec5SDimitry Andric     // If the last option explicitly specified a debug-info level, use it.
42830b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC) &&
42840b57cec5SDimitry Andric         A->getOption().matches(options::OPT_gN_Group)) {
428506c3fb27SDimitry Andric       DebugInfoKind = debugLevelToInfoKind(*A);
42860b57cec5SDimitry Andric       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
42870b57cec5SDimitry Andric       // complicated if you've disabled inline info in the skeleton CUs
42880b57cec5SDimitry Andric       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
42890b57cec5SDimitry Andric       // line-tables-only, so let those compose naturally in that case.
429006c3fb27SDimitry Andric       if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
429106c3fb27SDimitry Andric           DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
429206c3fb27SDimitry Andric           (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
42930b57cec5SDimitry Andric            SplitDWARFInlining))
42940b57cec5SDimitry Andric         DwarfFission = DwarfFissionKind::None;
42950b57cec5SDimitry Andric     }
42960b57cec5SDimitry Andric   }
42970b57cec5SDimitry Andric 
42980b57cec5SDimitry Andric   // If a debugger tuning argument appeared, remember it.
4299bdd1243dSDimitry Andric   bool HasDebuggerTuning = false;
43000b57cec5SDimitry Andric   if (const Arg *A =
43010b57cec5SDimitry Andric           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4302bdd1243dSDimitry Andric     HasDebuggerTuning = true;
43030b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC)) {
43040b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_glldb))
43050b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::LLDB;
43060b57cec5SDimitry Andric       else if (A->getOption().matches(options::OPT_gsce))
43070b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::SCE;
4308fe6060f1SDimitry Andric       else if (A->getOption().matches(options::OPT_gdbx))
4309fe6060f1SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::DBX;
43100b57cec5SDimitry Andric       else
43110b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::GDB;
43120b57cec5SDimitry Andric     }
43130b57cec5SDimitry Andric   }
43140b57cec5SDimitry Andric 
43150b57cec5SDimitry Andric   // If a -gdwarf argument appeared, remember it.
4316480093f4SDimitry Andric   bool EmitDwarf = false;
4317bdd1243dSDimitry Andric   if (const Arg *A = getDwarfNArg(Args))
4318bdd1243dSDimitry Andric     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
43190b57cec5SDimitry Andric 
43205f757f3fSDimitry Andric   bool EmitCodeView = false;
4321bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4322bdd1243dSDimitry Andric     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
43230b57cec5SDimitry Andric 
43240b57cec5SDimitry Andric   // If the user asked for debug info but did not explicitly specify -gcodeview
43250b57cec5SDimitry Andric   // or -gdwarf, ask the toolchain for the default format.
4326480093f4SDimitry Andric   if (!EmitCodeView && !EmitDwarf &&
432706c3fb27SDimitry Andric       DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
43280b57cec5SDimitry Andric     switch (TC.getDefaultDebugFormat()) {
432906c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_CodeView:
43300b57cec5SDimitry Andric       EmitCodeView = true;
43310b57cec5SDimitry Andric       break;
433206c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_DWARF:
4333480093f4SDimitry Andric       EmitDwarf = true;
43340b57cec5SDimitry Andric       break;
43350b57cec5SDimitry Andric     }
43360b57cec5SDimitry Andric   }
43370b57cec5SDimitry Andric 
4338e8d8bef9SDimitry Andric   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4339e8d8bef9SDimitry Andric   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4340e8d8bef9SDimitry Andric                                       // be lower than what the user wanted.
4341480093f4SDimitry Andric   if (EmitDwarf) {
4342bdd1243dSDimitry Andric     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4343e8d8bef9SDimitry Andric     // Clamp effective DWARF version to the max supported by the toolchain.
4344e8d8bef9SDimitry Andric     EffectiveDWARFVersion =
4345e8d8bef9SDimitry Andric         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4346bdd1243dSDimitry Andric   } else {
4347bdd1243dSDimitry Andric     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4348480093f4SDimitry Andric   }
4349480093f4SDimitry Andric 
43500b57cec5SDimitry Andric   // -gline-directives-only supported only for the DWARF debug info.
4351e8d8bef9SDimitry Andric   if (RequestedDWARFVersion == 0 &&
435206c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
435306c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
43540b57cec5SDimitry Andric 
4355fe6060f1SDimitry Andric   // strict DWARF is set to false by default. But for DBX, we need it to be set
4356fe6060f1SDimitry Andric   // as true by default.
4357fe6060f1SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4358fe6060f1SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4359fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4360fe6060f1SDimitry Andric                    DebuggerTuning == llvm::DebuggerKind::DBX))
4361fe6060f1SDimitry Andric     CmdArgs.push_back("-gstrict-dwarf");
4362fe6060f1SDimitry Andric 
43630b57cec5SDimitry Andric   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
43640b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_flags_Group);
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric   // Column info is included by default for everything except SCE and
43670b57cec5SDimitry Andric   // CodeView. Clang doesn't track end columns, just starting columns, which,
43680b57cec5SDimitry Andric   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4369fe6060f1SDimitry Andric   // Microsoft debuggers don't handle missing end columns well, and the AIX
4370fe6060f1SDimitry Andric   // debugger DBX also doesn't handle the columns well, so it's better not to
4371fe6060f1SDimitry Andric   // include any column info.
43720b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
43730b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
43745ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4375fe6060f1SDimitry Andric                     !EmitCodeView &&
4376fe6060f1SDimitry Andric                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4377fe6060f1SDimitry Andric                          DebuggerTuning != llvm::DebuggerKind::DBX)))
43785ffd83dbSDimitry Andric     CmdArgs.push_back("-gno-column-info");
43790b57cec5SDimitry Andric 
43800b57cec5SDimitry Andric   // FIXME: Move backend command line options to the module.
4381bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4382bdd1243dSDimitry Andric     // If -gline-tables-only or -gline-directives-only is the last option it
4383bdd1243dSDimitry Andric     // wins.
4384bdd1243dSDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4385bdd1243dSDimitry Andric                              TC)) {
438606c3fb27SDimitry Andric       if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
438706c3fb27SDimitry Andric           DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
438806c3fb27SDimitry Andric         DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
43890b57cec5SDimitry Andric         CmdArgs.push_back("-dwarf-ext-refs");
43900b57cec5SDimitry Andric         CmdArgs.push_back("-fmodule-format=obj");
43910b57cec5SDimitry Andric       }
43920b57cec5SDimitry Andric     }
4393bdd1243dSDimitry Andric   }
43940b57cec5SDimitry Andric 
4395fe6060f1SDimitry Andric   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4396fe6060f1SDimitry Andric     CmdArgs.push_back("-fsplit-dwarf-inlining");
43970b57cec5SDimitry Andric 
43980b57cec5SDimitry Andric   // After we've dealt with all combinations of things that could
43990b57cec5SDimitry Andric   // make DebugInfoKind be other than None or DebugLineTablesOnly,
44000b57cec5SDimitry Andric   // figure out if we need to "upgrade" it to standalone debug info.
44010b57cec5SDimitry Andric   // We parse these two '-f' options whether or not they will be used,
44020b57cec5SDimitry Andric   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
44030b57cec5SDimitry Andric   bool NeedFullDebug = Args.hasFlag(
44040b57cec5SDimitry Andric       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
44050b57cec5SDimitry Andric       DebuggerTuning == llvm::DebuggerKind::LLDB ||
44060b57cec5SDimitry Andric           TC.GetDefaultStandaloneDebug());
44070b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
44080b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4409e8d8bef9SDimitry Andric 
441006c3fb27SDimitry Andric   if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
441106c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4412e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4413e8d8bef9SDimitry Andric                      options::OPT_feliminate_unused_debug_types, false))
441406c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4415e8d8bef9SDimitry Andric     else if (NeedFullDebug)
441606c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4417e8d8bef9SDimitry Andric   }
44180b57cec5SDimitry Andric 
44190b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
44200b57cec5SDimitry Andric                    false)) {
44210b57cec5SDimitry Andric     // Source embedding is a vendor extension to DWARF v5. By now we have
44220b57cec5SDimitry Andric     // checked if a DWARF version was stated explicitly, and have otherwise
44230b57cec5SDimitry Andric     // fallen back to the target default, so if this is still not at least 5
44240b57cec5SDimitry Andric     // we emit an error.
44250b57cec5SDimitry Andric     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4426e8d8bef9SDimitry Andric     if (RequestedDWARFVersion < 5)
44270b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
44280b57cec5SDimitry Andric           << A->getAsString(Args) << "-gdwarf-5";
4429e8d8bef9SDimitry Andric     else if (EffectiveDWARFVersion < 5)
4430e8d8bef9SDimitry Andric       // The toolchain has reduced allowed dwarf version, so we can't enable
4431e8d8bef9SDimitry Andric       // -gembed-source.
4432e8d8bef9SDimitry Andric       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4433e8d8bef9SDimitry Andric           << A->getAsString(Args) << TC.getTripleString() << 5
4434e8d8bef9SDimitry Andric           << EffectiveDWARFVersion;
44350b57cec5SDimitry Andric     else if (checkDebugInfoOption(A, Args, D, TC))
44360b57cec5SDimitry Andric       CmdArgs.push_back("-gembed-source");
44370b57cec5SDimitry Andric   }
44380b57cec5SDimitry Andric 
44390b57cec5SDimitry Andric   if (EmitCodeView) {
44400b57cec5SDimitry Andric     CmdArgs.push_back("-gcodeview");
44410b57cec5SDimitry Andric 
4442bdd1243dSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4443bdd1243dSDimitry Andric                       options::OPT_gno_codeview_ghash);
4444bdd1243dSDimitry Andric 
4445bdd1243dSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4446bdd1243dSDimitry Andric                        options::OPT_gno_codeview_command_line);
44470b57cec5SDimitry Andric   }
44480b57cec5SDimitry Andric 
4449bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4450bdd1243dSDimitry Andric                      options::OPT_gno_inline_line_tables);
4451480093f4SDimitry Andric 
4452480093f4SDimitry Andric   // When emitting remarks, we need at least debug lines in the output.
4453480093f4SDimitry Andric   if (willEmitRemarks(Args) &&
445406c3fb27SDimitry Andric       DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
445506c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4456480093f4SDimitry Andric 
4457e8d8bef9SDimitry Andric   // Adjust the debug info kind for the given toolchain.
4458e8d8bef9SDimitry Andric   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4459e8d8bef9SDimitry Andric 
4460bdd1243dSDimitry Andric   // On AIX, the debugger tuning option can be omitted if it is not explicitly
4461bdd1243dSDimitry Andric   // set.
4462e8d8bef9SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4463bdd1243dSDimitry Andric                           T.isOSAIX() && !HasDebuggerTuning
4464bdd1243dSDimitry Andric                               ? llvm::DebuggerKind::Default
4465bdd1243dSDimitry Andric                               : DebuggerTuning);
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric   // -fdebug-macro turns on macro debug info generation.
44680b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
44690b57cec5SDimitry Andric                    false))
44700b57cec5SDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
44710b57cec5SDimitry Andric                              D, TC))
44720b57cec5SDimitry Andric       CmdArgs.push_back("-debug-info-macro");
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric   // -ggnu-pubnames turns on gnu style pubnames in the backend.
44750b57cec5SDimitry Andric   const auto *PubnamesArg =
44760b57cec5SDimitry Andric       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
44770b57cec5SDimitry Andric                       options::OPT_gpubnames, options::OPT_gno_pubnames);
44780b57cec5SDimitry Andric   if (DwarfFission != DwarfFissionKind::None ||
44790b57cec5SDimitry Andric       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
44800b57cec5SDimitry Andric     if (!PubnamesArg ||
44810b57cec5SDimitry Andric         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
44820b57cec5SDimitry Andric          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
44830b57cec5SDimitry Andric       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
44840b57cec5SDimitry Andric                                            options::OPT_gpubnames)
44850b57cec5SDimitry Andric                             ? "-gpubnames"
44860b57cec5SDimitry Andric                             : "-ggnu-pubnames");
4487349cc55cSDimitry Andric   const auto *SimpleTemplateNamesArg =
448881ad6265SDimitry Andric       Args.getLastArg(options::OPT_gsimple_template_names,
448981ad6265SDimitry Andric                       options::OPT_gno_simple_template_names);
4490349cc55cSDimitry Andric   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4491349cc55cSDimitry Andric   if (SimpleTemplateNamesArg &&
4492349cc55cSDimitry Andric       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4493349cc55cSDimitry Andric     const auto &Opt = SimpleTemplateNamesArg->getOption();
4494349cc55cSDimitry Andric     if (Opt.matches(options::OPT_gsimple_template_names)) {
4495349cc55cSDimitry Andric       ForwardTemplateParams = true;
4496349cc55cSDimitry Andric       CmdArgs.push_back("-gsimple-template-names=simple");
4497349cc55cSDimitry Andric     }
4498349cc55cSDimitry Andric   }
44990b57cec5SDimitry Andric 
4500bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4501bdd1243dSDimitry Andric     StringRef v = A->getValue();
4502bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
45030b57cec5SDimitry Andric   }
45040b57cec5SDimitry Andric 
4505bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4506bdd1243dSDimitry Andric                     options::OPT_fno_debug_ranges_base_address);
4507bdd1243dSDimitry Andric 
45080b57cec5SDimitry Andric   // -gdwarf-aranges turns on the emission of the aranges section in the
45090b57cec5SDimitry Andric   // backend.
45100b57cec5SDimitry Andric   // Always enabled for SCE tuning.
45110b57cec5SDimitry Andric   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
45120b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
45130b57cec5SDimitry Andric     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
45140b57cec5SDimitry Andric   if (NeedAranges) {
45150b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
45160b57cec5SDimitry Andric     CmdArgs.push_back("-generate-arange-section");
45170b57cec5SDimitry Andric   }
45180b57cec5SDimitry Andric 
4519bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4520bdd1243dSDimitry Andric                     options::OPT_fno_force_dwarf_frame);
4521480093f4SDimitry Andric 
45220b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_types_section,
45230b57cec5SDimitry Andric                    options::OPT_fno_debug_types_section, false)) {
4524e8d8bef9SDimitry Andric     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
45250b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
45260b57cec5SDimitry Andric           << Args.getLastArg(options::OPT_fdebug_types_section)
45270b57cec5SDimitry Andric                  ->getAsString(Args)
45280b57cec5SDimitry Andric           << T.getTriple();
45290b57cec5SDimitry Andric     } else if (checkDebugInfoOption(
45300b57cec5SDimitry Andric                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
45310b57cec5SDimitry Andric                    TC)) {
45320b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
45330b57cec5SDimitry Andric       CmdArgs.push_back("-generate-type-units");
45340b57cec5SDimitry Andric     }
45350b57cec5SDimitry Andric   }
45360b57cec5SDimitry Andric 
4537fe6060f1SDimitry Andric   // To avoid join/split of directory+filename, the integrated assembler prefers
4538fe6060f1SDimitry Andric   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4539fe6060f1SDimitry Andric   // form before DWARF v5.
4540fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4541fe6060f1SDimitry Andric                     options::OPT_fno_dwarf_directory_asm,
4542fe6060f1SDimitry Andric                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4543fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-dwarf-directory-asm");
4544fe6060f1SDimitry Andric 
45450b57cec5SDimitry Andric   // Decide how to render forward declarations of template instantiations.
45460b57cec5SDimitry Andric   // SCE wants full descriptions, others just get them in the name.
4547349cc55cSDimitry Andric   if (ForwardTemplateParams)
45480b57cec5SDimitry Andric     CmdArgs.push_back("-debug-forward-template-params");
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric   // Do we need to explicitly import anonymous namespaces into the parent
45510b57cec5SDimitry Andric   // scope?
45520b57cec5SDimitry Andric   if (DebuggerTuning == llvm::DebuggerKind::SCE)
45530b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-explicit-import");
45540b57cec5SDimitry Andric 
4555fe6060f1SDimitry Andric   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
45560b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
45575f757f3fSDimitry Andric 
45585f757f3fSDimitry Andric   // This controls whether or not we perform JustMyCode instrumentation.
45595f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
45605f757f3fSDimitry Andric     if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
45615f757f3fSDimitry Andric       if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
45625f757f3fSDimitry Andric         CmdArgs.push_back("-fjmc");
45635f757f3fSDimitry Andric       else if (D.IsCLMode())
45645f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
45655f757f3fSDimitry Andric                                                              << "'/Zi', '/Z7'";
45665f757f3fSDimitry Andric       else
45675f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
45685f757f3fSDimitry Andric                                                              << "-g";
45695f757f3fSDimitry Andric     } else {
45705f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
45715f757f3fSDimitry Andric     }
45725f757f3fSDimitry Andric   }
45735f757f3fSDimitry Andric 
45745f757f3fSDimitry Andric   // Add in -fdebug-compilation-dir if necessary.
45755f757f3fSDimitry Andric   const char *DebugCompilationDir =
45765f757f3fSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
45775f757f3fSDimitry Andric 
45785f757f3fSDimitry Andric   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
45795f757f3fSDimitry Andric 
45805f757f3fSDimitry Andric   // Add the output path to the object file for CodeView debug infos.
45815f757f3fSDimitry Andric   if (EmitCodeView && Output.isFilename())
45825f757f3fSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
45835f757f3fSDimitry Andric                        Output.getFilename());
45840b57cec5SDimitry Andric }
45850b57cec5SDimitry Andric 
ProcessVSRuntimeLibrary(const ArgList & Args,ArgStringList & CmdArgs)4586bdd1243dSDimitry Andric static void ProcessVSRuntimeLibrary(const ArgList &Args,
4587bdd1243dSDimitry Andric                                     ArgStringList &CmdArgs) {
4588bdd1243dSDimitry Andric   unsigned RTOptionID = options::OPT__SLASH_MT;
4589bdd1243dSDimitry Andric 
4590bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_LDd))
4591bdd1243dSDimitry Andric     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4592bdd1243dSDimitry Andric     // but defining _DEBUG is sticky.
4593bdd1243dSDimitry Andric     RTOptionID = options::OPT__SLASH_MTd;
4594bdd1243dSDimitry Andric 
4595bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4596bdd1243dSDimitry Andric     RTOptionID = A->getOption().getID();
4597bdd1243dSDimitry Andric 
4598bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4599bdd1243dSDimitry Andric     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4600bdd1243dSDimitry Andric                      .Case("static", options::OPT__SLASH_MT)
4601bdd1243dSDimitry Andric                      .Case("static_dbg", options::OPT__SLASH_MTd)
4602bdd1243dSDimitry Andric                      .Case("dll", options::OPT__SLASH_MD)
4603bdd1243dSDimitry Andric                      .Case("dll_dbg", options::OPT__SLASH_MDd)
4604bdd1243dSDimitry Andric                      .Default(options::OPT__SLASH_MT);
4605bdd1243dSDimitry Andric   }
4606bdd1243dSDimitry Andric 
4607bdd1243dSDimitry Andric   StringRef FlagForCRT;
4608bdd1243dSDimitry Andric   switch (RTOptionID) {
4609bdd1243dSDimitry Andric   case options::OPT__SLASH_MD:
4610bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4611bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4612bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4613bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4614bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrt";
4615bdd1243dSDimitry Andric     break;
4616bdd1243dSDimitry Andric   case options::OPT__SLASH_MDd:
4617bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4618bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4619bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4620bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrtd";
4621bdd1243dSDimitry Andric     break;
4622bdd1243dSDimitry Andric   case options::OPT__SLASH_MT:
4623bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4624bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4625bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4626bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4627bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmt";
4628bdd1243dSDimitry Andric     break;
4629bdd1243dSDimitry Andric   case options::OPT__SLASH_MTd:
4630bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4631bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4632bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4633bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmtd";
4634bdd1243dSDimitry Andric     break;
4635bdd1243dSDimitry Andric   default:
4636bdd1243dSDimitry Andric     llvm_unreachable("Unexpected option ID.");
4637bdd1243dSDimitry Andric   }
4638bdd1243dSDimitry Andric 
4639bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4640bdd1243dSDimitry Andric     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4641bdd1243dSDimitry Andric   } else {
4642bdd1243dSDimitry Andric     CmdArgs.push_back(FlagForCRT.data());
4643bdd1243dSDimitry Andric 
4644bdd1243dSDimitry Andric     // This provides POSIX compatibility (maps 'open' to '_open'), which most
4645bdd1243dSDimitry Andric     // users want.  The /Za flag to cl.exe turns this off, but it's not
4646bdd1243dSDimitry Andric     // implemented in clang.
4647bdd1243dSDimitry Andric     CmdArgs.push_back("--dependent-lib=oldnames");
4648bdd1243dSDimitry Andric   }
4649bdd1243dSDimitry Andric }
4650bdd1243dSDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const46510b57cec5SDimitry Andric void Clang::ConstructJob(Compilation &C, const JobAction &JA,
46520b57cec5SDimitry Andric                          const InputInfo &Output, const InputInfoList &Inputs,
46530b57cec5SDimitry Andric                          const ArgList &Args, const char *LinkingOutput) const {
46540b57cec5SDimitry Andric   const auto &TC = getToolChain();
46550b57cec5SDimitry Andric   const llvm::Triple &RawTriple = TC.getTriple();
46560b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
46570b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
46580b57cec5SDimitry Andric 
46590b57cec5SDimitry Andric   bool KernelOrKext =
46600b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
46610b57cec5SDimitry Andric   const Driver &D = TC.getDriver();
46620b57cec5SDimitry Andric   ArgStringList CmdArgs;
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   assert(Inputs.size() >= 1 && "Must have at least one input.");
46650b57cec5SDimitry Andric   // CUDA/HIP compilation may have multiple inputs (source file + results of
46660b57cec5SDimitry Andric   // device-side compilations). OpenMP device jobs also take the host IR as a
46670b57cec5SDimitry Andric   // second input. Module precompilation accepts a list of header files to
466881ad6265SDimitry Andric   // include as part of the module. API extraction accepts a list of header
466981ad6265SDimitry Andric   // files whose API information is emitted in the output. All other jobs are
467081ad6265SDimitry Andric   // expected to have exactly one input.
46710b57cec5SDimitry Andric   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4672fe6060f1SDimitry Andric   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
46730b57cec5SDimitry Andric   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4674fe6060f1SDimitry Andric   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
46750b57cec5SDimitry Andric   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
467681ad6265SDimitry Andric   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4677fe6060f1SDimitry Andric   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4678fe6060f1SDimitry Andric                                  JA.isDeviceOffloading(Action::OFK_Host));
467981ad6265SDimitry Andric   bool IsHostOffloadingAction =
4680bdd1243dSDimitry Andric       JA.isHostOffloading(Action::OFK_OpenMP) ||
468181ad6265SDimitry Andric       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
468281ad6265SDimitry Andric        Args.hasFlag(options::OPT_offload_new_driver,
468381ad6265SDimitry Andric                     options::OPT_no_offload_new_driver, false));
468481ad6265SDimitry Andric 
4685753f127fSDimitry Andric   bool IsRDCMode =
4686753f127fSDimitry Andric       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4687fe6060f1SDimitry Andric   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4688fe6060f1SDimitry Andric   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
46890b57cec5SDimitry Andric 
469081ad6265SDimitry Andric   // Extract API doesn't have a main input file, so invent a fake one as a
469181ad6265SDimitry Andric   // placeholder.
469281ad6265SDimitry Andric   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
469381ad6265SDimitry Andric                                        "extract-api");
469481ad6265SDimitry Andric 
4695bdd1243dSDimitry Andric   const InputInfo &Input =
4696bdd1243dSDimitry Andric       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
46970b57cec5SDimitry Andric 
469881ad6265SDimitry Andric   InputInfoList ExtractAPIInputs;
469981ad6265SDimitry Andric   InputInfoList HostOffloadingInputs;
47000b57cec5SDimitry Andric   const InputInfo *CudaDeviceInput = nullptr;
47010b57cec5SDimitry Andric   const InputInfo *OpenMPDeviceInput = nullptr;
47020b57cec5SDimitry Andric   for (const InputInfo &I : Inputs) {
4703bdd1243dSDimitry Andric     if (&I == &Input || I.getType() == types::TY_Nothing) {
4704bdd1243dSDimitry Andric       // This is the primary input or contains nothing.
470581ad6265SDimitry Andric     } else if (IsExtractAPI) {
470681ad6265SDimitry Andric       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
470781ad6265SDimitry Andric       if (I.getType() != ExpectedInputType) {
470881ad6265SDimitry Andric         D.Diag(diag::err_drv_extract_api_wrong_kind)
470981ad6265SDimitry Andric             << I.getFilename() << types::getTypeName(I.getType())
471081ad6265SDimitry Andric             << types::getTypeName(ExpectedInputType);
471181ad6265SDimitry Andric       }
471281ad6265SDimitry Andric       ExtractAPIInputs.push_back(I);
471381ad6265SDimitry Andric     } else if (IsHostOffloadingAction) {
471481ad6265SDimitry Andric       HostOffloadingInputs.push_back(I);
47150b57cec5SDimitry Andric     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
47160b57cec5SDimitry Andric       CudaDeviceInput = &I;
47170b57cec5SDimitry Andric     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
47180b57cec5SDimitry Andric       OpenMPDeviceInput = &I;
47190b57cec5SDimitry Andric     } else {
47200b57cec5SDimitry Andric       llvm_unreachable("unexpectedly given multiple inputs");
47210b57cec5SDimitry Andric     }
47220b57cec5SDimitry Andric   }
47230b57cec5SDimitry Andric 
47245ffd83dbSDimitry Andric   const llvm::Triple *AuxTriple =
47255ffd83dbSDimitry Andric       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
47260b57cec5SDimitry Andric   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
47270b57cec5SDimitry Andric   bool IsIAMCU = RawTriple.isOSIAMCU();
47280b57cec5SDimitry Andric 
47290b57cec5SDimitry Andric   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
47300b57cec5SDimitry Andric   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
47310b57cec5SDimitry Andric   // Windows), we need to pass Windows-specific flags to cc1.
47320b57cec5SDimitry Andric   if (IsCuda || IsHIP)
47330b57cec5SDimitry Andric     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   // C++ is not supported for IAMCU.
47360b57cec5SDimitry Andric   if (IsIAMCU && types::isCXX(Input.getType()))
47370b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
47380b57cec5SDimitry Andric 
47390b57cec5SDimitry Andric   // Invoke ourselves in -cc1 mode.
47400b57cec5SDimitry Andric   //
47410b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
47420b57cec5SDimitry Andric   CmdArgs.push_back("-cc1");
47430b57cec5SDimitry Andric 
47440b57cec5SDimitry Andric   // Add the "effective" target triple.
47450b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
47460b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
47470b57cec5SDimitry Andric 
47480b57cec5SDimitry Andric   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
47490b57cec5SDimitry Andric     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
47500b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_MJ);
4751a7dea167SDimitry Andric   } else if (const Arg *GenCDBFragment =
4752a7dea167SDimitry Andric                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4753a7dea167SDimitry Andric     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4754a7dea167SDimitry Andric                                          TripleStr, Output, Input, Args);
4755a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
47560b57cec5SDimitry Andric   }
47570b57cec5SDimitry Andric 
47580b57cec5SDimitry Andric   if (IsCuda || IsHIP) {
47590b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for a CUDA/HIP device
47600b57cec5SDimitry Andric     // and vice-versa.
47610b57cec5SDimitry Andric     std::string NormalizedTriple;
47620b57cec5SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
47630b57cec5SDimitry Andric         JA.isDeviceOffloading(Action::OFK_HIP))
47640b57cec5SDimitry Andric       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
47650b57cec5SDimitry Andric                              ->getTriple()
47660b57cec5SDimitry Andric                              .normalize();
47670b57cec5SDimitry Andric     else {
47680b57cec5SDimitry Andric       // Host-side compilation.
47690b57cec5SDimitry Andric       NormalizedTriple =
47700b57cec5SDimitry Andric           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
47710b57cec5SDimitry Andric                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
47720b57cec5SDimitry Andric               ->getTriple()
47730b57cec5SDimitry Andric               .normalize();
47740b57cec5SDimitry Andric       if (IsCuda) {
47750b57cec5SDimitry Andric         // We need to figure out which CUDA version we're compiling for, as that
47760b57cec5SDimitry Andric         // determines how we load and launch GPU kernels.
47770b57cec5SDimitry Andric         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
47780b57cec5SDimitry Andric             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
47790b57cec5SDimitry Andric         assert(CTC && "Expected valid CUDA Toolchain.");
47800b57cec5SDimitry Andric         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
47810b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
47820b57cec5SDimitry Andric               Twine("-target-sdk-version=") +
47830b57cec5SDimitry Andric               CudaVersionToString(CTC->CudaInstallation.version())));
478406c3fb27SDimitry Andric         // Unsized function arguments used for variadics were introduced in
478506c3fb27SDimitry Andric         // CUDA-9.0. We still do not support generating code that actually uses
478606c3fb27SDimitry Andric         // variadic arguments yet, but we do need to allow parsing them as
478706c3fb27SDimitry Andric         // recent CUDA headers rely on that.
478806c3fb27SDimitry Andric         // https://github.com/llvm/llvm-project/issues/58410
478906c3fb27SDimitry Andric         if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
479006c3fb27SDimitry Andric           CmdArgs.push_back("-fcuda-allow-variadic-functions");
47910b57cec5SDimitry Andric       }
47920b57cec5SDimitry Andric     }
47930b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
47940b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
479506c3fb27SDimitry Andric 
479606c3fb27SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_HIP) &&
479706c3fb27SDimitry Andric         getToolChain().getTriple().isAMDGPU()) {
479806c3fb27SDimitry Andric       // Device side compilation printf
479906c3fb27SDimitry Andric       if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
480006c3fb27SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
480106c3fb27SDimitry Andric             "-mprintf-kind=" +
480206c3fb27SDimitry Andric             Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
480306c3fb27SDimitry Andric         // Force compiler error on invalid conversion specifiers
480406c3fb27SDimitry Andric         CmdArgs.push_back(
480506c3fb27SDimitry Andric             Args.MakeArgString("-Werror=format-invalid-specifier"));
48060b57cec5SDimitry Andric       }
480706c3fb27SDimitry Andric     }
480806c3fb27SDimitry Andric   }
480906c3fb27SDimitry Andric 
481006c3fb27SDimitry Andric   // Unconditionally claim the printf option now to avoid unused diagnostic.
481106c3fb27SDimitry Andric   if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
481206c3fb27SDimitry Andric     PF->claim();
48130b57cec5SDimitry Andric 
48145ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
48155ffd83dbSDimitry Andric     CmdArgs.push_back("-fsycl-is-device");
48165ffd83dbSDimitry Andric 
48175ffd83dbSDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
48185ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
48195ffd83dbSDimitry Andric     } else {
4820fe6060f1SDimitry Andric       // Ensure the default version in SYCL mode is 2020.
4821fe6060f1SDimitry Andric       CmdArgs.push_back("-sycl-std=2020");
48225ffd83dbSDimitry Andric     }
48235ffd83dbSDimitry Andric   }
48245ffd83dbSDimitry Andric 
48250b57cec5SDimitry Andric   if (IsOpenMPDevice) {
48260b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for an OpenMP device.
48270b57cec5SDimitry Andric     std::string NormalizedTriple =
48280b57cec5SDimitry Andric         C.getSingleOffloadToolChain<Action::OFK_Host>()
48290b57cec5SDimitry Andric             ->getTriple()
48300b57cec5SDimitry Andric             .normalize();
48310b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
48320b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
48330b57cec5SDimitry Andric   }
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
48360b57cec5SDimitry Andric                                Triple.getArch() == llvm::Triple::thumb)) {
48370b57cec5SDimitry Andric     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
48385ffd83dbSDimitry Andric     unsigned Version = 0;
48395ffd83dbSDimitry Andric     bool Failure =
48405ffd83dbSDimitry Andric         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
48415ffd83dbSDimitry Andric     if (Failure || Version < 7)
48420b57cec5SDimitry Andric       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
48430b57cec5SDimitry Andric                                                 << TripleStr;
48440b57cec5SDimitry Andric   }
48450b57cec5SDimitry Andric 
48460b57cec5SDimitry Andric   // Push all default warning arguments that are specific to
48470b57cec5SDimitry Andric   // the given target.  These come before user provided warning options
48480b57cec5SDimitry Andric   // are provided.
48490b57cec5SDimitry Andric   TC.addClangWarningOptions(CmdArgs);
48500b57cec5SDimitry Andric 
4851fe6060f1SDimitry Andric   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4852bdd1243dSDimitry Andric   if (Triple.isSPIR() || Triple.isSPIRV())
4853fe6060f1SDimitry Andric     CmdArgs.push_back("-Wspir-compat");
4854fe6060f1SDimitry Andric 
48550b57cec5SDimitry Andric   // Select the appropriate action.
48560b57cec5SDimitry Andric   RewriteKind rewriteKind = RK_None;
48570b57cec5SDimitry Andric 
485806c3fb27SDimitry Andric   bool UnifiedLTO = false;
485906c3fb27SDimitry Andric   if (IsUsingLTO) {
486006c3fb27SDimitry Andric     UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
48617a6dacacSDimitry Andric                               options::OPT_fno_unified_lto, Triple.isPS());
486206c3fb27SDimitry Andric     if (UnifiedLTO)
486306c3fb27SDimitry Andric       CmdArgs.push_back("-funified-lto");
486406c3fb27SDimitry Andric   }
486506c3fb27SDimitry Andric 
4866a7dea167SDimitry Andric   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4867a7dea167SDimitry Andric   // it claims when not running an assembler. Otherwise, clang would emit
4868a7dea167SDimitry Andric   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4869a7dea167SDimitry Andric   // flags while debugging something. That'd be somewhat inconvenient, and it's
4870a7dea167SDimitry Andric   // also inconsistent with most other flags -- we don't warn on
4871a7dea167SDimitry Andric   // -ffunction-sections not being used in -E mode either for example, even
4872a7dea167SDimitry Andric   // though it's not really used either.
4873a7dea167SDimitry Andric   if (!isa<AssembleJobAction>(JA)) {
4874a7dea167SDimitry Andric     // The args claimed here should match the args used in
4875a7dea167SDimitry Andric     // CollectArgsForIntegratedAssembler().
4876a7dea167SDimitry Andric     if (TC.useIntegratedAs()) {
4877a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mrelax_all);
4878a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_relax_all);
4879a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4880a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4881a7dea167SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
4882a7dea167SDimitry Andric       case llvm::Triple::arm:
4883a7dea167SDimitry Andric       case llvm::Triple::armeb:
4884a7dea167SDimitry Andric       case llvm::Triple::thumb:
4885a7dea167SDimitry Andric       case llvm::Triple::thumbeb:
4886a7dea167SDimitry Andric         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4887a7dea167SDimitry Andric         break;
4888a7dea167SDimitry Andric       default:
4889a7dea167SDimitry Andric         break;
4890a7dea167SDimitry Andric       }
4891a7dea167SDimitry Andric     }
4892a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4893a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Xassembler);
489481ad6265SDimitry Andric     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4895a7dea167SDimitry Andric   }
4896a7dea167SDimitry Andric 
48970b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA)) {
48980b57cec5SDimitry Andric     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
48990b57cec5SDimitry Andric     CmdArgs.push_back("-analyze");
49000b57cec5SDimitry Andric   } else if (isa<MigrateJobAction>(JA)) {
49010b57cec5SDimitry Andric     CmdArgs.push_back("-migrate");
49020b57cec5SDimitry Andric   } else if (isa<PreprocessJobAction>(JA)) {
49030b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies)
49040b57cec5SDimitry Andric       CmdArgs.push_back("-Eonly");
49050b57cec5SDimitry Andric     else {
49060b57cec5SDimitry Andric       CmdArgs.push_back("-E");
49070b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_rewrite_objc) &&
49080b57cec5SDimitry Andric           !Args.hasArg(options::OPT_g_Group))
49090b57cec5SDimitry Andric         CmdArgs.push_back("-P");
491081ad6265SDimitry Andric       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
491181ad6265SDimitry Andric         CmdArgs.push_back("-fdirectives-only");
49120b57cec5SDimitry Andric     }
49130b57cec5SDimitry Andric   } else if (isa<AssembleJobAction>(JA)) {
49140b57cec5SDimitry Andric     CmdArgs.push_back("-emit-obj");
49150b57cec5SDimitry Andric 
49160b57cec5SDimitry Andric     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric     // Also ignore explicit -force_cpusubtype_ALL option.
49190b57cec5SDimitry Andric     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
49200b57cec5SDimitry Andric   } else if (isa<PrecompileJobAction>(JA)) {
49210b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing)
49220b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
49230b57cec5SDimitry Andric     else if (JA.getType() == types::TY_ModuleFile)
4924bdd1243dSDimitry Andric       CmdArgs.push_back("-emit-module-interface");
492581ad6265SDimitry Andric     else if (JA.getType() == types::TY_HeaderUnit)
492681ad6265SDimitry Andric       CmdArgs.push_back("-emit-header-unit");
49270b57cec5SDimitry Andric     else
49280b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
49290b57cec5SDimitry Andric   } else if (isa<VerifyPCHJobAction>(JA)) {
49300b57cec5SDimitry Andric     CmdArgs.push_back("-verify-pch");
493181ad6265SDimitry Andric   } else if (isa<ExtractAPIJobAction>(JA)) {
493281ad6265SDimitry Andric     assert(JA.getType() == types::TY_API_INFO &&
493381ad6265SDimitry Andric            "Extract API actions must generate a API information.");
493481ad6265SDimitry Andric     CmdArgs.push_back("-extract-api");
493581ad6265SDimitry Andric     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
493681ad6265SDimitry Andric       ProductNameArg->render(Args, CmdArgs);
4937bdd1243dSDimitry Andric     if (Arg *ExtractAPIIgnoresFileArg =
4938bdd1243dSDimitry Andric             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4939bdd1243dSDimitry Andric       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
49400b57cec5SDimitry Andric   } else {
49410b57cec5SDimitry Andric     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
49420b57cec5SDimitry Andric            "Invalid action for clang tool.");
49430b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing) {
49440b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
49450b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_IR ||
49460b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_IR) {
49470b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm");
49480b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_BC ||
49490b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_BC) {
4950fe6060f1SDimitry Andric       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4951fe6060f1SDimitry Andric       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4952fe6060f1SDimitry Andric           Args.hasArg(options::OPT_emit_llvm)) {
4953fe6060f1SDimitry Andric         CmdArgs.push_back("-emit-llvm");
4954fe6060f1SDimitry Andric       } else {
49550b57cec5SDimitry Andric         CmdArgs.push_back("-emit-llvm-bc");
4956fe6060f1SDimitry Andric       }
4957a7dea167SDimitry Andric     } else if (JA.getType() == types::TY_IFS ||
4958a7dea167SDimitry Andric                JA.getType() == types::TY_IFS_CPP) {
4959a7dea167SDimitry Andric       StringRef ArgStr =
4960a7dea167SDimitry Andric           Args.hasArg(options::OPT_interface_stub_version_EQ)
4961a7dea167SDimitry Andric               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4962fe6060f1SDimitry Andric               : "ifs-v1";
49630b57cec5SDimitry Andric       CmdArgs.push_back("-emit-interface-stubs");
49640b57cec5SDimitry Andric       CmdArgs.push_back(
4965a7dea167SDimitry Andric           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
49660b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_PP_Asm) {
49670b57cec5SDimitry Andric       CmdArgs.push_back("-S");
49680b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_AST) {
49690b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
49700b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_ModuleFile) {
49710b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-info");
49720b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenObjC) {
49730b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
49740b57cec5SDimitry Andric       rewriteKind = RK_NonFragile;
49750b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
49760b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
49770b57cec5SDimitry Andric       rewriteKind = RK_Fragile;
49780b57cec5SDimitry Andric     } else {
49790b57cec5SDimitry Andric       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
49800b57cec5SDimitry Andric     }
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric     // Preserve use-list order by default when emitting bitcode, so that
49830b57cec5SDimitry Andric     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
49840b57cec5SDimitry Andric     // same result as running passes here.  For LTO, we don't need to preserve
49850b57cec5SDimitry Andric     // the use-list order, since serialization to bitcode is part of the flow.
49860b57cec5SDimitry Andric     if (JA.getType() == types::TY_LLVM_BC)
49870b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm-uselists");
49880b57cec5SDimitry Andric 
498981ad6265SDimitry Andric     if (IsUsingLTO) {
4990bdd1243dSDimitry Andric       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
499181ad6265SDimitry Andric           !Args.hasFlag(options::OPT_offload_new_driver,
499281ad6265SDimitry Andric                         options::OPT_no_offload_new_driver, false) &&
499381ad6265SDimitry Andric           !Triple.isAMDGPU()) {
4994fe6060f1SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
4995fe6060f1SDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
4996fe6060f1SDimitry Andric                                options::OPT_foffload_lto_EQ)
4997fe6060f1SDimitry Andric                    ->getAsString(Args)
4998fe6060f1SDimitry Andric             << Triple.getTriple();
4999bdd1243dSDimitry Andric       } else if (Triple.isNVPTX() && !IsRDCMode &&
5000bdd1243dSDimitry Andric                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
5001bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5002bdd1243dSDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
5003bdd1243dSDimitry Andric                                options::OPT_foffload_lto_EQ)
5004bdd1243dSDimitry Andric                    ->getAsString(Args)
5005bdd1243dSDimitry Andric             << "-fno-gpu-rdc";
5006349cc55cSDimitry Andric       } else {
5007349cc55cSDimitry Andric         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5008349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
5009349cc55cSDimitry Andric             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
501006c3fb27SDimitry Andric         // PS4 uses the legacy LTO API, which does not support some of the
501106c3fb27SDimitry Andric         // features enabled by -flto-unit.
501206c3fb27SDimitry Andric         if (!RawTriple.isPS4() ||
501306c3fb27SDimitry Andric             (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5014349cc55cSDimitry Andric           CmdArgs.push_back("-flto-unit");
5015fe6060f1SDimitry Andric       }
50160b57cec5SDimitry Andric     }
50170b57cec5SDimitry Andric   }
50180b57cec5SDimitry Andric 
501906c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
502006c3fb27SDimitry Andric 
50210b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
50220b57cec5SDimitry Andric     if (!types::isLLVMIR(Input.getType()))
50230b57cec5SDimitry Andric       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
50240b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
50250b57cec5SDimitry Andric   }
50260b57cec5SDimitry Andric 
50275f757f3fSDimitry Andric   if (Triple.isPPC())
50285f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
50295f757f3fSDimitry Andric                       options::OPT_mno_regnames);
50305f757f3fSDimitry Andric 
5031480093f4SDimitry Andric   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5032480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5033480093f4SDimitry Andric 
50340b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
50350b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
50360b57cec5SDimitry Andric 
5037e8d8bef9SDimitry Andric   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5038e8d8bef9SDimitry Andric                                      options::OPT_fmemory_profile_EQ,
5039e8d8bef9SDimitry Andric                                      options::OPT_fno_memory_profile);
5040e8d8bef9SDimitry Andric   if (MemProfArg &&
5041e8d8bef9SDimitry Andric       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5042e8d8bef9SDimitry Andric     MemProfArg->render(Args, CmdArgs);
5043e8d8bef9SDimitry Andric 
504406c3fb27SDimitry Andric   if (auto *MemProfUseArg =
504506c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
504606c3fb27SDimitry Andric     if (MemProfArg)
504706c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
504806c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
504906c3fb27SDimitry Andric     if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
505006c3fb27SDimitry Andric                                             options::OPT_fprofile_generate_EQ))
505106c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
505206c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
505306c3fb27SDimitry Andric     MemProfUseArg->render(Args, CmdArgs);
505406c3fb27SDimitry Andric   }
505506c3fb27SDimitry Andric 
50560b57cec5SDimitry Andric   // Embed-bitcode option.
50570b57cec5SDimitry Andric   // Only white-listed flags below are allowed to be embedded.
5058fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
50590b57cec5SDimitry Andric       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
50600b57cec5SDimitry Andric     // Add flags implied by -fembed-bitcode.
50610b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
50620b57cec5SDimitry Andric     // Disable all llvm IR level optimizations.
50630b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
50640b57cec5SDimitry Andric 
5065480093f4SDimitry Andric     // Render target options.
50660b57cec5SDimitry Andric     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
50670b57cec5SDimitry Andric 
50680b57cec5SDimitry Andric     // reject options that shouldn't be supported in bitcode
50690b57cec5SDimitry Andric     // also reject kernel/kext
5070349cc55cSDimitry Andric     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
50710b57cec5SDimitry Andric         options::OPT_mkernel,
50720b57cec5SDimitry Andric         options::OPT_fapple_kext,
50730b57cec5SDimitry Andric         options::OPT_ffunction_sections,
50740b57cec5SDimitry Andric         options::OPT_fno_function_sections,
50750b57cec5SDimitry Andric         options::OPT_fdata_sections,
50760b57cec5SDimitry Andric         options::OPT_fno_data_sections,
50775ffd83dbSDimitry Andric         options::OPT_fbasic_block_sections_EQ,
50785ffd83dbSDimitry Andric         options::OPT_funique_internal_linkage_names,
50795ffd83dbSDimitry Andric         options::OPT_fno_unique_internal_linkage_names,
50800b57cec5SDimitry Andric         options::OPT_funique_section_names,
50810b57cec5SDimitry Andric         options::OPT_fno_unique_section_names,
50825ffd83dbSDimitry Andric         options::OPT_funique_basic_block_section_names,
50835ffd83dbSDimitry Andric         options::OPT_fno_unique_basic_block_section_names,
50840b57cec5SDimitry Andric         options::OPT_mrestrict_it,
50850b57cec5SDimitry Andric         options::OPT_mno_restrict_it,
50860b57cec5SDimitry Andric         options::OPT_mstackrealign,
50870b57cec5SDimitry Andric         options::OPT_mno_stackrealign,
50880b57cec5SDimitry Andric         options::OPT_mstack_alignment,
50890b57cec5SDimitry Andric         options::OPT_mcmodel_EQ,
50900b57cec5SDimitry Andric         options::OPT_mlong_calls,
50910b57cec5SDimitry Andric         options::OPT_mno_long_calls,
50920b57cec5SDimitry Andric         options::OPT_ggnu_pubnames,
50930b57cec5SDimitry Andric         options::OPT_gdwarf_aranges,
50940b57cec5SDimitry Andric         options::OPT_fdebug_types_section,
50950b57cec5SDimitry Andric         options::OPT_fno_debug_types_section,
50960b57cec5SDimitry Andric         options::OPT_fdwarf_directory_asm,
50970b57cec5SDimitry Andric         options::OPT_fno_dwarf_directory_asm,
50980b57cec5SDimitry Andric         options::OPT_mrelax_all,
50990b57cec5SDimitry Andric         options::OPT_mno_relax_all,
51000b57cec5SDimitry Andric         options::OPT_ftrap_function_EQ,
51010b57cec5SDimitry Andric         options::OPT_ffixed_r9,
51020b57cec5SDimitry Andric         options::OPT_mfix_cortex_a53_835769,
51030b57cec5SDimitry Andric         options::OPT_mno_fix_cortex_a53_835769,
51040b57cec5SDimitry Andric         options::OPT_ffixed_x18,
51050b57cec5SDimitry Andric         options::OPT_mglobal_merge,
51060b57cec5SDimitry Andric         options::OPT_mno_global_merge,
51070b57cec5SDimitry Andric         options::OPT_mred_zone,
51080b57cec5SDimitry Andric         options::OPT_mno_red_zone,
51090b57cec5SDimitry Andric         options::OPT_Wa_COMMA,
51100b57cec5SDimitry Andric         options::OPT_Xassembler,
51110b57cec5SDimitry Andric         options::OPT_mllvm,
51120b57cec5SDimitry Andric     };
51130b57cec5SDimitry Andric     for (const auto &A : Args)
5114349cc55cSDimitry Andric       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
51150b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric     // Render the CodeGen options that need to be passed.
511881ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
511981ad6265SDimitry Andric                        options::OPT_fno_optimize_sibling_calls);
51200b57cec5SDimitry Andric 
51210b57cec5SDimitry Andric     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
51225ffd83dbSDimitry Andric                                CmdArgs, JA);
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric     // Render ABI arguments
51250b57cec5SDimitry Andric     switch (TC.getArch()) {
51260b57cec5SDimitry Andric     default: break;
51270b57cec5SDimitry Andric     case llvm::Triple::arm:
51280b57cec5SDimitry Andric     case llvm::Triple::armeb:
51290b57cec5SDimitry Andric     case llvm::Triple::thumbeb:
5130349cc55cSDimitry Andric       RenderARMABI(D, Triple, Args, CmdArgs);
51310b57cec5SDimitry Andric       break;
51320b57cec5SDimitry Andric     case llvm::Triple::aarch64:
5133480093f4SDimitry Andric     case llvm::Triple::aarch64_32:
51340b57cec5SDimitry Andric     case llvm::Triple::aarch64_be:
51350b57cec5SDimitry Andric       RenderAArch64ABI(Triple, Args, CmdArgs);
51360b57cec5SDimitry Andric       break;
51370b57cec5SDimitry Andric     }
51380b57cec5SDimitry Andric 
51390b57cec5SDimitry Andric     // Optimization level for CodeGen.
51400b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
51410b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_O4)) {
51420b57cec5SDimitry Andric         CmdArgs.push_back("-O3");
51430b57cec5SDimitry Andric         D.Diag(diag::warn_O4_is_O3);
51440b57cec5SDimitry Andric       } else {
51450b57cec5SDimitry Andric         A->render(Args, CmdArgs);
51460b57cec5SDimitry Andric       }
51470b57cec5SDimitry Andric     }
51480b57cec5SDimitry Andric 
51490b57cec5SDimitry Andric     // Input/Output file.
51500b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies) {
51510b57cec5SDimitry Andric       // Handled with other dependency code.
51520b57cec5SDimitry Andric     } else if (Output.isFilename()) {
51530b57cec5SDimitry Andric       CmdArgs.push_back("-o");
51540b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
51550b57cec5SDimitry Andric     } else {
51560b57cec5SDimitry Andric       assert(Output.isNothing() && "Input output.");
51570b57cec5SDimitry Andric     }
51580b57cec5SDimitry Andric 
51590b57cec5SDimitry Andric     for (const auto &II : Inputs) {
51600b57cec5SDimitry Andric       addDashXForInput(Args, II, CmdArgs);
51610b57cec5SDimitry Andric       if (II.isFilename())
51620b57cec5SDimitry Andric         CmdArgs.push_back(II.getFilename());
51630b57cec5SDimitry Andric       else
51640b57cec5SDimitry Andric         II.getInputArg().renderAsInput(Args, CmdArgs);
51650b57cec5SDimitry Andric     }
51660b57cec5SDimitry Andric 
5167e8d8bef9SDimitry Andric     C.addCommand(std::make_unique<Command>(
5168e8d8bef9SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
516906c3fb27SDimitry Andric         CmdArgs, Inputs, Output, D.getPrependArg()));
51700b57cec5SDimitry Andric     return;
51710b57cec5SDimitry Andric   }
51720b57cec5SDimitry Andric 
5173fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
51740b57cec5SDimitry Andric     CmdArgs.push_back("-fembed-bitcode=marker");
51750b57cec5SDimitry Andric 
51760b57cec5SDimitry Andric   // We normally speed up the clang process a bit by skipping destructors at
51770b57cec5SDimitry Andric   // exit, but when we're generating diagnostics we can rely on some of the
51780b57cec5SDimitry Andric   // cleanup.
51790b57cec5SDimitry Andric   if (!C.isForDiagnostics())
51800b57cec5SDimitry Andric     CmdArgs.push_back("-disable-free");
5181349cc55cSDimitry Andric   CmdArgs.push_back("-clear-ast-before-backend");
51820b57cec5SDimitry Andric 
51830b57cec5SDimitry Andric #ifdef NDEBUG
51840b57cec5SDimitry Andric   const bool IsAssertBuild = false;
51850b57cec5SDimitry Andric #else
51860b57cec5SDimitry Andric   const bool IsAssertBuild = true;
51870b57cec5SDimitry Andric #endif
51880b57cec5SDimitry Andric 
51895f757f3fSDimitry Andric   // Disable the verification pass in asserts builds unless otherwise specified.
51905f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
51915f757f3fSDimitry Andric                    options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
51920b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-verifier");
51935f757f3fSDimitry Andric   }
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric   // Discard value names in assert builds unless otherwise specified.
51960b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdiscard_value_names,
519747395794SDimitry Andric                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
519847395794SDimitry Andric     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5199349cc55cSDimitry Andric         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
520047395794SDimitry Andric           return types::isLLVMIR(II.getType());
5201349cc55cSDimitry Andric         })) {
520247395794SDimitry Andric       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
520347395794SDimitry Andric     }
52040b57cec5SDimitry Andric     CmdArgs.push_back("-discard-value-names");
520547395794SDimitry Andric   }
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
52080b57cec5SDimitry Andric   // -save-temps.
52090b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
52100b57cec5SDimitry Andric   CmdArgs.push_back(getBaseInputName(Args, Input));
52110b57cec5SDimitry Andric 
52120b57cec5SDimitry Andric   // Some flags which affect the language (via preprocessor
52130b57cec5SDimitry Andric   // defines).
52140b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
52150b57cec5SDimitry Andric     CmdArgs.push_back("-static-define");
52160b57cec5SDimitry Andric 
52170b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_municode))
52180b57cec5SDimitry Andric     CmdArgs.push_back("-DUNICODE");
52190b57cec5SDimitry Andric 
52200b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA))
52210b57cec5SDimitry Andric     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
52220b57cec5SDimitry Andric 
5223a7dea167SDimitry Andric   if (isa<AnalyzeJobAction>(JA) ||
5224a7dea167SDimitry Andric       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5225a7dea167SDimitry Andric     CmdArgs.push_back("-setup-static-analyzer");
5226a7dea167SDimitry Andric 
52270b57cec5SDimitry Andric   // Enable compatilibily mode to avoid analyzer-config related errors.
52280b57cec5SDimitry Andric   // Since we can't access frontend flags through hasArg, let's manually iterate
52290b57cec5SDimitry Andric   // through them.
52300b57cec5SDimitry Andric   bool FoundAnalyzerConfig = false;
5231bdd1243dSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
52320b57cec5SDimitry Andric     if (StringRef(Arg->getValue()) == "-analyzer-config") {
52330b57cec5SDimitry Andric       FoundAnalyzerConfig = true;
52340b57cec5SDimitry Andric       break;
52350b57cec5SDimitry Andric     }
52360b57cec5SDimitry Andric   if (!FoundAnalyzerConfig)
5237bdd1243dSDimitry Andric     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
52380b57cec5SDimitry Andric       if (StringRef(Arg->getValue()) == "-analyzer-config") {
52390b57cec5SDimitry Andric         FoundAnalyzerConfig = true;
52400b57cec5SDimitry Andric         break;
52410b57cec5SDimitry Andric       }
52420b57cec5SDimitry Andric   if (FoundAnalyzerConfig)
52430b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
52440b57cec5SDimitry Andric 
52450b57cec5SDimitry Andric   CheckCodeGenerationOptions(D, Args);
52460b57cec5SDimitry Andric 
52470b57cec5SDimitry Andric   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
52480b57cec5SDimitry Andric   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
52490b57cec5SDimitry Andric   if (FunctionAlignment) {
52500b57cec5SDimitry Andric     CmdArgs.push_back("-function-alignment");
52510b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
52520b57cec5SDimitry Andric   }
52530b57cec5SDimitry Andric 
5254349cc55cSDimitry Andric   // We support -falign-loops=N where N is a power of 2. GCC supports more
5255349cc55cSDimitry Andric   // forms.
5256349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5257349cc55cSDimitry Andric     unsigned Value = 0;
5258349cc55cSDimitry Andric     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5259349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5260349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5261349cc55cSDimitry Andric     else if (Value & (Value - 1))
5262349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5263349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5264349cc55cSDimitry Andric     // Treat =0 as unspecified (use the target preference).
5265349cc55cSDimitry Andric     if (Value)
5266349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5267349cc55cSDimitry Andric                                            Twine(std::min(Value, 65536u))));
5268349cc55cSDimitry Andric   }
5269349cc55cSDimitry Andric 
527006c3fb27SDimitry Andric   if (Triple.isOSzOS()) {
527106c3fb27SDimitry Andric     // On z/OS some of the system header feature macros need to
527206c3fb27SDimitry Andric     // be defined to enable most cross platform projects to build
527306c3fb27SDimitry Andric     // successfully.  Ths include the libc++ library.  A
527406c3fb27SDimitry Andric     // complicating factor is that users can define these
527506c3fb27SDimitry Andric     // macros to the same or different values.  We need to add
527606c3fb27SDimitry Andric     // the definition for these macros to the compilation command
527706c3fb27SDimitry Andric     // if the user hasn't already defined them.
527806c3fb27SDimitry Andric 
527906c3fb27SDimitry Andric     auto findMacroDefinition = [&](const std::string &Macro) {
528006c3fb27SDimitry Andric       auto MacroDefs = Args.getAllArgValues(options::OPT_D);
52815f757f3fSDimitry Andric       return llvm::any_of(MacroDefs, [&](const std::string &M) {
52825f757f3fSDimitry Andric         return M == Macro || M.find(Macro + '=') != std::string::npos;
52835f757f3fSDimitry Andric       });
528406c3fb27SDimitry Andric     };
528506c3fb27SDimitry Andric 
528606c3fb27SDimitry Andric     // _UNIX03_WITHDRAWN is required for libcxx & porting.
528706c3fb27SDimitry Andric     if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
528806c3fb27SDimitry Andric       CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
528906c3fb27SDimitry Andric     // _OPEN_DEFAULT is required for XL compat
529006c3fb27SDimitry Andric     if (!findMacroDefinition("_OPEN_DEFAULT"))
529106c3fb27SDimitry Andric       CmdArgs.push_back("-D_OPEN_DEFAULT");
529206c3fb27SDimitry Andric     if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
529306c3fb27SDimitry Andric       // _XOPEN_SOURCE=600 is required for libcxx.
529406c3fb27SDimitry Andric       if (!findMacroDefinition("_XOPEN_SOURCE"))
529506c3fb27SDimitry Andric         CmdArgs.push_back("-D_XOPEN_SOURCE=600");
529606c3fb27SDimitry Andric     }
529706c3fb27SDimitry Andric   }
529806c3fb27SDimitry Andric 
52990b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
53000b57cec5SDimitry Andric   unsigned PICLevel;
53010b57cec5SDimitry Andric   bool IsPIE;
53020b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5303bdd1243dSDimitry Andric   Arg *LastPICDataRelArg =
5304bdd1243dSDimitry Andric       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5305bdd1243dSDimitry Andric                       options::OPT_mpic_data_is_text_relative);
5306bdd1243dSDimitry Andric   bool NoPICDataIsTextRelative = false;
5307bdd1243dSDimitry Andric   if (LastPICDataRelArg) {
5308bdd1243dSDimitry Andric     if (LastPICDataRelArg->getOption().matches(
5309bdd1243dSDimitry Andric             options::OPT_mno_pic_data_is_text_relative)) {
5310bdd1243dSDimitry Andric       NoPICDataIsTextRelative = true;
5311bdd1243dSDimitry Andric       if (!PICLevel)
5312bdd1243dSDimitry Andric         D.Diag(diag::err_drv_argument_only_allowed_with)
5313bdd1243dSDimitry Andric             << "-mno-pic-data-is-text-relative"
5314bdd1243dSDimitry Andric             << "-fpic/-fpie";
5315bdd1243dSDimitry Andric     }
5316bdd1243dSDimitry Andric     if (!Triple.isSystemZ())
5317bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5318bdd1243dSDimitry Andric           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5319bdd1243dSDimitry Andric                                       : "-mpic-data-is-text-relative")
5320bdd1243dSDimitry Andric           << RawTriple.str();
5321bdd1243dSDimitry Andric   }
53220b57cec5SDimitry Andric 
53235ffd83dbSDimitry Andric   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
53245ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
53255ffd83dbSDimitry Andric   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
53265ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
53270b57cec5SDimitry Andric 
53285ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_mcmse) &&
53295ffd83dbSDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported)) {
53305ffd83dbSDimitry Andric     if (IsROPI)
53315ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
53325ffd83dbSDimitry Andric     if (IsRWPI)
53335ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
53345ffd83dbSDimitry Andric   }
53355ffd83dbSDimitry Andric 
53365ffd83dbSDimitry Andric   if (IsROPI && types::isCXX(Input.getType()) &&
53370b57cec5SDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported))
53380b57cec5SDimitry Andric     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
53390b57cec5SDimitry Andric 
53405ffd83dbSDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
53410b57cec5SDimitry Andric   if (RMName) {
53420b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
53430b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
53440b57cec5SDimitry Andric   }
53450b57cec5SDimitry Andric   if (PICLevel > 0) {
53460b57cec5SDimitry Andric     CmdArgs.push_back("-pic-level");
53470b57cec5SDimitry Andric     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
53480b57cec5SDimitry Andric     if (IsPIE)
53490b57cec5SDimitry Andric       CmdArgs.push_back("-pic-is-pie");
5350bdd1243dSDimitry Andric     if (NoPICDataIsTextRelative)
5351bdd1243dSDimitry Andric       CmdArgs.push_back("-mcmodel=medium");
53520b57cec5SDimitry Andric   }
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::ROPI ||
53550b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
53560b57cec5SDimitry Andric     CmdArgs.push_back("-fropi");
53570b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::RWPI ||
53580b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
53590b57cec5SDimitry Andric     CmdArgs.push_back("-frwpi");
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
53620b57cec5SDimitry Andric     CmdArgs.push_back("-meabi");
53630b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
53640b57cec5SDimitry Andric   }
53650b57cec5SDimitry Andric 
5366e8d8bef9SDimitry Andric   // -fsemantic-interposition is forwarded to CC1: set the
5367e8d8bef9SDimitry Andric   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5368e8d8bef9SDimitry Andric   // make default visibility external linkage definitions dso_preemptable.
5369e8d8bef9SDimitry Andric   //
5370e8d8bef9SDimitry Andric   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5371e8d8bef9SDimitry Andric   // aliases (make default visibility external linkage definitions dso_local).
5372e8d8bef9SDimitry Andric   // This is the CC1 default for ELF to match COFF/Mach-O.
5373e8d8bef9SDimitry Andric   //
5374e8d8bef9SDimitry Andric   // Otherwise use Clang's traditional behavior: like
5375e8d8bef9SDimitry Andric   // -fno-semantic-interposition but local aliases are not used. So references
5376e8d8bef9SDimitry Andric   // can be interposed if not optimized out.
5377e8d8bef9SDimitry Andric   if (Triple.isOSBinFormatELF()) {
5378e8d8bef9SDimitry Andric     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5379e8d8bef9SDimitry Andric                              options::OPT_fno_semantic_interposition);
5380e8d8bef9SDimitry Andric     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5381e8d8bef9SDimitry Andric       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5382fe6060f1SDimitry Andric       bool SupportsLocalAlias =
5383fe6060f1SDimitry Andric           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5384e8d8bef9SDimitry Andric       if (!A)
5385e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5386e8d8bef9SDimitry Andric       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
53875ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
5388e8d8bef9SDimitry Andric       else if (!SupportsLocalAlias)
5389e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5390e8d8bef9SDimitry Andric     }
5391e8d8bef9SDimitry Andric   }
53925ffd83dbSDimitry Andric 
53935ffd83dbSDimitry Andric   {
53945ffd83dbSDimitry Andric     std::string Model;
53950b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
53960b57cec5SDimitry Andric       if (!TC.isThreadModelSupported(A->getValue()))
53970b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_thread_model_for_target)
53980b57cec5SDimitry Andric             << A->getValue() << A->getAsString(Args);
53995ffd83dbSDimitry Andric       Model = A->getValue();
54005ffd83dbSDimitry Andric     } else
54015ffd83dbSDimitry Andric       Model = TC.getThreadModel();
54025ffd83dbSDimitry Andric     if (Model != "posix") {
54035ffd83dbSDimitry Andric       CmdArgs.push_back("-mthread-model");
54045ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Model));
54050b57cec5SDimitry Andric     }
54065ffd83dbSDimitry Andric   }
54070b57cec5SDimitry Andric 
5408bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5409bdd1243dSDimitry Andric     StringRef Name = A->getValue();
5410bdd1243dSDimitry Andric     if (Name == "SVML") {
5411bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5412bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5413bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5414bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5415bdd1243dSDimitry Andric     } else if (Name == "LIBMVEC-X86") {
5416bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5417bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5418bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5419bdd1243dSDimitry Andric             << Name << Triple.getArchName();
542006c3fb27SDimitry Andric     } else if (Name == "SLEEF" || Name == "ArmPL") {
5421bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::aarch64 &&
5422bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::aarch64_be)
5423bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5424bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5425bdd1243dSDimitry Andric     }
5426bdd1243dSDimitry Andric     A->render(Args, CmdArgs);
5427bdd1243dSDimitry Andric   }
54280b57cec5SDimitry Andric 
54290b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmerge_all_constants,
54300b57cec5SDimitry Andric                    options::OPT_fno_merge_all_constants, false))
54310b57cec5SDimitry Andric     CmdArgs.push_back("-fmerge-all-constants");
54320b57cec5SDimitry Andric 
5433bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5434bdd1243dSDimitry Andric                      options::OPT_fno_delete_null_pointer_checks);
54350b57cec5SDimitry Andric 
54360b57cec5SDimitry Andric   // LLVM Code Generator Options.
54370b57cec5SDimitry Andric 
5438972a253aSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5439972a253aSDimitry Andric     if (!Triple.isOSAIX() || Triple.isPPC32())
5440972a253aSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5441972a253aSDimitry Andric         << A->getSpelling() << RawTriple.str();
5442972a253aSDimitry Andric     CmdArgs.push_back("-mabi=quadword-atomics");
5443972a253aSDimitry Andric   }
5444972a253aSDimitry Andric 
5445fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5446fe6060f1SDimitry Andric     // Emit the unsupported option error until the Clang's library integration
5447fe6060f1SDimitry Andric     // support for 128-bit long double is available for AIX.
5448fe6060f1SDimitry Andric     if (Triple.isOSAIX())
5449fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5450fe6060f1SDimitry Andric           << A->getSpelling() << RawTriple.str();
5451e8d8bef9SDimitry Andric   }
5452e8d8bef9SDimitry Andric 
54530b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
545406c3fb27SDimitry Andric     StringRef V = A->getValue(), V1 = V;
545506c3fb27SDimitry Andric     unsigned Size;
545606c3fb27SDimitry Andric     if (V1.consumeInteger(10, Size) || !V1.empty())
545706c3fb27SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
545806c3fb27SDimitry Andric           << V << A->getOption().getName();
5459fe6060f1SDimitry Andric     else
546006c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
54610b57cec5SDimitry Andric   }
54620b57cec5SDimitry Andric 
546381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
546481ad6265SDimitry Andric                      options::OPT_fno_jump_tables);
546581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
546681ad6265SDimitry Andric                     options::OPT_fno_profile_sample_accurate);
546781ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
546881ad6265SDimitry Andric                      options::OPT_fno_preserve_as_comments);
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
54710b57cec5SDimitry Andric     CmdArgs.push_back("-mregparm");
54720b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
54730b57cec5SDimitry Andric   }
54740b57cec5SDimitry Andric 
5475e86cf8adSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5476e86cf8adSDimitry Andric                                options::OPT_msvr4_struct_return)) {
5477e8d8bef9SDimitry Andric     if (!TC.getTriple().isPPC32()) {
5478e86cf8adSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5479e86cf8adSDimitry Andric           << A->getSpelling() << RawTriple.str();
5480e86cf8adSDimitry Andric     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5481e86cf8adSDimitry Andric       CmdArgs.push_back("-maix-struct-return");
5482e86cf8adSDimitry Andric     } else {
5483e86cf8adSDimitry Andric       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5484e86cf8adSDimitry Andric       CmdArgs.push_back("-msvr4-struct-return");
5485e86cf8adSDimitry Andric     }
5486e86cf8adSDimitry Andric   }
5487e86cf8adSDimitry Andric 
54880b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
54890b57cec5SDimitry Andric                                options::OPT_freg_struct_return)) {
54900b57cec5SDimitry Andric     if (TC.getArch() != llvm::Triple::x86) {
54910b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
54920b57cec5SDimitry Andric           << A->getSpelling() << RawTriple.str();
54930b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
54940b57cec5SDimitry Andric       CmdArgs.push_back("-fpcc-struct-return");
54950b57cec5SDimitry Andric     } else {
54960b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_freg_struct_return));
54970b57cec5SDimitry Andric       CmdArgs.push_back("-freg-struct-return");
54980b57cec5SDimitry Andric     }
54990b57cec5SDimitry Andric   }
55000b57cec5SDimitry Andric 
55015f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
55025f757f3fSDimitry Andric     if (Triple.getArch() == llvm::Triple::m68k)
55035f757f3fSDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
55045f757f3fSDimitry Andric     else
55050b57cec5SDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=stdcall");
55065f757f3fSDimitry Andric   }
55070b57cec5SDimitry Andric 
55085ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_fenable_matrix)) {
55095ffd83dbSDimitry Andric     // enable-matrix is needed by both the LangOpts and by LLVM.
55105ffd83dbSDimitry Andric     CmdArgs.push_back("-fenable-matrix");
55115ffd83dbSDimitry Andric     CmdArgs.push_back("-mllvm");
55125ffd83dbSDimitry Andric     CmdArgs.push_back("-enable-matrix");
55135ffd83dbSDimitry Andric   }
55145ffd83dbSDimitry Andric 
5515a7dea167SDimitry Andric   CodeGenOptions::FramePointerKind FPKeepKind =
5516a7dea167SDimitry Andric                   getFramePointerKind(Args, RawTriple);
5517a7dea167SDimitry Andric   const char *FPKeepKindStr = nullptr;
5518a7dea167SDimitry Andric   switch (FPKeepKind) {
5519a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
5520a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=none";
5521a7dea167SDimitry Andric     break;
5522a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
5523a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=non-leaf";
5524a7dea167SDimitry Andric     break;
5525a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
5526a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=all";
5527a7dea167SDimitry Andric     break;
5528a7dea167SDimitry Andric   }
5529a7dea167SDimitry Andric   assert(FPKeepKindStr && "unknown FramePointerKind");
5530a7dea167SDimitry Andric   CmdArgs.push_back(FPKeepKindStr);
5531a7dea167SDimitry Andric 
553281ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
553381ad6265SDimitry Andric                      options::OPT_fno_zero_initialized_in_bss);
55340b57cec5SDimitry Andric 
55350b57cec5SDimitry Andric   bool OFastEnabled = isOptimizationLevelFast(Args);
55360b57cec5SDimitry Andric   // If -Ofast is the optimization level, then -fstrict-aliasing should be
55370b57cec5SDimitry Andric   // enabled.  This alias option is being used to simplify the hasFlag logic.
55380b57cec5SDimitry Andric   OptSpecifier StrictAliasingAliasOption =
55390b57cec5SDimitry Andric       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
55400b57cec5SDimitry Andric   // We turn strict aliasing off by default if we're in CL mode, since MSVC
55410b57cec5SDimitry Andric   // doesn't do any TBAA.
55420b57cec5SDimitry Andric   bool TBAAOnByDefault = !D.IsCLMode();
55430b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
55440b57cec5SDimitry Andric                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
55450b57cec5SDimitry Andric     CmdArgs.push_back("-relaxed-aliasing");
55460b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
554781ad6265SDimitry Andric                     options::OPT_fno_struct_path_tbaa, true))
55480b57cec5SDimitry Andric     CmdArgs.push_back("-no-struct-path-tbaa");
554981ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
555081ad6265SDimitry Andric                     options::OPT_fno_strict_enums);
555181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
555281ad6265SDimitry Andric                      options::OPT_fno_strict_return);
555381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
555481ad6265SDimitry Andric                     options::OPT_fno_allow_editor_placeholders);
555581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
555681ad6265SDimitry Andric                     options::OPT_fno_strict_vtable_pointers);
555781ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
555881ad6265SDimitry Andric                     options::OPT_fno_force_emit_vtables);
555981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
556081ad6265SDimitry Andric                      options::OPT_fno_optimize_sibling_calls);
556181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
556281ad6265SDimitry Andric                      options::OPT_fno_escaping_block_tail_calls);
55630b57cec5SDimitry Andric 
55640b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
55650b57cec5SDimitry Andric                   options::OPT_fno_fine_grained_bitfield_accesses);
55660b57cec5SDimitry Andric 
5567fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5568fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5569fe6060f1SDimitry Andric 
55705f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
55715f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
55725f757f3fSDimitry Andric 
55730b57cec5SDimitry Andric   // Handle segmented stacks.
5574bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5575bdd1243dSDimitry Andric                     options::OPT_fno_split_stack);
5576fe6060f1SDimitry Andric 
5577fe6060f1SDimitry Andric   // -fprotect-parens=0 is default.
5578fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fprotect_parens,
5579fe6060f1SDimitry Andric                    options::OPT_fno_protect_parens, false))
5580fe6060f1SDimitry Andric     CmdArgs.push_back("-fprotect-parens");
55810b57cec5SDimitry Andric 
55825ffd83dbSDimitry Andric   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
55835ffd83dbSDimitry Andric 
5584fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5585fe6060f1SDimitry Andric     const llvm::Triple::ArchType Arch = TC.getArch();
5586fe6060f1SDimitry Andric     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5587fe6060f1SDimitry Andric       StringRef V = A->getValue();
5588fe6060f1SDimitry Andric       if (V == "64")
5589fe6060f1SDimitry Andric         CmdArgs.push_back("-fextend-arguments=64");
5590fe6060f1SDimitry Andric       else if (V != "32")
5591fe6060f1SDimitry Andric         D.Diag(diag::err_drv_invalid_argument_to_option)
5592fe6060f1SDimitry Andric             << A->getValue() << A->getOption().getName();
5593fe6060f1SDimitry Andric     } else
5594fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5595fe6060f1SDimitry Andric           << A->getOption().getName() << TripleStr;
5596fe6060f1SDimitry Andric   }
5597fe6060f1SDimitry Andric 
55985ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
55995ffd83dbSDimitry Andric     if (TC.getArch() == llvm::Triple::avr)
56005ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
56015ffd83dbSDimitry Andric     else
56025ffd83dbSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
56035ffd83dbSDimitry Andric           << A->getAsString(Args) << TripleStr;
56045ffd83dbSDimitry Andric   }
56050b57cec5SDimitry Andric 
5606a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5607480093f4SDimitry Andric     if (TC.getTriple().isX86())
5608a7dea167SDimitry Andric       A->render(Args, CmdArgs);
5609e8d8bef9SDimitry Andric     else if (TC.getTriple().isPPC() &&
5610a7dea167SDimitry Andric              (A->getOption().getID() != options::OPT_mlong_double_80))
56110b57cec5SDimitry Andric       A->render(Args, CmdArgs);
56120b57cec5SDimitry Andric     else
56130b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
56140b57cec5SDimitry Andric           << A->getAsString(Args) << TripleStr;
56150b57cec5SDimitry Andric   }
56160b57cec5SDimitry Andric 
56170b57cec5SDimitry Andric   // Decide whether to use verbose asm. Verbose assembly is the default on
56180b57cec5SDimitry Andric   // toolchains which have the integrated assembler on by default.
56190b57cec5SDimitry Andric   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
56205ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5621a7dea167SDimitry Andric                     IsIntegratedAssemblerDefault))
56225ffd83dbSDimitry Andric     CmdArgs.push_back("-fno-verbose-asm");
56230b57cec5SDimitry Andric 
5624e8d8bef9SDimitry Andric   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5625e8d8bef9SDimitry Andric   // use that to indicate the MC default in the backend.
5626e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5627e8d8bef9SDimitry Andric     StringRef V = A->getValue();
5628e8d8bef9SDimitry Andric     unsigned Num;
5629e8d8bef9SDimitry Andric     if (V == "none")
5630e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5631e8d8bef9SDimitry Andric     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5632e8d8bef9SDimitry Andric              (V.empty() || (V.consume_front(".") &&
5633e8d8bef9SDimitry Andric                             !V.consumeInteger(10, Num) && V.empty())))
5634e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5635e8d8bef9SDimitry Andric     else
5636e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
5637e8d8bef9SDimitry Andric           << A->getValue() << A->getOption().getName();
5638e8d8bef9SDimitry Andric   }
5639e8d8bef9SDimitry Andric 
5640fe6060f1SDimitry Andric   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5641fe6060f1SDimitry Andric   // option to disable integrated-as explictly.
5642fe6060f1SDimitry Andric   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
56430b57cec5SDimitry Andric     CmdArgs.push_back("-no-integrated-as");
56440b57cec5SDimitry Andric 
56450b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
56460b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
56470b57cec5SDimitry Andric     CmdArgs.push_back("Structure");
56480b57cec5SDimitry Andric   }
56490b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
56500b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
56510b57cec5SDimitry Andric     CmdArgs.push_back("Arguments");
56520b57cec5SDimitry Andric   }
56530b57cec5SDimitry Andric 
56540b57cec5SDimitry Andric   // Enable -mconstructor-aliases except on darwin, where we have to work around
56555f757f3fSDimitry Andric   // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
56565f757f3fSDimitry Andric   // code, where aliases aren't supported.
5657349cc55cSDimitry Andric   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
56580b57cec5SDimitry Andric     CmdArgs.push_back("-mconstructor-aliases");
56590b57cec5SDimitry Andric 
56600b57cec5SDimitry Andric   // Darwin's kernel doesn't support guard variables; just die if we
56610b57cec5SDimitry Andric   // try to use them.
56620b57cec5SDimitry Andric   if (KernelOrKext && RawTriple.isOSDarwin())
56630b57cec5SDimitry Andric     CmdArgs.push_back("-fforbid-guard-variables");
56640b57cec5SDimitry Andric 
56650b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
56665ffd83dbSDimitry Andric                    Triple.isWindowsGNUEnvironment())) {
56670b57cec5SDimitry Andric     CmdArgs.push_back("-mms-bitfields");
56680b57cec5SDimitry Andric   }
56690b57cec5SDimitry Andric 
56705f757f3fSDimitry Andric   if (Triple.isWindowsGNUEnvironment()) {
56715f757f3fSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
56725f757f3fSDimitry Andric                        options::OPT_fno_auto_import);
56735f757f3fSDimitry Andric   }
56745f757f3fSDimitry Andric 
56755f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
56765f757f3fSDimitry Andric                    Triple.isX86() && D.IsCLMode()))
56775f757f3fSDimitry Andric     CmdArgs.push_back("-fms-volatile");
56785f757f3fSDimitry Andric 
5679e8d8bef9SDimitry Andric   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5680e8d8bef9SDimitry Andric   // defaults to -fno-direct-access-external-data. Pass the option if different
5681e8d8bef9SDimitry Andric   // from the default.
5682e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
56835f757f3fSDimitry Andric                                options::OPT_fno_direct_access_external_data)) {
5684e8d8bef9SDimitry Andric     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5685e8d8bef9SDimitry Andric         (PICLevel == 0))
5686e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
56875f757f3fSDimitry Andric   } else if (PICLevel == 0 && Triple.isLoongArch()) {
56885f757f3fSDimitry Andric     // Some targets default to -fno-direct-access-external-data even for
56895f757f3fSDimitry Andric     // -fno-pic.
56905f757f3fSDimitry Andric     CmdArgs.push_back("-fno-direct-access-external-data");
56915f757f3fSDimitry Andric   }
56920b57cec5SDimitry Andric 
56930b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
56940b57cec5SDimitry Andric     CmdArgs.push_back("-fno-plt");
56950b57cec5SDimitry Andric   }
56960b57cec5SDimitry Andric 
56970b57cec5SDimitry Andric   // -fhosted is default.
56980b57cec5SDimitry Andric   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
56990b57cec5SDimitry Andric   // use Freestanding.
57000b57cec5SDimitry Andric   bool Freestanding =
57010b57cec5SDimitry Andric       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
57020b57cec5SDimitry Andric       KernelOrKext;
57030b57cec5SDimitry Andric   if (Freestanding)
57040b57cec5SDimitry Andric     CmdArgs.push_back("-ffreestanding");
57050b57cec5SDimitry Andric 
570681ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
570781ad6265SDimitry Andric 
57080b57cec5SDimitry Andric   // This is a coarse approximation of what llvm-gcc actually does, both
57090b57cec5SDimitry Andric   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
57100b57cec5SDimitry Andric   // complicated ways.
5711349cc55cSDimitry Andric   auto SanitizeArgs = TC.getSanitizerArgs(Args);
5712bdd1243dSDimitry Andric 
5713bdd1243dSDimitry Andric   bool IsAsyncUnwindTablesDefault =
5714bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5715bdd1243dSDimitry Andric   bool IsSyncUnwindTablesDefault =
5716bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5717bdd1243dSDimitry Andric 
5718349cc55cSDimitry Andric   bool AsyncUnwindTables = Args.hasFlag(
5719349cc55cSDimitry Andric       options::OPT_fasynchronous_unwind_tables,
57200b57cec5SDimitry Andric       options::OPT_fno_asynchronous_unwind_tables,
5721bdd1243dSDimitry Andric       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
57220b57cec5SDimitry Andric           !Freestanding);
5723bdd1243dSDimitry Andric   bool UnwindTables =
5724bdd1243dSDimitry Andric       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5725bdd1243dSDimitry Andric                    IsSyncUnwindTablesDefault && !Freestanding);
5726349cc55cSDimitry Andric   if (AsyncUnwindTables)
5727349cc55cSDimitry Andric     CmdArgs.push_back("-funwind-tables=2");
5728349cc55cSDimitry Andric   else if (UnwindTables)
5729349cc55cSDimitry Andric      CmdArgs.push_back("-funwind-tables=1");
57300b57cec5SDimitry Andric 
57315ffd83dbSDimitry Andric   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
57325ffd83dbSDimitry Andric   // `--gpu-use-aux-triple-only` is specified.
57335ffd83dbSDimitry Andric   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5734fe6060f1SDimitry Andric       (IsCudaDevice || IsHIPDevice)) {
57355ffd83dbSDimitry Andric     const ArgList &HostArgs =
57365ffd83dbSDimitry Andric         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
57375ffd83dbSDimitry Andric     std::string HostCPU =
5738349cc55cSDimitry Andric         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
57395ffd83dbSDimitry Andric     if (!HostCPU.empty()) {
57405ffd83dbSDimitry Andric       CmdArgs.push_back("-aux-target-cpu");
57415ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(HostCPU));
57425ffd83dbSDimitry Andric     }
57435ffd83dbSDimitry Andric     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
57445ffd83dbSDimitry Andric                       /*ForAS*/ false, /*IsAux*/ true);
57455ffd83dbSDimitry Andric   }
57465ffd83dbSDimitry Andric 
57470b57cec5SDimitry Andric   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
57480b57cec5SDimitry Andric 
57490b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
57505ffd83dbSDimitry Andric     StringRef CM = A->getValue();
57515f757f3fSDimitry Andric     bool Ok = false;
5752fe6060f1SDimitry Andric     if (Triple.isOSAIX() && CM == "medium")
57535f757f3fSDimitry Andric       CM = "large";
57545f757f3fSDimitry Andric     if (Triple.isAArch64(64)) {
57555f757f3fSDimitry Andric       Ok = CM == "tiny" || CM == "small" || CM == "large";
57565f757f3fSDimitry Andric       if (CM == "large" && RelocationModel != llvm::Reloc::Static)
57575f757f3fSDimitry Andric         D.Diag(diag::err_drv_argument_only_allowed_with)
57585f757f3fSDimitry Andric             << A->getAsString(Args) << "-fno-pic";
57595f757f3fSDimitry Andric     } else if (Triple.isLoongArch()) {
57605f757f3fSDimitry Andric       if (CM == "extreme" &&
57615f757f3fSDimitry Andric           Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
57625f757f3fSDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
57635f757f3fSDimitry Andric             << A->getAsString(Args) << "-fplt";
57645f757f3fSDimitry Andric       Ok = CM == "normal" || CM == "medium" || CM == "extreme";
57655f757f3fSDimitry Andric       // Convert to LLVM recognizable names.
57665f757f3fSDimitry Andric       if (Ok)
57675f757f3fSDimitry Andric         CM = llvm::StringSwitch<StringRef>(CM)
57685f757f3fSDimitry Andric                  .Case("normal", "small")
57695f757f3fSDimitry Andric                  .Case("extreme", "large")
57705f757f3fSDimitry Andric                  .Default(CM);
57715f757f3fSDimitry Andric     } else if (Triple.isPPC64() || Triple.isOSAIX()) {
57725f757f3fSDimitry Andric       Ok = CM == "small" || CM == "medium" || CM == "large";
57735f757f3fSDimitry Andric     } else if (Triple.isRISCV()) {
57745f757f3fSDimitry Andric       if (CM == "medlow")
57755f757f3fSDimitry Andric         CM = "small";
57765f757f3fSDimitry Andric       else if (CM == "medany")
57775f757f3fSDimitry Andric         CM = "medium";
57785f757f3fSDimitry Andric       Ok = CM == "small" || CM == "medium";
57795f757f3fSDimitry Andric     } else if (Triple.getArch() == llvm::Triple::x86_64) {
57805f757f3fSDimitry Andric       Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
57815f757f3fSDimitry Andric                               CM);
57825f757f3fSDimitry Andric     } else if (Triple.isNVPTX() || Triple.isAMDGPU()) {
57835f757f3fSDimitry Andric       // NVPTX/AMDGPU does not care about the code model and will accept
57845f757f3fSDimitry Andric       // whatever works for the host.
57855f757f3fSDimitry Andric       Ok = true;
5786b3edf446SDimitry Andric     } else if (Triple.isSPARC64()) {
5787b3edf446SDimitry Andric       if (CM == "medlow")
5788b3edf446SDimitry Andric         CM = "small";
5789b3edf446SDimitry Andric       else if (CM == "medmid")
5790b3edf446SDimitry Andric         CM = "medium";
5791b3edf446SDimitry Andric       else if (CM == "medany")
5792b3edf446SDimitry Andric         CM = "large";
5793b3edf446SDimitry Andric       Ok = CM == "small" || CM == "medium" || CM == "large";
57945f757f3fSDimitry Andric     }
57955f757f3fSDimitry Andric     if (Ok) {
57965f757f3fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
5797fe6060f1SDimitry Andric     } else {
57985f757f3fSDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument_for_target)
57995f757f3fSDimitry Andric           << A->getSpelling() << CM << TripleStr;
58005f757f3fSDimitry Andric     }
58015f757f3fSDimitry Andric   }
58025f757f3fSDimitry Andric 
58037a6dacacSDimitry Andric   if (Triple.getArch() == llvm::Triple::x86_64) {
58045f757f3fSDimitry Andric     bool IsMediumCM = false;
58057a6dacacSDimitry Andric     bool IsLargeCM = false;
58067a6dacacSDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
58075f757f3fSDimitry Andric       IsMediumCM = StringRef(A->getValue()) == "medium";
58087a6dacacSDimitry Andric       IsLargeCM = StringRef(A->getValue()) == "large";
58097a6dacacSDimitry Andric     }
58107a6dacacSDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
58117a6dacacSDimitry Andric       if (!IsMediumCM && !IsLargeCM) {
58125f757f3fSDimitry Andric         D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
58135f757f3fSDimitry Andric             << A->getOption().getRenderName();
58145f757f3fSDimitry Andric       } else {
58155f757f3fSDimitry Andric         A->render(Args, CmdArgs);
58165f757f3fSDimitry Andric       }
58177a6dacacSDimitry Andric     } else if (IsMediumCM) {
58187a6dacacSDimitry Andric       CmdArgs.push_back("-mlarge-data-threshold=65536");
58197a6dacacSDimitry Andric     } else if (IsLargeCM) {
58207a6dacacSDimitry Andric       CmdArgs.push_back("-mlarge-data-threshold=0");
58210b57cec5SDimitry Andric     }
5822fe6060f1SDimitry Andric   }
58230b57cec5SDimitry Andric 
5824480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5825480093f4SDimitry Andric     StringRef Value = A->getValue();
5826480093f4SDimitry Andric     unsigned TLSSize = 0;
5827480093f4SDimitry Andric     Value.getAsInteger(10, TLSSize);
5828480093f4SDimitry Andric     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5829480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5830480093f4SDimitry Andric           << A->getOption().getName() << TripleStr;
5831480093f4SDimitry Andric     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5832480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
5833480093f4SDimitry Andric           << A->getOption().getName() << Value;
5834480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5835480093f4SDimitry Andric   }
5836480093f4SDimitry Andric 
5837b3edf446SDimitry Andric   if (isTLSDESCEnabled(TC, Args))
5838b3edf446SDimitry Andric     CmdArgs.push_back("-enable-tlsdesc");
5839b3edf446SDimitry Andric 
58400b57cec5SDimitry Andric   // Add the target cpu
5841349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
58420b57cec5SDimitry Andric   if (!CPU.empty()) {
58430b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
58440b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
58450b57cec5SDimitry Andric   }
58460b57cec5SDimitry Andric 
58470b57cec5SDimitry Andric   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
58480b57cec5SDimitry Andric 
58490b57cec5SDimitry Andric   // Add clang-cl arguments.
58500b57cec5SDimitry Andric   types::ID InputType = Input.getType();
58510b57cec5SDimitry Andric   if (D.IsCLMode())
58525f757f3fSDimitry Andric     AddClangCLArgs(Args, InputType, CmdArgs);
58530b57cec5SDimitry Andric 
58545f757f3fSDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
58555f757f3fSDimitry Andric       llvm::codegenoptions::NoDebugInfo;
5856e8d8bef9SDimitry Andric   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
58575f757f3fSDimitry Andric   renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
58585f757f3fSDimitry Andric                      CmdArgs, Output, DebugInfoKind, DwarfFission);
585981ad6265SDimitry Andric 
58600b57cec5SDimitry Andric   // Add the split debug info name to the command lines here so we
58610b57cec5SDimitry Andric   // can propagate it to the backend.
58620b57cec5SDimitry Andric   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5863e8d8bef9SDimitry Andric                     (TC.getTriple().isOSBinFormatELF() ||
586406c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatWasm() ||
586506c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatCOFF()) &&
58660b57cec5SDimitry Andric                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
58670b57cec5SDimitry Andric                      isa<BackendJobAction>(JA));
58680b57cec5SDimitry Andric   if (SplitDWARF) {
5869e8d8bef9SDimitry Andric     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
58700b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-file");
58710b57cec5SDimitry Andric     CmdArgs.push_back(SplitDWARFOut);
58720b57cec5SDimitry Andric     if (DwarfFission == DwarfFissionKind::Split) {
58730b57cec5SDimitry Andric       CmdArgs.push_back("-split-dwarf-output");
58740b57cec5SDimitry Andric       CmdArgs.push_back(SplitDWARFOut);
58750b57cec5SDimitry Andric     }
58760b57cec5SDimitry Andric   }
58770b57cec5SDimitry Andric 
58780b57cec5SDimitry Andric   // Pass the linker version in use.
58790b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
58800b57cec5SDimitry Andric     CmdArgs.push_back("-target-linker-version");
58810b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
58820b57cec5SDimitry Andric   }
58830b57cec5SDimitry Andric 
58840b57cec5SDimitry Andric   // Explicitly error on some things we know we don't support and can't just
58850b57cec5SDimitry Andric   // ignore.
58860b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
58870b57cec5SDimitry Andric     Arg *Unsupported;
58880b57cec5SDimitry Andric     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
58890b57cec5SDimitry Andric         TC.getArch() == llvm::Triple::x86) {
58900b57cec5SDimitry Andric       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
58910b57cec5SDimitry Andric           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
58920b57cec5SDimitry Andric         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
58930b57cec5SDimitry Andric             << Unsupported->getOption().getName();
58940b57cec5SDimitry Andric     }
58950b57cec5SDimitry Andric     // The faltivec option has been superseded by the maltivec option.
58960b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
58970b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
58980b57cec5SDimitry Andric           << Unsupported->getOption().getName()
58990b57cec5SDimitry Andric           << "please use -maltivec and include altivec.h explicitly";
59000b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
59010b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
59020b57cec5SDimitry Andric           << Unsupported->getOption().getName() << "please use -mno-altivec";
59030b57cec5SDimitry Andric   }
59040b57cec5SDimitry Andric 
59050b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_v);
59065ffd83dbSDimitry Andric 
59075ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_H)) {
59085ffd83dbSDimitry Andric     CmdArgs.push_back("-H");
59095ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
59105ffd83dbSDimitry Andric   }
5911fe6060f1SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
59125ffd83dbSDimitry Andric 
5913bdd1243dSDimitry Andric   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
59140b57cec5SDimitry Andric     CmdArgs.push_back("-header-include-file");
5915fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5916fe6060f1SDimitry Andric                           ? D.CCPrintHeadersFilename.c_str()
59170b57cec5SDimitry Andric                           : "-");
59185ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
5919bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
5920bdd1243dSDimitry Andric         "-header-include-format=" +
5921bdd1243dSDimitry Andric         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5922bdd1243dSDimitry Andric     CmdArgs.push_back(
5923bdd1243dSDimitry Andric         Args.MakeArgString("-header-include-filtering=" +
5924bdd1243dSDimitry Andric                            std::string(headerIncludeFilteringKindToString(
5925bdd1243dSDimitry Andric                                D.CCPrintHeadersFiltering))));
59260b57cec5SDimitry Andric   }
59270b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_P);
59280b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
59290b57cec5SDimitry Andric 
59300b57cec5SDimitry Andric   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
59310b57cec5SDimitry Andric     CmdArgs.push_back("-diagnostic-log-file");
5932fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5933fe6060f1SDimitry Andric                           ? D.CCLogDiagnosticsFilename.c_str()
59340b57cec5SDimitry Andric                           : "-");
59350b57cec5SDimitry Andric   }
59360b57cec5SDimitry Andric 
593713138422SDimitry Andric   // Give the gen diagnostics more chances to succeed, by avoiding intentional
593813138422SDimitry Andric   // crashes.
593913138422SDimitry Andric   if (D.CCGenDiagnostics)
594013138422SDimitry Andric     CmdArgs.push_back("-disable-pragma-debug-crash");
594113138422SDimitry Andric 
5942fe6060f1SDimitry Andric   // Allow backend to put its diagnostic files in the same place as frontend
5943fe6060f1SDimitry Andric   // crash diagnostics files.
5944fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5945fe6060f1SDimitry Andric     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5946fe6060f1SDimitry Andric     CmdArgs.push_back("-mllvm");
5947fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5948fe6060f1SDimitry Andric   }
5949fe6060f1SDimitry Andric 
59500b57cec5SDimitry Andric   bool UseSeparateSections = isUseSeparateSections(Triple);
59510b57cec5SDimitry Andric 
59520b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_ffunction_sections,
59530b57cec5SDimitry Andric                    options::OPT_fno_function_sections, UseSeparateSections)) {
59540b57cec5SDimitry Andric     CmdArgs.push_back("-ffunction-sections");
59550b57cec5SDimitry Andric   }
59560b57cec5SDimitry Andric 
59575ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
59585ffd83dbSDimitry Andric     StringRef Val = A->getValue();
5959fe6060f1SDimitry Andric     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
59605ffd83dbSDimitry Andric       if (Val != "all" && Val != "labels" && Val != "none" &&
59615f757f3fSDimitry Andric           !Val.starts_with("list="))
59625ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
59635ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
59645ffd83dbSDimitry Andric       else
59655ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
5966fe6060f1SDimitry Andric     } else if (Triple.isNVPTX()) {
5967fe6060f1SDimitry Andric       // Do not pass the option to the GPU compilation. We still want it enabled
5968fe6060f1SDimitry Andric       // for the host-side compilation, so seeing it here is not an error.
5969fe6060f1SDimitry Andric     } else if (Val != "none") {
5970fe6060f1SDimitry Andric       // =none is allowed everywhere. It's useful for overriding the option
5971fe6060f1SDimitry Andric       // and is the same as not specifying the option.
5972e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5973e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
5974e8d8bef9SDimitry Andric     }
59755ffd83dbSDimitry Andric   }
59765ffd83dbSDimitry Andric 
5977e8d8bef9SDimitry Andric   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
59780b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5979e8d8bef9SDimitry Andric                    UseSeparateSections || HasDefaultDataSections)) {
59800b57cec5SDimitry Andric     CmdArgs.push_back("-fdata-sections");
59810b57cec5SDimitry Andric   }
59820b57cec5SDimitry Andric 
598381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
598481ad6265SDimitry Andric                      options::OPT_fno_unique_section_names);
598581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
598681ad6265SDimitry Andric                     options::OPT_fno_unique_internal_linkage_names);
598781ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
598881ad6265SDimitry Andric                     options::OPT_fno_unique_basic_block_section_names);
598906c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
599006c3fb27SDimitry Andric                     options::OPT_fno_convergent_functions);
59915ffd83dbSDimitry Andric 
5992e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5993e8d8bef9SDimitry Andric                                options::OPT_fno_split_machine_functions)) {
59945f757f3fSDimitry Andric     if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
59955f757f3fSDimitry Andric       // This codegen pass is only available on x86 and AArch64 ELF targets.
59965f757f3fSDimitry Andric       if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
5997e8d8bef9SDimitry Andric         A->render(Args, CmdArgs);
59985f757f3fSDimitry Andric       else
5999e8d8bef9SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6000e8d8bef9SDimitry Andric             << A->getAsString(Args) << TripleStr;
6001e8d8bef9SDimitry Andric     }
6002e8d8bef9SDimitry Andric   }
6003e8d8bef9SDimitry Andric 
60040b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
60050b57cec5SDimitry Andric                   options::OPT_finstrument_functions_after_inlining,
60060b57cec5SDimitry Andric                   options::OPT_finstrument_function_entry_bare);
60070b57cec5SDimitry Andric 
60085ffd83dbSDimitry Andric   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
60095ffd83dbSDimitry Andric   // for sampling, overhead of call arc collection is way too high and there's
60105ffd83dbSDimitry Andric   // no way to collect the output.
60115ffd83dbSDimitry Andric   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
601206c3fb27SDimitry Andric     addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
60130b57cec5SDimitry Andric 
60140b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
60150b57cec5SDimitry Andric 
6016bdd1243dSDimitry Andric   if (getLastProfileSampleUseArg(Args) &&
6017bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fsample_profile_use_profi)) {
6018bdd1243dSDimitry Andric     CmdArgs.push_back("-mllvm");
6019bdd1243dSDimitry Andric     CmdArgs.push_back("-sample-profile-use-profi");
6020bdd1243dSDimitry Andric   }
6021bdd1243dSDimitry Andric 
602281ad6265SDimitry Andric   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
602381ad6265SDimitry Andric   if (RawTriple.isPS() &&
60240b57cec5SDimitry Andric       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
602581ad6265SDimitry Andric     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
602681ad6265SDimitry Andric     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
60270b57cec5SDimitry Andric   }
60280b57cec5SDimitry Andric 
60290b57cec5SDimitry Andric   // Pass options for controlling the default header search paths.
60300b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_nostdinc)) {
60310b57cec5SDimitry Andric     CmdArgs.push_back("-nostdsysteminc");
60320b57cec5SDimitry Andric     CmdArgs.push_back("-nobuiltininc");
60330b57cec5SDimitry Andric   } else {
60340b57cec5SDimitry Andric     if (Args.hasArg(options::OPT_nostdlibinc))
60350b57cec5SDimitry Andric       CmdArgs.push_back("-nostdsysteminc");
60360b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
60370b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
60380b57cec5SDimitry Andric   }
60390b57cec5SDimitry Andric 
60400b57cec5SDimitry Andric   // Pass the path to compiler resource files.
60410b57cec5SDimitry Andric   CmdArgs.push_back("-resource-dir");
60420b57cec5SDimitry Andric   CmdArgs.push_back(D.ResourceDir.c_str());
60430b57cec5SDimitry Andric 
60440b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
60450b57cec5SDimitry Andric 
60460b57cec5SDimitry Andric   RenderARCMigrateToolOptions(D, Args, CmdArgs);
60470b57cec5SDimitry Andric 
60480b57cec5SDimitry Andric   // Add preprocessing options like -I, -D, etc. if we are using the
60490b57cec5SDimitry Andric   // preprocessor.
60500b57cec5SDimitry Andric   //
60510b57cec5SDimitry Andric   // FIXME: Support -fpreprocessed
60520b57cec5SDimitry Andric   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
60530b57cec5SDimitry Andric     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
60540b57cec5SDimitry Andric 
60550b57cec5SDimitry Andric   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
60560b57cec5SDimitry Andric   // that "The compiler can only warn and ignore the option if not recognized".
60570b57cec5SDimitry Andric   // When building with ccache, it will pass -D options to clang even on
60580b57cec5SDimitry Andric   // preprocessed inputs and configure concludes that -fPIC is not supported.
60590b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_D);
60600b57cec5SDimitry Andric 
60610b57cec5SDimitry Andric   // Manually translate -O4 to -O3; let clang reject others.
60620b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
60630b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4)) {
60640b57cec5SDimitry Andric       CmdArgs.push_back("-O3");
60650b57cec5SDimitry Andric       D.Diag(diag::warn_O4_is_O3);
60660b57cec5SDimitry Andric     } else {
60670b57cec5SDimitry Andric       A->render(Args, CmdArgs);
60680b57cec5SDimitry Andric     }
60690b57cec5SDimitry Andric   }
60700b57cec5SDimitry Andric 
60710b57cec5SDimitry Andric   // Warn about ignored options to clang.
60720b57cec5SDimitry Andric   for (const Arg *A :
60730b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
60740b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
60750b57cec5SDimitry Andric     A->claim();
60760b57cec5SDimitry Andric   }
60770b57cec5SDimitry Andric 
60780b57cec5SDimitry Andric   for (const Arg *A :
60790b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
60800b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
60810b57cec5SDimitry Andric     A->claim();
60820b57cec5SDimitry Andric   }
60830b57cec5SDimitry Andric 
60840b57cec5SDimitry Andric   claimNoWarnArgs(Args);
60850b57cec5SDimitry Andric 
60860b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
60870b57cec5SDimitry Andric 
6088349cc55cSDimitry Andric   for (const Arg *A :
6089349cc55cSDimitry Andric        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6090349cc55cSDimitry Andric     A->claim();
6091349cc55cSDimitry Andric     if (A->getOption().getID() == options::OPT__SLASH_wd) {
6092349cc55cSDimitry Andric       unsigned WarningNumber;
6093349cc55cSDimitry Andric       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6094349cc55cSDimitry Andric         D.Diag(diag::err_drv_invalid_int_value)
6095349cc55cSDimitry Andric             << A->getAsString(Args) << A->getValue();
6096349cc55cSDimitry Andric         continue;
6097349cc55cSDimitry Andric       }
6098349cc55cSDimitry Andric 
6099349cc55cSDimitry Andric       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6100349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
6101349cc55cSDimitry Andric             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6102349cc55cSDimitry Andric       }
6103349cc55cSDimitry Andric       continue;
6104349cc55cSDimitry Andric     }
6105349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6106349cc55cSDimitry Andric   }
6107349cc55cSDimitry Andric 
61085f757f3fSDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
61095f757f3fSDimitry Andric 
61100b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
61110b57cec5SDimitry Andric     CmdArgs.push_back("-pedantic");
61120b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
61130b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_w);
61140b57cec5SDimitry Andric 
6115bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6116bdd1243dSDimitry Andric                     options::OPT_fno_fixed_point);
61170b57cec5SDimitry Andric 
6118fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6119fe6060f1SDimitry Andric     A->render(Args, CmdArgs);
6120fe6060f1SDimitry Andric 
6121fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6122fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
6123fe6060f1SDimitry Andric 
61245f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
61255f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
61265f757f3fSDimitry Andric 
6127349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6128349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6129349cc55cSDimitry Andric 
61300b57cec5SDimitry Andric   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
61310b57cec5SDimitry Andric   // (-ansi is equivalent to -std=c89 or -std=c++98).
61320b57cec5SDimitry Andric   //
61330b57cec5SDimitry Andric   // If a std is supplied, only add -trigraphs if it follows the
61340b57cec5SDimitry Andric   // option.
6135fe6060f1SDimitry Andric   bool ImplyVCPPCVer = false;
61360b57cec5SDimitry Andric   bool ImplyVCPPCXXVer = false;
61370b57cec5SDimitry Andric   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
61380b57cec5SDimitry Andric   if (Std) {
61390b57cec5SDimitry Andric     if (Std->getOption().matches(options::OPT_ansi))
61400b57cec5SDimitry Andric       if (types::isCXX(InputType))
61410b57cec5SDimitry Andric         CmdArgs.push_back("-std=c++98");
61420b57cec5SDimitry Andric       else
61430b57cec5SDimitry Andric         CmdArgs.push_back("-std=c89");
61440b57cec5SDimitry Andric     else
61450b57cec5SDimitry Andric       Std->render(Args, CmdArgs);
61460b57cec5SDimitry Andric 
61470b57cec5SDimitry Andric     // If -f(no-)trigraphs appears after the language standard flag, honor it.
61480b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
61490b57cec5SDimitry Andric                                  options::OPT_ftrigraphs,
61500b57cec5SDimitry Andric                                  options::OPT_fno_trigraphs))
61510b57cec5SDimitry Andric       if (A != Std)
61520b57cec5SDimitry Andric         A->render(Args, CmdArgs);
61530b57cec5SDimitry Andric   } else {
61540b57cec5SDimitry Andric     // Honor -std-default.
61550b57cec5SDimitry Andric     //
61560b57cec5SDimitry Andric     // FIXME: Clang doesn't correctly handle -std= when the input language
61570b57cec5SDimitry Andric     // doesn't match. For the time being just ignore this for C++ inputs;
61580b57cec5SDimitry Andric     // eventually we want to do all the standard defaulting here instead of
61590b57cec5SDimitry Andric     // splitting it between the driver and clang -cc1.
6160fe6060f1SDimitry Andric     if (!types::isCXX(InputType)) {
6161fe6060f1SDimitry Andric       if (!Args.hasArg(options::OPT__SLASH_std)) {
61620b57cec5SDimitry Andric         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
61630b57cec5SDimitry Andric                                   /*Joined=*/true);
6164fe6060f1SDimitry Andric       } else
6165fe6060f1SDimitry Andric         ImplyVCPPCVer = true;
6166fe6060f1SDimitry Andric     }
61670b57cec5SDimitry Andric     else if (IsWindowsMSVC)
61680b57cec5SDimitry Andric       ImplyVCPPCXXVer = true;
61690b57cec5SDimitry Andric 
61700b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
61710b57cec5SDimitry Andric                     options::OPT_fno_trigraphs);
61720b57cec5SDimitry Andric   }
61730b57cec5SDimitry Andric 
61740b57cec5SDimitry Andric   // GCC's behavior for -Wwrite-strings is a bit strange:
61750b57cec5SDimitry Andric   //  * In C, this "warning flag" changes the types of string literals from
61760b57cec5SDimitry Andric   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
61770b57cec5SDimitry Andric   //    for the discarded qualifier.
61780b57cec5SDimitry Andric   //  * In C++, this is just a normal warning flag.
61790b57cec5SDimitry Andric   //
61800b57cec5SDimitry Andric   // Implementing this warning correctly in C is hard, so we follow GCC's
61810b57cec5SDimitry Andric   // behavior for now. FIXME: Directly diagnose uses of a string literal as
61820b57cec5SDimitry Andric   // a non-const char* in C, rather than using this crude hack.
61830b57cec5SDimitry Andric   if (!types::isCXX(InputType)) {
61840b57cec5SDimitry Andric     // FIXME: This should behave just like a warning flag, and thus should also
61850b57cec5SDimitry Andric     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
61860b57cec5SDimitry Andric     Arg *WriteStrings =
61870b57cec5SDimitry Andric         Args.getLastArg(options::OPT_Wwrite_strings,
61880b57cec5SDimitry Andric                         options::OPT_Wno_write_strings, options::OPT_w);
61890b57cec5SDimitry Andric     if (WriteStrings &&
61900b57cec5SDimitry Andric         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
61910b57cec5SDimitry Andric       CmdArgs.push_back("-fconst-strings");
61920b57cec5SDimitry Andric   }
61930b57cec5SDimitry Andric 
61940b57cec5SDimitry Andric   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
61950b57cec5SDimitry Andric   // during C++ compilation, which it is by default. GCC keeps this define even
61960b57cec5SDimitry Andric   // in the presence of '-w', match this behavior bug-for-bug.
61970b57cec5SDimitry Andric   if (types::isCXX(InputType) &&
61980b57cec5SDimitry Andric       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
61990b57cec5SDimitry Andric                    true)) {
62000b57cec5SDimitry Andric     CmdArgs.push_back("-fdeprecated-macro");
62010b57cec5SDimitry Andric   }
62020b57cec5SDimitry Andric 
62030b57cec5SDimitry Andric   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
62040b57cec5SDimitry Andric   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
62050b57cec5SDimitry Andric     if (Asm->getOption().matches(options::OPT_fasm))
62060b57cec5SDimitry Andric       CmdArgs.push_back("-fgnu-keywords");
62070b57cec5SDimitry Andric     else
62080b57cec5SDimitry Andric       CmdArgs.push_back("-fno-gnu-keywords");
62090b57cec5SDimitry Andric   }
62100b57cec5SDimitry Andric 
6211480093f4SDimitry Andric   if (!ShouldEnableAutolink(Args, TC, JA))
62120b57cec5SDimitry Andric     CmdArgs.push_back("-fno-autolink");
62130b57cec5SDimitry Andric 
621406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
621506c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
621606c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
621706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
62180b57cec5SDimitry Andric 
6219fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
622081ad6265SDimitry Andric 
6221a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6222a7dea167SDimitry Andric     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6223a7dea167SDimitry Andric 
62240b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
62250b57cec5SDimitry Andric     CmdArgs.push_back("-fbracket-depth");
62260b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
62270b57cec5SDimitry Andric   }
62280b57cec5SDimitry Andric 
62290b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
62300b57cec5SDimitry Andric                                options::OPT_Wlarge_by_value_copy_def)) {
62310b57cec5SDimitry Andric     if (A->getNumValues()) {
62320b57cec5SDimitry Andric       StringRef bytes = A->getValue();
62330b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
62340b57cec5SDimitry Andric     } else
62350b57cec5SDimitry Andric       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
62360b57cec5SDimitry Andric   }
62370b57cec5SDimitry Andric 
62380b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_relocatable_pch))
62390b57cec5SDimitry Andric     CmdArgs.push_back("-relocatable-pch");
62400b57cec5SDimitry Andric 
62410b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
62420b57cec5SDimitry Andric     static const char *kCFABIs[] = {
62430b57cec5SDimitry Andric       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
62440b57cec5SDimitry Andric     };
62450b57cec5SDimitry Andric 
624681ad6265SDimitry Andric     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
62470b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
62480b57cec5SDimitry Andric     else
62490b57cec5SDimitry Andric       A->render(Args, CmdArgs);
62500b57cec5SDimitry Andric   }
62510b57cec5SDimitry Andric 
62520b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
62530b57cec5SDimitry Andric     CmdArgs.push_back("-fconstant-string-class");
62540b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
62550b57cec5SDimitry Andric   }
62560b57cec5SDimitry Andric 
62570b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
62580b57cec5SDimitry Andric     CmdArgs.push_back("-ftabstop");
62590b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
62600b57cec5SDimitry Andric   }
62610b57cec5SDimitry Andric 
6262bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6263bdd1243dSDimitry Andric                     options::OPT_fno_stack_size_section);
62640b57cec5SDimitry Andric 
6265fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fstack_usage)) {
6266fe6060f1SDimitry Andric     CmdArgs.push_back("-stack-usage-file");
6267fe6060f1SDimitry Andric 
6268fe6060f1SDimitry Andric     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6269fe6060f1SDimitry Andric       SmallString<128> OutputFilename(OutputOpt->getValue());
6270fe6060f1SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "su");
6271fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6272fe6060f1SDimitry Andric     } else
6273fe6060f1SDimitry Andric       CmdArgs.push_back(
6274fe6060f1SDimitry Andric           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6275fe6060f1SDimitry Andric   }
6276fe6060f1SDimitry Andric 
62770b57cec5SDimitry Andric   CmdArgs.push_back("-ferror-limit");
62780b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
62790b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
62800b57cec5SDimitry Andric   else
62810b57cec5SDimitry Andric     CmdArgs.push_back("19");
62820b57cec5SDimitry Andric 
628306c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
628406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
628506c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
628606c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
628706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
62880b57cec5SDimitry Andric 
62890b57cec5SDimitry Andric   // Pass -fmessage-length=.
62905ffd83dbSDimitry Andric   unsigned MessageLength = 0;
62910b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
62925ffd83dbSDimitry Andric     StringRef V(A->getValue());
62935ffd83dbSDimitry Andric     if (V.getAsInteger(0, MessageLength))
62945ffd83dbSDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
62955ffd83dbSDimitry Andric           << V << A->getOption().getName();
62960b57cec5SDimitry Andric   } else {
62970b57cec5SDimitry Andric     // If -fmessage-length=N was not specified, determine whether this is a
62980b57cec5SDimitry Andric     // terminal and, if so, implicitly define -fmessage-length appropriately.
62995ffd83dbSDimitry Andric     MessageLength = llvm::sys::Process::StandardErrColumns();
63000b57cec5SDimitry Andric   }
63015ffd83dbSDimitry Andric   if (MessageLength != 0)
63025ffd83dbSDimitry Andric     CmdArgs.push_back(
63035ffd83dbSDimitry Andric         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
63040b57cec5SDimitry Andric 
630581ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
630681ad6265SDimitry Andric     CmdArgs.push_back(
630781ad6265SDimitry Andric         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
630881ad6265SDimitry Andric 
630981ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
631081ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
631181ad6265SDimitry Andric                                          Twine(A->getValue(0))));
631281ad6265SDimitry Andric 
63130b57cec5SDimitry Andric   // -fvisibility= and -fvisibility-ms-compat are of a piece.
63140b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
63150b57cec5SDimitry Andric                                      options::OPT_fvisibility_ms_compat)) {
63160b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6317bdd1243dSDimitry Andric       A->render(Args, CmdArgs);
63180b57cec5SDimitry Andric     } else {
63190b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6320bdd1243dSDimitry Andric       CmdArgs.push_back("-fvisibility=hidden");
6321bdd1243dSDimitry Andric       CmdArgs.push_back("-ftype-visibility=default");
63220b57cec5SDimitry Andric     }
632304eeddc0SDimitry Andric   } else if (IsOpenMPDevice) {
632404eeddc0SDimitry Andric     // When compiling for the OpenMP device we want protected visibility by
6325bdd1243dSDimitry Andric     // default. This prevents the device from accidentally preempting code on
6326bdd1243dSDimitry Andric     // the host, makes the system more robust, and improves performance.
6327bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=protected");
63280b57cec5SDimitry Andric   }
63290b57cec5SDimitry Andric 
6330bdd1243dSDimitry Andric   // PS4/PS5 process these options in addClangTargetOptions.
6331bdd1243dSDimitry Andric   if (!RawTriple.isPS()) {
6332e8d8bef9SDimitry Andric     if (const Arg *A =
6333e8d8bef9SDimitry Andric             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6334e8d8bef9SDimitry Andric                             options::OPT_fno_visibility_from_dllstorageclass)) {
6335e8d8bef9SDimitry Andric       if (A->getOption().matches(
6336e8d8bef9SDimitry Andric               options::OPT_fvisibility_from_dllstorageclass)) {
6337e8d8bef9SDimitry Andric         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6338e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6339e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6340e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6341e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs,
6342e8d8bef9SDimitry Andric                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6343e8d8bef9SDimitry Andric       }
6344e8d8bef9SDimitry Andric     }
6345bdd1243dSDimitry Andric   }
6346e8d8bef9SDimitry Andric 
6347fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6348fe6060f1SDimitry Andric                     options::OPT_fno_visibility_inlines_hidden, false))
6349fe6060f1SDimitry Andric     CmdArgs.push_back("-fvisibility-inlines-hidden");
6350fe6060f1SDimitry Andric 
6351e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6352e8d8bef9SDimitry Andric                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
63537a6dacacSDimitry Andric 
63547a6dacacSDimitry Andric   // -fvisibility-global-new-delete-hidden is a deprecated spelling of
63557a6dacacSDimitry Andric   // -fvisibility-global-new-delete=force-hidden.
63567a6dacacSDimitry Andric   if (const Arg *A =
63577a6dacacSDimitry Andric           Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
63587a6dacacSDimitry Andric     D.Diag(diag::warn_drv_deprecated_arg)
63597a6dacacSDimitry Andric         << A->getAsString(Args)
63607a6dacacSDimitry Andric         << "-fvisibility-global-new-delete=force-hidden";
63617a6dacacSDimitry Andric   }
63627a6dacacSDimitry Andric 
63637a6dacacSDimitry Andric   if (const Arg *A =
63647a6dacacSDimitry Andric           Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
63657a6dacacSDimitry Andric                           options::OPT_fvisibility_global_new_delete_hidden)) {
63667a6dacacSDimitry Andric     if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
63677a6dacacSDimitry Andric       A->render(Args, CmdArgs);
63687a6dacacSDimitry Andric     } else {
63697a6dacacSDimitry Andric       assert(A->getOption().matches(
63707a6dacacSDimitry Andric           options::OPT_fvisibility_global_new_delete_hidden));
63717a6dacacSDimitry Andric       CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
63727a6dacacSDimitry Andric     }
63737a6dacacSDimitry Andric   }
63747a6dacacSDimitry Andric 
63750b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
63760b57cec5SDimitry Andric 
63774824e7fdSDimitry Andric   if (Args.hasFlag(options::OPT_fnew_infallible,
63784824e7fdSDimitry Andric                    options::OPT_fno_new_infallible, false))
63794824e7fdSDimitry Andric     CmdArgs.push_back("-fnew-infallible");
63804824e7fdSDimitry Andric 
6381fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fno_operator_names,
6382fe6060f1SDimitry Andric                    options::OPT_foperator_names, false))
6383fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-operator-names");
6384fe6060f1SDimitry Andric 
63850b57cec5SDimitry Andric   // Forward -f (flag) options which we can pass directly.
63860b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
63870b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
63880b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
638981ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
639081ad6265SDimitry Andric 
639106c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
639206c3fb27SDimitry Andric                    Triple.hasDefaultEmulatedTLS()))
639306c3fb27SDimitry Andric     CmdArgs.push_back("-femulated-tls");
639406c3fb27SDimitry Andric 
639506c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
639606c3fb27SDimitry Andric                     options::OPT_fno_check_new);
639706c3fb27SDimitry Andric 
639881ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
639981ad6265SDimitry Andric     // FIXME: There's no reason for this to be restricted to X86. The backend
640081ad6265SDimitry Andric     // code needs to be changed to include the appropriate function calls
640181ad6265SDimitry Andric     // automatically.
640281ad6265SDimitry Andric     if (!Triple.isX86() && !Triple.isAArch64())
640381ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
640481ad6265SDimitry Andric           << A->getAsString(Args) << TripleStr;
640581ad6265SDimitry Andric   }
64060b57cec5SDimitry Andric 
64070b57cec5SDimitry Andric   // AltiVec-like language extensions aren't relevant for assembling.
64080b57cec5SDimitry Andric   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
64090b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
64100b57cec5SDimitry Andric 
64110b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
64120b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
64130b57cec5SDimitry Andric 
64140b57cec5SDimitry Andric   // Forward flags for OpenMP. We don't do this if the current action is an
64150b57cec5SDimitry Andric   // device offloading action other than OpenMP.
64160b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
64170b57cec5SDimitry Andric                    options::OPT_fno_openmp, false) &&
64180b57cec5SDimitry Andric       (JA.isDeviceOffloading(Action::OFK_None) ||
64190b57cec5SDimitry Andric        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
64200b57cec5SDimitry Andric     switch (D.getOpenMPRuntime(Args)) {
64210b57cec5SDimitry Andric     case Driver::OMPRT_OMP:
64220b57cec5SDimitry Andric     case Driver::OMPRT_IOMP5:
64230b57cec5SDimitry Andric       // Clang can generate useful OpenMP code for these two runtime libraries.
64240b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp");
64250b57cec5SDimitry Andric 
64260b57cec5SDimitry Andric       // If no option regarding the use of TLS in OpenMP codegeneration is
64270b57cec5SDimitry Andric       // given, decide a default based on the target. Otherwise rely on the
64280b57cec5SDimitry Andric       // options and pass the right information to the frontend.
64290b57cec5SDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
64300b57cec5SDimitry Andric                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
64310b57cec5SDimitry Andric         CmdArgs.push_back("-fnoopenmp-use-tls");
64320b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
64330b57cec5SDimitry Andric                       options::OPT_fno_openmp_simd);
6434480093f4SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
64350b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6436349cc55cSDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6437349cc55cSDimitry Andric                         options::OPT_fno_openmp_extensions, /*Default=*/true))
6438349cc55cSDimitry Andric         CmdArgs.push_back("-fno-openmp-extensions");
64390b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
64400b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
64410b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs,
64420b57cec5SDimitry Andric                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
64430b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
64440b57cec5SDimitry Andric                        options::OPT_fno_openmp_optimistic_collapse,
64450b57cec5SDimitry Andric                        /*Default=*/false))
64460b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-optimistic-collapse");
64470b57cec5SDimitry Andric 
64480b57cec5SDimitry Andric       // When in OpenMP offloading mode with NVPTX target, forward
64490b57cec5SDimitry Andric       // cuda-mode flag
64500b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
64510b57cec5SDimitry Andric                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
64520b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-cuda-mode");
64530b57cec5SDimitry Andric 
6454349cc55cSDimitry Andric       // When in OpenMP offloading mode, enable debugging on the device.
6455349cc55cSDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6456349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6457349cc55cSDimitry Andric                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6458349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-target-debug");
6459349cc55cSDimitry Andric 
6460349cc55cSDimitry Andric       // When in OpenMP offloading mode, forward assumptions information about
6461349cc55cSDimitry Andric       // thread and team counts in the device.
6462349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6463349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_teams_oversubscription,
6464349cc55cSDimitry Andric                        /*Default=*/false))
6465349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6466349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6467349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_threads_oversubscription,
6468349cc55cSDimitry Andric                        /*Default=*/false))
6469349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
647081ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
647181ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6472bdd1243dSDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6473bdd1243dSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
647481ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
647581ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-offload-mandatory");
64767a6dacacSDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_force_usm))
64777a6dacacSDimitry Andric         CmdArgs.push_back("-fopenmp-force-usm");
64780b57cec5SDimitry Andric       break;
64790b57cec5SDimitry Andric     default:
64800b57cec5SDimitry Andric       // By default, if Clang doesn't know how to generate useful OpenMP code
64810b57cec5SDimitry Andric       // for a specific runtime library, we just don't pass the '-fopenmp' flag
64820b57cec5SDimitry Andric       // down to the actual compilation.
64830b57cec5SDimitry Andric       // FIXME: It would be better to have a mode which *only* omits IR
64840b57cec5SDimitry Andric       // generation based on the OpenMP support so that we get consistent
64850b57cec5SDimitry Andric       // semantic analysis, etc.
64860b57cec5SDimitry Andric       break;
64870b57cec5SDimitry Andric     }
64880b57cec5SDimitry Andric   } else {
64890b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
64900b57cec5SDimitry Andric                     options::OPT_fno_openmp_simd);
64910b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
649281ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
649381ad6265SDimitry Andric                        options::OPT_fno_openmp_extensions);
64940b57cec5SDimitry Andric   }
64950b57cec5SDimitry Andric 
649681ad6265SDimitry Andric   // Forward the new driver to change offloading code generation.
6497bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_offload_new_driver,
6498bdd1243dSDimitry Andric                    options::OPT_no_offload_new_driver, false))
649981ad6265SDimitry Andric     CmdArgs.push_back("--offload-new-driver");
650081ad6265SDimitry Andric 
6501349cc55cSDimitry Andric   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
65020b57cec5SDimitry Andric 
65030b57cec5SDimitry Andric   const XRayArgs &XRay = TC.getXRayArgs();
65040b57cec5SDimitry Andric   XRay.addArgs(TC, Args, CmdArgs, InputType);
65050b57cec5SDimitry Andric 
6506e8d8bef9SDimitry Andric   for (const auto &Filename :
6507e8d8bef9SDimitry Andric        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6508e8d8bef9SDimitry Andric     if (D.getVFS().exists(Filename))
6509e8d8bef9SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6510e8d8bef9SDimitry Andric     else
6511e8d8bef9SDimitry Andric       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6512e8d8bef9SDimitry Andric   }
6513e8d8bef9SDimitry Andric 
6514480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6515480093f4SDimitry Andric     StringRef S0 = A->getValue(), S = S0;
651655e4f9d5SDimitry Andric     unsigned Size, Offset = 0;
651706c3fb27SDimitry Andric     if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
651806c3fb27SDimitry Andric         !Triple.isX86())
6519480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6520480093f4SDimitry Andric           << A->getAsString(Args) << TripleStr;
6521480093f4SDimitry Andric     else if (S.consumeInteger(10, Size) ||
6522480093f4SDimitry Andric              (!S.empty() && (!S.consume_front(",") ||
652355e4f9d5SDimitry Andric                              S.consumeInteger(10, Offset) || !S.empty())))
6524480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
6525480093f4SDimitry Andric           << S0 << A->getOption().getName();
652655e4f9d5SDimitry Andric     else if (Size < Offset)
6527480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
652855e4f9d5SDimitry Andric     else {
6529480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
653055e4f9d5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
653155e4f9d5SDimitry Andric           "-fpatchable-function-entry-offset=" + Twine(Offset)));
653255e4f9d5SDimitry Andric     }
6533480093f4SDimitry Andric   }
6534480093f4SDimitry Andric 
653504eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
653604eeddc0SDimitry Andric 
6537480093f4SDimitry Andric   if (TC.SupportsProfiling()) {
65380b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_pg);
65390b57cec5SDimitry Andric 
6540480093f4SDimitry Andric     llvm::Triple::ArchType Arch = TC.getArch();
6541480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6542480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6543480093f4SDimitry Andric         A->render(Args, CmdArgs);
6544480093f4SDimitry Andric       else
6545480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6546480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6547480093f4SDimitry Andric     }
6548480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6549480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6550480093f4SDimitry Andric         A->render(Args, CmdArgs);
6551480093f4SDimitry Andric       else
6552480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6553480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6554480093f4SDimitry Andric     }
6555480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6556480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6557480093f4SDimitry Andric         A->render(Args, CmdArgs);
6558480093f4SDimitry Andric       else
6559480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6560480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6561480093f4SDimitry Andric     }
6562480093f4SDimitry Andric   }
656306c3fb27SDimitry Andric 
656406c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
656506c3fb27SDimitry Andric     if (TC.getTriple().isOSzOS()) {
6566bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6567bdd1243dSDimitry Andric           << A->getAsString(Args) << TripleStr;
6568bdd1243dSDimitry Andric     }
6569bdd1243dSDimitry Andric   }
657006c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
657106c3fb27SDimitry Andric     if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
657206c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
657306c3fb27SDimitry Andric           << A->getAsString(Args) << TripleStr;
657406c3fb27SDimitry Andric     }
657506c3fb27SDimitry Andric   }
657606c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
657706c3fb27SDimitry Andric     if (A->getOption().matches(options::OPT_p)) {
657806c3fb27SDimitry Andric       A->claim();
657906c3fb27SDimitry Andric       if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
658006c3fb27SDimitry Andric         CmdArgs.push_back("-pg");
658106c3fb27SDimitry Andric     }
658206c3fb27SDimitry Andric   }
658306c3fb27SDimitry Andric 
658406c3fb27SDimitry Andric   // Reject AIX-specific link options on other targets.
658506c3fb27SDimitry Andric   if (!TC.getTriple().isOSAIX()) {
658606c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
658706c3fb27SDimitry Andric                                       options::OPT_mxcoff_build_id_EQ)) {
658806c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
658906c3fb27SDimitry Andric           << A->getSpelling() << TripleStr;
659006c3fb27SDimitry Andric     }
659106c3fb27SDimitry Andric   }
65920b57cec5SDimitry Andric 
65930b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_fapple_kext) ||
65940b57cec5SDimitry Andric       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
65950b57cec5SDimitry Andric     CmdArgs.push_back("-fapple-kext");
65960b57cec5SDimitry Andric 
6597fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6598a7dea167SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
65990b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
66000b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
66010b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
66020b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6603e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
66040b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
66050b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6606480093f4SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
66070b57cec5SDimitry Andric 
660806c3fb27SDimitry Andric   if (const char *Name = C.getTimeTraceFile(&JA)) {
660906c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
661006c3fb27SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
661106c3fb27SDimitry Andric   }
661206c3fb27SDimitry Andric 
66130b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
66140b57cec5SDimitry Andric     CmdArgs.push_back("-ftrapv-handler");
66150b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
66160b57cec5SDimitry Andric   }
66170b57cec5SDimitry Andric 
66180b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
66190b57cec5SDimitry Andric 
66200b57cec5SDimitry Andric   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
66210b57cec5SDimitry Andric   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
66220b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
66230b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fwrapv))
66240b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
66250b57cec5SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
66260b57cec5SDimitry Andric                                       options::OPT_fno_strict_overflow)) {
66270b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_strict_overflow))
66280b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
66290b57cec5SDimitry Andric   }
66300b57cec5SDimitry Andric 
66310b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
66320b57cec5SDimitry Andric                                options::OPT_fno_reroll_loops))
66330b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_freroll_loops))
66340b57cec5SDimitry Andric       CmdArgs.push_back("-freroll-loops");
66350b57cec5SDimitry Andric 
6636d409305fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6637d409305fSDimitry Andric                   options::OPT_fno_finite_loops);
6638d409305fSDimitry Andric 
66390b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
66400b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
66410b57cec5SDimitry Andric                   options::OPT_fno_unroll_loops);
66420b57cec5SDimitry Andric 
6643fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6644fcaf7f86SDimitry Andric 
66450b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pthread);
66460b57cec5SDimitry Andric 
6647bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6648bdd1243dSDimitry Andric                     options::OPT_mno_speculative_load_hardening);
66490b57cec5SDimitry Andric 
6650e8d8bef9SDimitry Andric   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
66515ffd83dbSDimitry Andric   RenderSCPOptions(TC, Args, CmdArgs);
66520b57cec5SDimitry Andric   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
66530b57cec5SDimitry Andric 
6654349cc55cSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6655349cc55cSDimitry Andric 
6656bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6657bdd1243dSDimitry Andric                     options::OPT_mno_stackrealign);
66580b57cec5SDimitry Andric 
66590b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_alignment)) {
66600b57cec5SDimitry Andric     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
66610b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
66620b57cec5SDimitry Andric   }
66630b57cec5SDimitry Andric 
66640b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_probe_size)) {
66650b57cec5SDimitry Andric     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
66660b57cec5SDimitry Andric 
66670b57cec5SDimitry Andric     if (!Size.empty())
66680b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
66690b57cec5SDimitry Andric     else
66700b57cec5SDimitry Andric       CmdArgs.push_back("-mstack-probe-size=0");
66710b57cec5SDimitry Andric   }
66720b57cec5SDimitry Andric 
667381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
667481ad6265SDimitry Andric                      options::OPT_mno_stack_arg_probe);
66750b57cec5SDimitry Andric 
66760b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
66770b57cec5SDimitry Andric                                options::OPT_mno_restrict_it)) {
66780b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mrestrict_it)) {
66790b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
66800b57cec5SDimitry Andric       CmdArgs.push_back("-arm-restrict-it");
66810b57cec5SDimitry Andric     } else {
66820b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
668381ad6265SDimitry Andric       CmdArgs.push_back("-arm-default-it");
66840b57cec5SDimitry Andric     }
66850b57cec5SDimitry Andric   }
66860b57cec5SDimitry Andric 
66870b57cec5SDimitry Andric   // Forward -cl options to -cc1
6688fe6060f1SDimitry Andric   RenderOpenCLOptions(Args, CmdArgs, InputType);
66890b57cec5SDimitry Andric 
669081ad6265SDimitry Andric   // Forward hlsl options to -cc1
669181ad6265SDimitry Andric   RenderHLSLOptions(Args, CmdArgs, InputType);
669281ad6265SDimitry Andric 
66935f757f3fSDimitry Andric   // Forward OpenACC options to -cc1
66945f757f3fSDimitry Andric   RenderOpenACCOptions(D, Args, CmdArgs, InputType);
66955f757f3fSDimitry Andric 
6696e8d8bef9SDimitry Andric   if (IsHIP) {
6697e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
66985ffd83dbSDimitry Andric                      options::OPT_fno_hip_new_launch_api, true))
6699a7dea167SDimitry Andric       CmdArgs.push_back("-fhip-new-launch-api");
67005f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
67015f757f3fSDimitry Andric                       options::OPT_fno_gpu_allow_device_init);
67025f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
67035f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
670481ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
670581ad6265SDimitry Andric                       options::OPT_fno_hip_kernel_arg_name);
6706e8d8bef9SDimitry Andric   }
6707e8d8bef9SDimitry Andric 
6708e8d8bef9SDimitry Andric   if (IsCuda || IsHIP) {
6709753f127fSDimitry Andric     if (IsRDCMode)
6710fe6060f1SDimitry Andric       CmdArgs.push_back("-fgpu-rdc");
67115f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
67125f757f3fSDimitry Andric                       options::OPT_fno_gpu_defer_diag);
6713e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6714e8d8bef9SDimitry Andric                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6715e8d8bef9SDimitry Andric                      false)) {
6716e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6717e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-defer-diag");
6718e8d8bef9SDimitry Andric     }
6719e8d8bef9SDimitry Andric   }
6720a7dea167SDimitry Andric 
672181ad6265SDimitry Andric   // Forward -nogpulib to -cc1.
672281ad6265SDimitry Andric   if (Args.hasArg(options::OPT_nogpulib))
672381ad6265SDimitry Andric     CmdArgs.push_back("-nogpulib");
672481ad6265SDimitry Andric 
67250b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
67260b57cec5SDimitry Andric     CmdArgs.push_back(
67270b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
67280b57cec5SDimitry Andric   }
67290b57cec5SDimitry Andric 
6730753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6731753f127fSDimitry Andric     CmdArgs.push_back(
6732753f127fSDimitry Andric         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6733753f127fSDimitry Andric 
6734bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6735bdd1243dSDimitry Andric 
6736fe6060f1SDimitry Andric   // Forward -f options with positive and negative forms; we translate these by
6737fe6060f1SDimitry Andric   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6738fe6060f1SDimitry Andric   // profile info is for the host-side compilation only.
6739fe6060f1SDimitry Andric   if (!(IsCudaDevice || IsHIPDevice)) {
67400b57cec5SDimitry Andric     if (Arg *A = getLastProfileSampleUseArg(Args)) {
67410b57cec5SDimitry Andric       auto *PGOArg = Args.getLastArg(
67420b57cec5SDimitry Andric           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6743fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate,
6744fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6745fe6060f1SDimitry Andric           options::OPT_fprofile_use_EQ);
67460b57cec5SDimitry Andric       if (PGOArg)
67470b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
67480b57cec5SDimitry Andric             << "SampleUse with PGO options";
67490b57cec5SDimitry Andric 
67500b57cec5SDimitry Andric       StringRef fname = A->getValue();
67510b57cec5SDimitry Andric       if (!llvm::sys::fs::exists(fname))
67520b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << fname;
67530b57cec5SDimitry Andric       else
67540b57cec5SDimitry Andric         A->render(Args, CmdArgs);
67550b57cec5SDimitry Andric     }
67560b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
67570b57cec5SDimitry Andric 
6758e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6759fe6060f1SDimitry Andric                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6760e8d8bef9SDimitry Andric       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6761fe6060f1SDimitry Andric       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6762fe6060f1SDimitry Andric       // off.
6763fe6060f1SDimitry Andric       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6764fe6060f1SDimitry Andric                        options::OPT_fno_unique_internal_linkage_names, true))
6765fe6060f1SDimitry Andric         CmdArgs.push_back("-funique-internal-linkage-names");
6766fe6060f1SDimitry Andric     }
6767fe6060f1SDimitry Andric   }
67680b57cec5SDimitry Andric   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
67690b57cec5SDimitry Andric 
677081ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
677181ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
67720b57cec5SDimitry Andric 
67735f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
67745f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes");
67755f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes_modules,
67765f757f3fSDimitry Andric                    options::OPT_fno_apinotes_modules, false))
67775f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes-modules");
67785f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
67795f757f3fSDimitry Andric 
67800b57cec5SDimitry Andric   // -fblocks=0 is default.
67810b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
67820b57cec5SDimitry Andric                    TC.IsBlocksDefault()) ||
67830b57cec5SDimitry Andric       (Args.hasArg(options::OPT_fgnu_runtime) &&
67840b57cec5SDimitry Andric        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
67850b57cec5SDimitry Andric        !Args.hasArg(options::OPT_fno_blocks))) {
67860b57cec5SDimitry Andric     CmdArgs.push_back("-fblocks");
67870b57cec5SDimitry Andric 
67880b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
67890b57cec5SDimitry Andric       CmdArgs.push_back("-fblocks-runtime-optional");
67900b57cec5SDimitry Andric   }
67910b57cec5SDimitry Andric 
67920b57cec5SDimitry Andric   // -fencode-extended-block-signature=1 is default.
67930b57cec5SDimitry Andric   if (TC.IsEncodeExtendedBlockSignatureDefault())
67940b57cec5SDimitry Andric     CmdArgs.push_back("-fencode-extended-block-signature");
67950b57cec5SDimitry Andric 
6796bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6797bdd1243dSDimitry Andric                    options::OPT_fno_coro_aligned_allocation, false) &&
6798bdd1243dSDimitry Andric       types::isCXX(InputType))
6799bdd1243dSDimitry Andric     CmdArgs.push_back("-fcoro-aligned-allocation");
6800bdd1243dSDimitry Andric 
68010b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
68020b57cec5SDimitry Andric                   options::OPT_fno_double_square_bracket_attributes);
68030b57cec5SDimitry Andric 
680481ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
680581ad6265SDimitry Andric                      options::OPT_fno_access_control);
680681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
680781ad6265SDimitry Andric                      options::OPT_fno_elide_constructors);
68080b57cec5SDimitry Andric 
68090b57cec5SDimitry Andric   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
68100b57cec5SDimitry Andric 
68110b57cec5SDimitry Andric   if (KernelOrKext || (types::isCXX(InputType) &&
68120b57cec5SDimitry Andric                        (RTTIMode == ToolChain::RM_Disabled)))
68130b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti");
68140b57cec5SDimitry Andric 
6815e8d8bef9SDimitry Andric   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
68160b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6817e8d8bef9SDimitry Andric                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
68180b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
68190b57cec5SDimitry Andric 
68200b57cec5SDimitry Andric   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
68210b57cec5SDimitry Andric 
68220b57cec5SDimitry Andric   // -fuse-cxa-atexit is default.
68230b57cec5SDimitry Andric   if (!Args.hasFlag(
68240b57cec5SDimitry Andric           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
68255ffd83dbSDimitry Andric           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
68260b57cec5SDimitry Andric               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
68270b57cec5SDimitry Andric                RawTriple.hasEnvironment())) ||
68280b57cec5SDimitry Andric       KernelOrKext)
68290b57cec5SDimitry Andric     CmdArgs.push_back("-fno-use-cxa-atexit");
68300b57cec5SDimitry Andric 
68310b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
68320b57cec5SDimitry Andric                    options::OPT_fno_register_global_dtors_with_atexit,
68330b57cec5SDimitry Andric                    RawTriple.isOSDarwin() && !KernelOrKext))
68340b57cec5SDimitry Andric     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
68350b57cec5SDimitry Andric 
683681ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
683781ad6265SDimitry Andric                     options::OPT_fno_use_line_directives);
68380b57cec5SDimitry Andric 
6839349cc55cSDimitry Andric   // -fno-minimize-whitespace is default.
6840349cc55cSDimitry Andric   if (Args.hasFlag(options::OPT_fminimize_whitespace,
6841349cc55cSDimitry Andric                    options::OPT_fno_minimize_whitespace, false)) {
6842349cc55cSDimitry Andric     types::ID InputType = Inputs[0].getType();
6843349cc55cSDimitry Andric     if (!isDerivedFromC(InputType))
68445f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
68455f757f3fSDimitry Andric           << "-fminimize-whitespace" << types::getTypeName(InputType);
6846349cc55cSDimitry Andric     CmdArgs.push_back("-fminimize-whitespace");
6847349cc55cSDimitry Andric   }
6848349cc55cSDimitry Andric 
68495f757f3fSDimitry Andric   // -fno-keep-system-includes is default.
68505f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fkeep_system_includes,
68515f757f3fSDimitry Andric                    options::OPT_fno_keep_system_includes, false)) {
68525f757f3fSDimitry Andric     types::ID InputType = Inputs[0].getType();
68535f757f3fSDimitry Andric     if (!isDerivedFromC(InputType))
68545f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
68555f757f3fSDimitry Andric           << "-fkeep-system-includes" << types::getTypeName(InputType);
68565f757f3fSDimitry Andric     CmdArgs.push_back("-fkeep-system-includes");
68575f757f3fSDimitry Andric   }
68585f757f3fSDimitry Andric 
68595ffd83dbSDimitry Andric   // -fms-extensions=0 is default.
68605ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
68615ffd83dbSDimitry Andric                    IsWindowsMSVC))
68625ffd83dbSDimitry Andric     CmdArgs.push_back("-fms-extensions");
68635ffd83dbSDimitry Andric 
68640b57cec5SDimitry Andric   // -fms-compatibility=0 is default.
6865a7dea167SDimitry Andric   bool IsMSVCCompat = Args.hasFlag(
6866a7dea167SDimitry Andric       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6867a7dea167SDimitry Andric       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6868a7dea167SDimitry Andric                                      options::OPT_fno_ms_extensions, true)));
6869a7dea167SDimitry Andric   if (IsMSVCCompat)
68700b57cec5SDimitry Andric     CmdArgs.push_back("-fms-compatibility");
68710b57cec5SDimitry Andric 
6872bdd1243dSDimitry Andric   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6873bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6874bdd1243dSDimitry Andric     ProcessVSRuntimeLibrary(Args, CmdArgs);
6875bdd1243dSDimitry Andric 
6876a7dea167SDimitry Andric   // Handle -fgcc-version, if present.
6877a7dea167SDimitry Andric   VersionTuple GNUCVer;
6878a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6879a7dea167SDimitry Andric     // Check that the version has 1 to 3 components and the minor and patch
6880a7dea167SDimitry Andric     // versions fit in two decimal digits.
6881a7dea167SDimitry Andric     StringRef Val = A->getValue();
6882a7dea167SDimitry Andric     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6883a7dea167SDimitry Andric     bool Invalid = GNUCVer.tryParse(Val);
688481ad6265SDimitry Andric     unsigned Minor = GNUCVer.getMinor().value_or(0);
688581ad6265SDimitry Andric     unsigned Patch = GNUCVer.getSubminor().value_or(0);
6886a7dea167SDimitry Andric     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6887a7dea167SDimitry Andric       D.Diag(diag::err_drv_invalid_value)
6888a7dea167SDimitry Andric           << A->getAsString(Args) << A->getValue();
6889a7dea167SDimitry Andric     }
6890a7dea167SDimitry Andric   } else if (!IsMSVCCompat) {
6891a7dea167SDimitry Andric     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6892a7dea167SDimitry Andric     GNUCVer = VersionTuple(4, 2, 1);
6893a7dea167SDimitry Andric   }
6894a7dea167SDimitry Andric   if (!GNUCVer.empty()) {
6895a7dea167SDimitry Andric     CmdArgs.push_back(
6896a7dea167SDimitry Andric         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6897a7dea167SDimitry Andric   }
6898a7dea167SDimitry Andric 
68990b57cec5SDimitry Andric   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
69000b57cec5SDimitry Andric   if (!MSVT.empty())
69010b57cec5SDimitry Andric     CmdArgs.push_back(
69020b57cec5SDimitry Andric         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
69030b57cec5SDimitry Andric 
69040b57cec5SDimitry Andric   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6905fe6060f1SDimitry Andric   if (ImplyVCPPCVer) {
6906fe6060f1SDimitry Andric     StringRef LanguageStandard;
6907fe6060f1SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6908fe6060f1SDimitry Andric       Std = StdArg;
6909fe6060f1SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6910fe6060f1SDimitry Andric                              .Case("c11", "-std=c11")
6911fe6060f1SDimitry Andric                              .Case("c17", "-std=c17")
6912fe6060f1SDimitry Andric                              .Default("");
6913fe6060f1SDimitry Andric       if (LanguageStandard.empty())
6914fe6060f1SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
6915fe6060f1SDimitry Andric             << StdArg->getAsString(Args);
6916fe6060f1SDimitry Andric     }
6917fe6060f1SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
6918fe6060f1SDimitry Andric   }
69190b57cec5SDimitry Andric   if (ImplyVCPPCXXVer) {
69200b57cec5SDimitry Andric     StringRef LanguageStandard;
69210b57cec5SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
69220b57cec5SDimitry Andric       Std = StdArg;
69230b57cec5SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
69240b57cec5SDimitry Andric                              .Case("c++14", "-std=c++14")
69250b57cec5SDimitry Andric                              .Case("c++17", "-std=c++17")
6926fe6060f1SDimitry Andric                              .Case("c++20", "-std=c++20")
692706c3fb27SDimitry Andric                              // TODO add c++23 and c++26 when MSVC supports it.
692806c3fb27SDimitry Andric                              .Case("c++latest", "-std=c++26")
69290b57cec5SDimitry Andric                              .Default("");
69300b57cec5SDimitry Andric       if (LanguageStandard.empty())
69310b57cec5SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
69320b57cec5SDimitry Andric             << StdArg->getAsString(Args);
69330b57cec5SDimitry Andric     }
69340b57cec5SDimitry Andric 
69350b57cec5SDimitry Andric     if (LanguageStandard.empty()) {
69360b57cec5SDimitry Andric       if (IsMSVC2015Compatible)
69370b57cec5SDimitry Andric         LanguageStandard = "-std=c++14";
69380b57cec5SDimitry Andric       else
69390b57cec5SDimitry Andric         LanguageStandard = "-std=c++11";
69400b57cec5SDimitry Andric     }
69410b57cec5SDimitry Andric 
69420b57cec5SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
69430b57cec5SDimitry Andric   }
69440b57cec5SDimitry Andric 
694581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
694681ad6265SDimitry Andric                     options::OPT_fno_borland_extensions);
69470b57cec5SDimitry Andric 
694881ad6265SDimitry Andric   // -fno-declspec is default, except for PS4/PS5.
69490b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
695081ad6265SDimitry Andric                    RawTriple.isPS()))
69510b57cec5SDimitry Andric     CmdArgs.push_back("-fdeclspec");
69520b57cec5SDimitry Andric   else if (Args.hasArg(options::OPT_fno_declspec))
69530b57cec5SDimitry Andric     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
69540b57cec5SDimitry Andric 
69550b57cec5SDimitry Andric   // -fthreadsafe-static is default, except for MSVC compatibility versions less
69560b57cec5SDimitry Andric   // than 19.
69570b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
69580b57cec5SDimitry Andric                     options::OPT_fno_threadsafe_statics,
6959349cc55cSDimitry Andric                     !types::isOpenCL(InputType) &&
6960349cc55cSDimitry Andric                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
69610b57cec5SDimitry Andric     CmdArgs.push_back("-fno-threadsafe-statics");
69620b57cec5SDimitry Andric 
69630b57cec5SDimitry Andric   // -fgnu-keywords default varies depending on language; only pass if
69640b57cec5SDimitry Andric   // specified.
69650b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
69660b57cec5SDimitry Andric                   options::OPT_fno_gnu_keywords);
69670b57cec5SDimitry Andric 
696881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
696981ad6265SDimitry Andric                     options::OPT_fno_gnu89_inline);
69700b57cec5SDimitry Andric 
697181ad6265SDimitry Andric   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
69720b57cec5SDimitry Andric                                          options::OPT_finline_hint_functions,
69730b57cec5SDimitry Andric                                          options::OPT_fno_inline_functions);
697481ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
697581ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_fno_inline))
697681ad6265SDimitry Andric       A->render(Args, CmdArgs);
697781ad6265SDimitry Andric   } else if (InlineArg) {
697881ad6265SDimitry Andric     InlineArg->render(Args, CmdArgs);
697981ad6265SDimitry Andric   }
69800b57cec5SDimitry Andric 
6981bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6982bdd1243dSDimitry Andric 
69835f757f3fSDimitry Andric   // FIXME: Find a better way to determine whether we are in C++20.
69845f757f3fSDimitry Andric   bool HaveCxx20 =
69855f757f3fSDimitry Andric       Std &&
69865f757f3fSDimitry Andric       (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
69875f757f3fSDimitry Andric        Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
69885f757f3fSDimitry Andric        Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
69895f757f3fSDimitry Andric        Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
69905f757f3fSDimitry Andric        Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
69915f757f3fSDimitry Andric        Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
69925f757f3fSDimitry Andric        Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
69930b57cec5SDimitry Andric   bool HaveModules =
69945f757f3fSDimitry Andric       RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
69955f757f3fSDimitry Andric 
69965f757f3fSDimitry Andric   // -fdelayed-template-parsing is default when targeting MSVC.
69975f757f3fSDimitry Andric   // Many old Windows SDK versions require this to parse.
69985f757f3fSDimitry Andric   //
69995f757f3fSDimitry Andric   // According to
70005f757f3fSDimitry Andric   // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
70015f757f3fSDimitry Andric   // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
70025f757f3fSDimitry Andric   // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
70035f757f3fSDimitry Andric   // not enable -fdelayed-template-parsing by default after C++20.
70045f757f3fSDimitry Andric   //
70055f757f3fSDimitry Andric   // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
70065f757f3fSDimitry Andric   // able to disable this by default at some point.
70075f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
70085f757f3fSDimitry Andric                    options::OPT_fno_delayed_template_parsing,
70095f757f3fSDimitry Andric                    IsWindowsMSVC && !HaveCxx20)) {
70105f757f3fSDimitry Andric     if (HaveCxx20)
70115f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
70125f757f3fSDimitry Andric 
70135f757f3fSDimitry Andric     CmdArgs.push_back("-fdelayed-template-parsing");
70145f757f3fSDimitry Andric   }
70150b57cec5SDimitry Andric 
7016a7dea167SDimitry Andric   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7017a7dea167SDimitry Andric                    options::OPT_fno_pch_validate_input_files_content, false))
7018a7dea167SDimitry Andric     CmdArgs.push_back("-fvalidate-ast-input-files-content");
70195ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
70205ffd83dbSDimitry Andric                    options::OPT_fno_pch_instantiate_templates, false))
70215ffd83dbSDimitry Andric     CmdArgs.push_back("-fpch-instantiate-templates");
7022590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7023590d96feSDimitry Andric                    false))
7024590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-codegen");
7025590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7026590d96feSDimitry Andric                    false))
7027590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-debuginfo");
7028a7dea167SDimitry Andric 
70295ffd83dbSDimitry Andric   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
70300b57cec5SDimitry Andric   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
70310b57cec5SDimitry Andric                     Input, CmdArgs);
70320b57cec5SDimitry Andric 
7033fe6060f1SDimitry Andric   if (types::isObjC(Input.getType()) &&
7034fe6060f1SDimitry Andric       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7035fe6060f1SDimitry Andric                    options::OPT_fno_objc_encode_cxx_class_template_spec,
7036fe6060f1SDimitry Andric                    !Runtime.isNeXTFamily()))
7037fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7038fe6060f1SDimitry Andric 
70390b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fapplication_extension,
70400b57cec5SDimitry Andric                    options::OPT_fno_application_extension, false))
70410b57cec5SDimitry Andric     CmdArgs.push_back("-fapplication-extension");
70420b57cec5SDimitry Andric 
70430b57cec5SDimitry Andric   // Handle GCC-style exception args.
7044fe6060f1SDimitry Andric   bool EH = false;
70450b57cec5SDimitry Andric   if (!C.getDriver().IsCLMode())
7046fe6060f1SDimitry Andric     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
70470b57cec5SDimitry Andric 
70480b57cec5SDimitry Andric   // Handle exception personalities
7049a7dea167SDimitry Andric   Arg *A = Args.getLastArg(
7050a7dea167SDimitry Andric       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7051a7dea167SDimitry Andric       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
70520b57cec5SDimitry Andric   if (A) {
70530b57cec5SDimitry Andric     const Option &Opt = A->getOption();
70540b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fsjlj_exceptions))
7055e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
70560b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fseh_exceptions))
7057e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
70580b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fdwarf_exceptions))
7059e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
7060a7dea167SDimitry Andric     if (Opt.matches(options::OPT_fwasm_exceptions))
7061e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=wasm");
70620b57cec5SDimitry Andric   } else {
70630b57cec5SDimitry Andric     switch (TC.GetExceptionModel(Args)) {
70640b57cec5SDimitry Andric     default:
70650b57cec5SDimitry Andric       break;
70660b57cec5SDimitry Andric     case llvm::ExceptionHandling::DwarfCFI:
7067e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
70680b57cec5SDimitry Andric       break;
70690b57cec5SDimitry Andric     case llvm::ExceptionHandling::SjLj:
7070e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
70710b57cec5SDimitry Andric       break;
70720b57cec5SDimitry Andric     case llvm::ExceptionHandling::WinEH:
7073e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
70740b57cec5SDimitry Andric       break;
70750b57cec5SDimitry Andric     }
70760b57cec5SDimitry Andric   }
70770b57cec5SDimitry Andric 
70780b57cec5SDimitry Andric   // C++ "sane" operator new.
707981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
708081ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
70810b57cec5SDimitry Andric 
708206c3fb27SDimitry Andric   // -fassume-unique-vtables is on by default.
708306c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
708406c3fb27SDimitry Andric                      options::OPT_fno_assume_unique_vtables);
708506c3fb27SDimitry Andric 
70860b57cec5SDimitry Andric   // -frelaxed-template-template-args is off by default, as it is a severe
70870b57cec5SDimitry Andric   // breaking change until a corresponding change to template partial ordering
70880b57cec5SDimitry Andric   // is provided.
708981ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
709081ad6265SDimitry Andric                     options::OPT_fno_relaxed_template_template_args);
70910b57cec5SDimitry Andric 
70920b57cec5SDimitry Andric   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
70930b57cec5SDimitry Andric   // most platforms.
709481ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
709581ad6265SDimitry Andric                     options::OPT_fno_sized_deallocation);
70960b57cec5SDimitry Andric 
70970b57cec5SDimitry Andric   // -faligned-allocation is on by default in C++17 onwards and otherwise off
70980b57cec5SDimitry Andric   // by default.
70990b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
71000b57cec5SDimitry Andric                                options::OPT_fno_aligned_allocation,
71010b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ)) {
71020b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
71030b57cec5SDimitry Andric       CmdArgs.push_back("-fno-aligned-allocation");
71040b57cec5SDimitry Andric     else
71050b57cec5SDimitry Andric       CmdArgs.push_back("-faligned-allocation");
71060b57cec5SDimitry Andric   }
71070b57cec5SDimitry Andric 
71080b57cec5SDimitry Andric   // The default new alignment can be specified using a dedicated option or via
71090b57cec5SDimitry Andric   // a GCC-compatible option that also turns on aligned allocation.
71100b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
71110b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ))
71120b57cec5SDimitry Andric     CmdArgs.push_back(
71130b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
71140b57cec5SDimitry Andric 
71150b57cec5SDimitry Andric   // -fconstant-cfstrings is default, and may be subject to argument translation
71160b57cec5SDimitry Andric   // on Darwin.
71170b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
711881ad6265SDimitry Andric                     options::OPT_fno_constant_cfstrings, true) ||
71190b57cec5SDimitry Andric       !Args.hasFlag(options::OPT_mconstant_cfstrings,
712081ad6265SDimitry Andric                     options::OPT_mno_constant_cfstrings, true))
71210b57cec5SDimitry Andric     CmdArgs.push_back("-fno-constant-cfstrings");
71220b57cec5SDimitry Andric 
712381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
712481ad6265SDimitry Andric                     options::OPT_fno_pascal_strings);
71250b57cec5SDimitry Andric 
71260b57cec5SDimitry Andric   // Honor -fpack-struct= and -fpack-struct, if given. Note that
71270b57cec5SDimitry Andric   // -fno-pack-struct doesn't apply to -fpack-struct=.
71280b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
71290b57cec5SDimitry Andric     std::string PackStructStr = "-fpack-struct=";
71300b57cec5SDimitry Andric     PackStructStr += A->getValue();
71310b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
71320b57cec5SDimitry Andric   } else if (Args.hasFlag(options::OPT_fpack_struct,
71330b57cec5SDimitry Andric                           options::OPT_fno_pack_struct, false)) {
71340b57cec5SDimitry Andric     CmdArgs.push_back("-fpack-struct=1");
71350b57cec5SDimitry Andric   }
71360b57cec5SDimitry Andric 
71370b57cec5SDimitry Andric   // Handle -fmax-type-align=N and -fno-type-align
71380b57cec5SDimitry Andric   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
71390b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
71400b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
71410b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=";
71420b57cec5SDimitry Andric       MaxTypeAlignStr += A->getValue();
71430b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
71440b57cec5SDimitry Andric     }
71450b57cec5SDimitry Andric   } else if (RawTriple.isOSDarwin()) {
71460b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
71470b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=16";
71480b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
71490b57cec5SDimitry Andric     }
71500b57cec5SDimitry Andric   }
71510b57cec5SDimitry Andric 
71520b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
71530b57cec5SDimitry Andric     CmdArgs.push_back("-Qn");
71540b57cec5SDimitry Andric 
71555ffd83dbSDimitry Andric   // -fno-common is the default, set -fcommon only when that flag is set.
715681ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
71570b57cec5SDimitry Andric 
71580b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't yet support
71590b57cec5SDimitry Andric   // -funsigned-bitfields.
71600b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
716181ad6265SDimitry Andric                     options::OPT_funsigned_bitfields, true))
71620b57cec5SDimitry Andric     D.Diag(diag::warn_drv_clang_unsupported)
71630b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
71640b57cec5SDimitry Andric 
71650b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
716681ad6265SDimitry Andric   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
71670b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported)
71680b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
71690b57cec5SDimitry Andric 
71700b57cec5SDimitry Andric   // -finput_charset=UTF-8 is default. Reject others
71710b57cec5SDimitry Andric   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
71720b57cec5SDimitry Andric     StringRef value = inputCharset->getValue();
7173fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
71740b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
71750b57cec5SDimitry Andric                                           << value;
71760b57cec5SDimitry Andric   }
71770b57cec5SDimitry Andric 
71780b57cec5SDimitry Andric   // -fexec_charset=UTF-8 is default. Reject others
71790b57cec5SDimitry Andric   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
71800b57cec5SDimitry Andric     StringRef value = execCharset->getValue();
7181fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
71820b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
71830b57cec5SDimitry Andric                                           << value;
71840b57cec5SDimitry Andric   }
71850b57cec5SDimitry Andric 
71860b57cec5SDimitry Andric   RenderDiagnosticsOptions(D, Args, CmdArgs);
71870b57cec5SDimitry Andric 
718881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
718981ad6265SDimitry Andric                     options::OPT_fno_asm_blocks);
71900b57cec5SDimitry Andric 
7191bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7192bdd1243dSDimitry Andric                      options::OPT_fno_gnu_inline_asm);
71930b57cec5SDimitry Andric 
71940b57cec5SDimitry Andric   // Enable vectorization per default according to the optimization level
71950b57cec5SDimitry Andric   // selected. For optimization levels that want vectorization we use the alias
71960b57cec5SDimitry Andric   // option to simplify the hasFlag logic.
71970b57cec5SDimitry Andric   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
71980b57cec5SDimitry Andric   OptSpecifier VectorizeAliasOption =
71990b57cec5SDimitry Andric       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
72000b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
72010b57cec5SDimitry Andric                    options::OPT_fno_vectorize, EnableVec))
72020b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-loops");
72030b57cec5SDimitry Andric 
72040b57cec5SDimitry Andric   // -fslp-vectorize is enabled based on the optimization level selected.
72050b57cec5SDimitry Andric   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
72060b57cec5SDimitry Andric   OptSpecifier SLPVectAliasOption =
72070b57cec5SDimitry Andric       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
72080b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
72090b57cec5SDimitry Andric                    options::OPT_fno_slp_vectorize, EnableSLPVec))
72100b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-slp");
72110b57cec5SDimitry Andric 
72120b57cec5SDimitry Andric   ParseMPreferVectorWidth(D, Args, CmdArgs);
72130b57cec5SDimitry Andric 
72140b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
72150b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs,
72160b57cec5SDimitry Andric                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric   // -fdollars-in-identifiers default varies depending on platform and
72190b57cec5SDimitry Andric   // language; only pass if specified.
72200b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
72210b57cec5SDimitry Andric                                options::OPT_fno_dollars_in_identifiers)) {
72220b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
72230b57cec5SDimitry Andric       CmdArgs.push_back("-fdollars-in-identifiers");
72240b57cec5SDimitry Andric     else
72250b57cec5SDimitry Andric       CmdArgs.push_back("-fno-dollars-in-identifiers");
72260b57cec5SDimitry Andric   }
72270b57cec5SDimitry Andric 
722881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
722981ad6265SDimitry Andric                     options::OPT_fno_apple_pragma_pack);
72300b57cec5SDimitry Andric 
72310b57cec5SDimitry Andric   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7232480093f4SDimitry Andric   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7233480093f4SDimitry Andric     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
72340b57cec5SDimitry Andric 
72350b57cec5SDimitry Andric   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
72360b57cec5SDimitry Andric                                      options::OPT_fno_rewrite_imports, false);
72370b57cec5SDimitry Andric   if (RewriteImports)
72380b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-imports");
72390b57cec5SDimitry Andric 
7240bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7241bdd1243dSDimitry Andric                     options::OPT_fno_directives_only);
724281ad6265SDimitry Andric 
72430b57cec5SDimitry Andric   // Enable rewrite includes if the user's asked for it or if we're generating
72440b57cec5SDimitry Andric   // diagnostics.
72450b57cec5SDimitry Andric   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
72460b57cec5SDimitry Andric   // nice to enable this when doing a crashdump for modules as well.
72470b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_frewrite_includes,
72480b57cec5SDimitry Andric                    options::OPT_fno_rewrite_includes, false) ||
72490b57cec5SDimitry Andric       (C.isForDiagnostics() && !HaveModules))
72500b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-includes");
72510b57cec5SDimitry Andric 
72520b57cec5SDimitry Andric   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
72530b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_traditional,
72540b57cec5SDimitry Andric                                options::OPT_traditional_cpp)) {
72550b57cec5SDimitry Andric     if (isa<PreprocessJobAction>(JA))
72560b57cec5SDimitry Andric       CmdArgs.push_back("-traditional-cpp");
72570b57cec5SDimitry Andric     else
72580b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
72590b57cec5SDimitry Andric   }
72600b57cec5SDimitry Andric 
72610b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dM);
72620b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dD);
726304eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dI);
72640b57cec5SDimitry Andric 
72655ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
72665ffd83dbSDimitry Andric 
72670b57cec5SDimitry Andric   // Handle serialized diagnostics.
72680b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
72690b57cec5SDimitry Andric     CmdArgs.push_back("-serialize-diagnostic-file");
72700b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
72710b57cec5SDimitry Andric   }
72720b57cec5SDimitry Andric 
72730b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
72740b57cec5SDimitry Andric     CmdArgs.push_back("-fretain-comments-from-system-headers");
72750b57cec5SDimitry Andric 
72760b57cec5SDimitry Andric   // Forward -fcomment-block-commands to -cc1.
72770b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
72780b57cec5SDimitry Andric   // Forward -fparse-all-comments to -cc1.
72790b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
72800b57cec5SDimitry Andric 
72810b57cec5SDimitry Andric   // Turn -fplugin=name.so into -load name.so
72820b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
72830b57cec5SDimitry Andric     CmdArgs.push_back("-load");
72840b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
72850b57cec5SDimitry Andric     A->claim();
72860b57cec5SDimitry Andric   }
72870b57cec5SDimitry Andric 
72884824e7fdSDimitry Andric   // Turn -fplugin-arg-pluginname-key=value into
72894824e7fdSDimitry Andric   // -plugin-arg-pluginname key=value
72904824e7fdSDimitry Andric   // GCC has an actual plugin_argument struct with key/value pairs that it
72914824e7fdSDimitry Andric   // passes to its plugins, but we don't, so just pass it on as-is.
72924824e7fdSDimitry Andric   //
72934824e7fdSDimitry Andric   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
72944824e7fdSDimitry Andric   // argument key are allowed to contain dashes. GCC therefore only
72954824e7fdSDimitry Andric   // allows dashes in the key. We do the same.
72964824e7fdSDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
72974824e7fdSDimitry Andric     auto ArgValue = StringRef(A->getValue());
72984824e7fdSDimitry Andric     auto FirstDashIndex = ArgValue.find('-');
72994824e7fdSDimitry Andric     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
73004824e7fdSDimitry Andric     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
73014824e7fdSDimitry Andric 
73024824e7fdSDimitry Andric     A->claim();
73034824e7fdSDimitry Andric     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
73044824e7fdSDimitry Andric       if (PluginName.empty()) {
73054824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
73064824e7fdSDimitry Andric       } else {
73074824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_arg)
73084824e7fdSDimitry Andric             << PluginName << A->getAsString(Args);
73094824e7fdSDimitry Andric       }
73104824e7fdSDimitry Andric       continue;
73114824e7fdSDimitry Andric     }
73124824e7fdSDimitry Andric 
73134824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
73144824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Arg));
73154824e7fdSDimitry Andric   }
73164824e7fdSDimitry Andric 
73170b57cec5SDimitry Andric   // Forward -fpass-plugin=name.so to -cc1.
73180b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
73190b57cec5SDimitry Andric     CmdArgs.push_back(
73200b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
73210b57cec5SDimitry Andric     A->claim();
73220b57cec5SDimitry Andric   }
73230b57cec5SDimitry Andric 
732406c3fb27SDimitry Andric   // Forward --vfsoverlay to -cc1.
732506c3fb27SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
732606c3fb27SDimitry Andric     CmdArgs.push_back("--vfsoverlay");
732706c3fb27SDimitry Andric     CmdArgs.push_back(A->getValue());
732806c3fb27SDimitry Andric     A->claim();
732906c3fb27SDimitry Andric   }
733006c3fb27SDimitry Andric 
733106c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
733206c3fb27SDimitry Andric                     options::OPT_fno_safe_buffer_usage_suggestions);
733306c3fb27SDimitry Andric 
73340b57cec5SDimitry Andric   // Setup statistics file output.
73350b57cec5SDimitry Andric   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
733606c3fb27SDimitry Andric   if (!StatsFile.empty()) {
73370b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
733806c3fb27SDimitry Andric     if (D.CCPrintInternalStats)
733906c3fb27SDimitry Andric       CmdArgs.push_back("-stats-file-append");
734006c3fb27SDimitry Andric   }
73410b57cec5SDimitry Andric 
73420b57cec5SDimitry Andric   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
73430b57cec5SDimitry Andric   // parser.
7344bdd1243dSDimitry Andric   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7345bdd1243dSDimitry Andric     Arg->claim();
73460b57cec5SDimitry Andric     // -finclude-default-header flag is for preprocessor,
73470b57cec5SDimitry Andric     // do not pass it to other cc1 commands when save-temps is enabled
73480b57cec5SDimitry Andric     if (C.getDriver().isSaveTempsEnabled() &&
73490b57cec5SDimitry Andric         !isa<PreprocessJobAction>(JA)) {
7350bdd1243dSDimitry Andric       if (StringRef(Arg->getValue()) == "-finclude-default-header")
7351bdd1243dSDimitry Andric         continue;
7352bdd1243dSDimitry Andric     }
73530b57cec5SDimitry Andric     CmdArgs.push_back(Arg->getValue());
73540b57cec5SDimitry Andric   }
73550b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
73560b57cec5SDimitry Andric     A->claim();
73570b57cec5SDimitry Andric 
73580b57cec5SDimitry Andric     // We translate this by hand to the -cc1 argument, since nightly test uses
73590b57cec5SDimitry Andric     // it and developers have been trained to spell it with -mllvm. Both
73600b57cec5SDimitry Andric     // spellings are now deprecated and should be removed.
73610b57cec5SDimitry Andric     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
73620b57cec5SDimitry Andric       CmdArgs.push_back("-disable-llvm-optzns");
73630b57cec5SDimitry Andric     } else {
73640b57cec5SDimitry Andric       A->render(Args, CmdArgs);
73650b57cec5SDimitry Andric     }
73660b57cec5SDimitry Andric   }
73670b57cec5SDimitry Andric 
73680b57cec5SDimitry Andric   // With -save-temps, we want to save the unoptimized bitcode output from the
73690b57cec5SDimitry Andric   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
73700b57cec5SDimitry Andric   // by the frontend.
73710b57cec5SDimitry Andric   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
73720b57cec5SDimitry Andric   // has slightly different breakdown between stages.
73730b57cec5SDimitry Andric   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
73740b57cec5SDimitry Andric   // pristine IR generated by the frontend. Ideally, a new compile action should
73750b57cec5SDimitry Andric   // be added so both IR can be captured.
73765ffd83dbSDimitry Andric   if ((C.getDriver().isSaveTempsEnabled() ||
73775ffd83dbSDimitry Andric        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7378fe6060f1SDimitry Andric       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
73790b57cec5SDimitry Andric       isa<CompileJobAction>(JA))
73800b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
73810b57cec5SDimitry Andric 
73820b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_undef);
73830b57cec5SDimitry Andric 
73840b57cec5SDimitry Andric   const char *Exec = D.getClangProgramPath();
73850b57cec5SDimitry Andric 
73860b57cec5SDimitry Andric   // Optionally embed the -cc1 level arguments into the debug info or a
73870b57cec5SDimitry Andric   // section, for build analysis.
73880b57cec5SDimitry Andric   // Also record command line arguments into the debug info if
73890b57cec5SDimitry Andric   // -grecord-gcc-switches options is set on.
73900b57cec5SDimitry Andric   // By default, -gno-record-gcc-switches is set on and no recording.
73910b57cec5SDimitry Andric   auto GRecordSwitches =
73920b57cec5SDimitry Andric       Args.hasFlag(options::OPT_grecord_command_line,
73930b57cec5SDimitry Andric                    options::OPT_gno_record_command_line, false);
73940b57cec5SDimitry Andric   auto FRecordSwitches =
73950b57cec5SDimitry Andric       Args.hasFlag(options::OPT_frecord_command_line,
73960b57cec5SDimitry Andric                    options::OPT_fno_record_command_line, false);
739706c3fb27SDimitry Andric   if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
739806c3fb27SDimitry Andric       !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
73990b57cec5SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt_for_target)
74000b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
74010b57cec5SDimitry Andric         << TripleStr;
74020b57cec5SDimitry Andric   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
74030b57cec5SDimitry Andric     ArgStringList OriginalArgs;
74040b57cec5SDimitry Andric     for (const auto &Arg : Args)
74050b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
74060b57cec5SDimitry Andric 
74070b57cec5SDimitry Andric     SmallString<256> Flags;
74085ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
74090b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
74100b57cec5SDimitry Andric       SmallString<128> EscapedArg;
74110b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
74120b57cec5SDimitry Andric       Flags += " ";
74130b57cec5SDimitry Andric       Flags += EscapedArg;
74140b57cec5SDimitry Andric     }
74150b57cec5SDimitry Andric     auto FlagsArgString = Args.MakeArgString(Flags);
74160b57cec5SDimitry Andric     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
74170b57cec5SDimitry Andric       CmdArgs.push_back("-dwarf-debug-flags");
74180b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
74190b57cec5SDimitry Andric     }
74200b57cec5SDimitry Andric     if (FRecordSwitches) {
74210b57cec5SDimitry Andric       CmdArgs.push_back("-record-command-line");
74220b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
74230b57cec5SDimitry Andric     }
74240b57cec5SDimitry Andric   }
74250b57cec5SDimitry Andric 
7426753f127fSDimitry Andric   // Host-side offloading compilation receives all device-side outputs. Include
7427753f127fSDimitry Andric   // them in the host compilation depending on the target. If the host inputs
7428753f127fSDimitry Andric   // are not empty we use the new-driver scheme, otherwise use the old scheme.
74290b57cec5SDimitry Andric   if ((IsCuda || IsHIP) && CudaDeviceInput) {
74300b57cec5SDimitry Andric     CmdArgs.push_back("-fcuda-include-gpubinary");
74310b57cec5SDimitry Andric     CmdArgs.push_back(CudaDeviceInput->getFilename());
7432753f127fSDimitry Andric   } else if (!HostOffloadingInputs.empty()) {
7433fcaf7f86SDimitry Andric     if ((IsCuda || IsHIP) && !IsRDCMode) {
7434753f127fSDimitry Andric       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7435753f127fSDimitry Andric       CmdArgs.push_back("-fcuda-include-gpubinary");
7436753f127fSDimitry Andric       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7437753f127fSDimitry Andric     } else {
7438753f127fSDimitry Andric       for (const InputInfo Input : HostOffloadingInputs)
7439753f127fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7440753f127fSDimitry Andric                                              TC.getInputFilename(Input)));
7441753f127fSDimitry Andric     }
74420b57cec5SDimitry Andric   }
74430b57cec5SDimitry Andric 
74440b57cec5SDimitry Andric   if (IsCuda) {
74450b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
74460b57cec5SDimitry Andric                      options::OPT_fno_cuda_short_ptr, false))
74470b57cec5SDimitry Andric       CmdArgs.push_back("-fcuda-short-ptr");
74480b57cec5SDimitry Andric   }
74490b57cec5SDimitry Andric 
7450fe6060f1SDimitry Andric   if (IsCuda || IsHIP) {
7451fe6060f1SDimitry Andric     // Determine the original source input.
7452fe6060f1SDimitry Andric     const Action *SourceAction = &JA;
7453fe6060f1SDimitry Andric     while (SourceAction->getKind() != Action::InputClass) {
7454fe6060f1SDimitry Andric       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7455fe6060f1SDimitry Andric       SourceAction = SourceAction->getInputs()[0];
7456fe6060f1SDimitry Andric     }
7457fe6060f1SDimitry Andric     auto CUID = cast<InputAction>(SourceAction)->getId();
7458fe6060f1SDimitry Andric     if (!CUID.empty())
7459fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
74605f757f3fSDimitry Andric 
74615f757f3fSDimitry Andric     // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
74625f757f3fSDimitry Andric     // be overriden by -fno-gpu-approx-transcendentals.
74635f757f3fSDimitry Andric     bool UseApproxTranscendentals = Args.hasFlag(
74645f757f3fSDimitry Andric         options::OPT_ffast_math, options::OPT_fno_fast_math, false);
74655f757f3fSDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
74665f757f3fSDimitry Andric                      options::OPT_fno_gpu_approx_transcendentals,
74675f757f3fSDimitry Andric                      UseApproxTranscendentals))
74685f757f3fSDimitry Andric       CmdArgs.push_back("-fgpu-approx-transcendentals");
74695f757f3fSDimitry Andric   } else {
74705f757f3fSDimitry Andric     Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
74715f757f3fSDimitry Andric                       options::OPT_fno_gpu_approx_transcendentals);
7472fe6060f1SDimitry Andric   }
7473fe6060f1SDimitry Andric 
747481ad6265SDimitry Andric   if (IsHIP) {
7475480093f4SDimitry Andric     CmdArgs.push_back("-fcuda-allow-variadic-functions");
747681ad6265SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
747781ad6265SDimitry Andric   }
7478480093f4SDimitry Andric 
74795f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
74805f757f3fSDimitry Andric                   options::OPT_fno_offload_uniform_block);
74815f757f3fSDimitry Andric 
74825f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
74835f757f3fSDimitry Andric                   options::OPT_fno_offload_implicit_host_device_templates);
74845f757f3fSDimitry Andric 
7485fe6060f1SDimitry Andric   if (IsCudaDevice || IsHIPDevice) {
7486fe6060f1SDimitry Andric     StringRef InlineThresh =
7487fe6060f1SDimitry Andric         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7488fe6060f1SDimitry Andric     if (!InlineThresh.empty()) {
7489fe6060f1SDimitry Andric       std::string ArgStr =
7490fe6060f1SDimitry Andric           std::string("-inline-threshold=") + InlineThresh.str();
7491fe6060f1SDimitry Andric       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7492fe6060f1SDimitry Andric     }
7493fe6060f1SDimitry Andric   }
7494fe6060f1SDimitry Andric 
749506c3fb27SDimitry Andric   if (IsHIPDevice)
749606c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs,
749706c3fb27SDimitry Andric                        options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
749806c3fb27SDimitry Andric                        options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
749906c3fb27SDimitry Andric 
75000b57cec5SDimitry Andric   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
75010b57cec5SDimitry Andric   // to specify the result of the compile phase on the host, so the meaningful
750206c3fb27SDimitry Andric   // device declarations can be identified. Also, -fopenmp-is-target-device is
750306c3fb27SDimitry Andric   // passed along to tell the frontend that it is generating code for a device,
750406c3fb27SDimitry Andric   // so that only the relevant declarations are emitted.
75050b57cec5SDimitry Andric   if (IsOpenMPDevice) {
750606c3fb27SDimitry Andric     CmdArgs.push_back("-fopenmp-is-target-device");
75070b57cec5SDimitry Andric     if (OpenMPDeviceInput) {
75080b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp-host-ir-file-path");
75090b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
75100b57cec5SDimitry Andric     }
75110b57cec5SDimitry Andric   }
75120b57cec5SDimitry Andric 
7513e8d8bef9SDimitry Andric   if (Triple.isAMDGPU()) {
7514e8d8bef9SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7515e8d8bef9SDimitry Andric 
751681ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
751781ad6265SDimitry Andric                       options::OPT_mno_unsafe_fp_atomics);
751806c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
751906c3fb27SDimitry Andric                        options::OPT_mno_amdgpu_ieee);
7520e8d8bef9SDimitry Andric   }
7521e8d8bef9SDimitry Andric 
75220b57cec5SDimitry Andric   // For all the host OpenMP offloading compile jobs we need to pass the targets
75230b57cec5SDimitry Andric   // information using -fopenmp-targets= option.
75240b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
752581ad6265SDimitry Andric     SmallString<128> Targets("-fopenmp-targets=");
75260b57cec5SDimitry Andric 
752781ad6265SDimitry Andric     SmallVector<std::string, 4> Triples;
752881ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
752981ad6265SDimitry Andric     std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
753081ad6265SDimitry Andric                    [](auto TC) { return TC.second->getTripleString(); });
753181ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
75320b57cec5SDimitry Andric   }
75330b57cec5SDimitry Andric 
7534a7dea167SDimitry Andric   bool VirtualFunctionElimination =
7535a7dea167SDimitry Andric       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7536a7dea167SDimitry Andric                    options::OPT_fno_virtual_function_elimination, false);
7537a7dea167SDimitry Andric   if (VirtualFunctionElimination) {
7538a7dea167SDimitry Andric     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7539a7dea167SDimitry Andric     // in the future).
7540fe6060f1SDimitry Andric     if (LTOMode != LTOK_Full)
7541a7dea167SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
7542a7dea167SDimitry Andric           << "-fvirtual-function-elimination"
7543a7dea167SDimitry Andric           << "-flto=full";
7544a7dea167SDimitry Andric 
7545a7dea167SDimitry Andric     CmdArgs.push_back("-fvirtual-function-elimination");
7546a7dea167SDimitry Andric   }
7547a7dea167SDimitry Andric 
7548a7dea167SDimitry Andric   // VFE requires whole-program-vtables, and enables it by default.
7549a7dea167SDimitry Andric   bool WholeProgramVTables = Args.hasFlag(
7550a7dea167SDimitry Andric       options::OPT_fwhole_program_vtables,
7551a7dea167SDimitry Andric       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7552a7dea167SDimitry Andric   if (VirtualFunctionElimination && !WholeProgramVTables) {
7553a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
7554a7dea167SDimitry Andric         << "-fno-whole-program-vtables"
7555a7dea167SDimitry Andric         << "-fvirtual-function-elimination";
7556a7dea167SDimitry Andric   }
7557a7dea167SDimitry Andric 
75580b57cec5SDimitry Andric   if (WholeProgramVTables) {
755906c3fb27SDimitry Andric     // PS4 uses the legacy LTO API, which does not support this feature in
756006c3fb27SDimitry Andric     // ThinLTO mode.
756106c3fb27SDimitry Andric     bool IsPS4 = getToolChain().getTriple().isPS4();
756206c3fb27SDimitry Andric 
7563fe6060f1SDimitry Andric     // Check if we passed LTO options but they were suppressed because this is a
7564fe6060f1SDimitry Andric     // device offloading action, or we passed device offload LTO options which
7565fe6060f1SDimitry Andric     // were suppressed because this is not the device offload action.
756606c3fb27SDimitry Andric     // Check if we are using PS4 in regular LTO mode.
7567fe6060f1SDimitry Andric     // Otherwise, issue an error.
756806c3fb27SDimitry Andric     if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
756906c3fb27SDimitry Andric         (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
75700b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
75710b57cec5SDimitry Andric           << "-fwhole-program-vtables"
757206c3fb27SDimitry Andric           << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
757306c3fb27SDimitry Andric 
757406c3fb27SDimitry Andric     // Propagate -fwhole-program-vtables if this is an LTO compile.
757506c3fb27SDimitry Andric     if (IsUsingLTO)
757606c3fb27SDimitry Andric       CmdArgs.push_back("-fwhole-program-vtables");
75770b57cec5SDimitry Andric   }
75780b57cec5SDimitry Andric 
7579480093f4SDimitry Andric   bool DefaultsSplitLTOUnit =
758006c3fb27SDimitry Andric       ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
758106c3fb27SDimitry Andric           (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
758206c3fb27SDimitry Andric       (!Triple.isPS4() && UnifiedLTO);
75830b57cec5SDimitry Andric   bool SplitLTOUnit =
75840b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_lto_unit,
7585a7dea167SDimitry Andric                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7586349cc55cSDimitry Andric   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7587a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7588a7dea167SDimitry Andric                                                     << "-fsanitize=cfi";
75890b57cec5SDimitry Andric   if (SplitLTOUnit)
75900b57cec5SDimitry Andric     CmdArgs.push_back("-fsplit-lto-unit");
75910b57cec5SDimitry Andric 
75925f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
75935f757f3fSDimitry Andric                                options::OPT_fno_fat_lto_objects)) {
75945f757f3fSDimitry Andric     if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
75955f757f3fSDimitry Andric       assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
75965f757f3fSDimitry Andric       if (!Triple.isOSBinFormatELF()) {
75975f757f3fSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
75985f757f3fSDimitry Andric             << A->getAsString(Args) << TC.getTripleString();
75995f757f3fSDimitry Andric       }
76005f757f3fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
76015f757f3fSDimitry Andric           Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
76025f757f3fSDimitry Andric       CmdArgs.push_back("-flto-unit");
76035f757f3fSDimitry Andric       CmdArgs.push_back("-ffat-lto-objects");
76045f757f3fSDimitry Andric       A->render(Args, CmdArgs);
76055f757f3fSDimitry Andric     }
76065f757f3fSDimitry Andric   }
76075f757f3fSDimitry Andric 
76085ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
76095ffd83dbSDimitry Andric                                options::OPT_fno_global_isel)) {
76100b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
76115ffd83dbSDimitry Andric     if (A->getOption().matches(options::OPT_fglobal_isel)) {
76120b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=1");
76130b57cec5SDimitry Andric 
76140b57cec5SDimitry Andric       // GISel is on by default on AArch64 -O0, so don't bother adding
76150b57cec5SDimitry Andric       // the fallback remarks for it. Other combinations will add a warning of
76160b57cec5SDimitry Andric       // some kind.
76170b57cec5SDimitry Andric       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
76180b57cec5SDimitry Andric       bool IsOptLevelSupported = false;
76190b57cec5SDimitry Andric 
76200b57cec5SDimitry Andric       Arg *A = Args.getLastArg(options::OPT_O_Group);
76210b57cec5SDimitry Andric       if (Triple.getArch() == llvm::Triple::aarch64) {
76220b57cec5SDimitry Andric         if (!A || A->getOption().matches(options::OPT_O0))
76230b57cec5SDimitry Andric           IsOptLevelSupported = true;
76240b57cec5SDimitry Andric       }
76250b57cec5SDimitry Andric       if (!IsArchSupported || !IsOptLevelSupported) {
76260b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
76270b57cec5SDimitry Andric         CmdArgs.push_back("-global-isel-abort=2");
76280b57cec5SDimitry Andric 
76290b57cec5SDimitry Andric         if (!IsArchSupported)
76305ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
76310b57cec5SDimitry Andric         else
76325ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
76330b57cec5SDimitry Andric       }
76340b57cec5SDimitry Andric     } else {
76350b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=0");
76360b57cec5SDimitry Andric     }
76370b57cec5SDimitry Andric   }
76380b57cec5SDimitry Andric 
76390b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
76400b57cec5SDimitry Andric      CmdArgs.push_back("-forder-file-instrumentation");
76410b57cec5SDimitry Andric      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
76420b57cec5SDimitry Andric      // on, we need to pass these flags as linker flags and that will be handled
76430b57cec5SDimitry Andric      // outside of the compiler.
7644fe6060f1SDimitry Andric      if (!IsUsingLTO) {
76450b57cec5SDimitry Andric        CmdArgs.push_back("-mllvm");
76460b57cec5SDimitry Andric        CmdArgs.push_back("-enable-order-file-instrumentation");
76470b57cec5SDimitry Andric      }
76480b57cec5SDimitry Andric   }
76490b57cec5SDimitry Andric 
76500b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
76510b57cec5SDimitry Andric                                options::OPT_fno_force_enable_int128)) {
76520b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fforce_enable_int128))
76530b57cec5SDimitry Andric       CmdArgs.push_back("-fforce-enable-int128");
76540b57cec5SDimitry Andric   }
76550b57cec5SDimitry Andric 
765681ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
765781ad6265SDimitry Andric                     options::OPT_fno_keep_static_consts);
765806c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
765906c3fb27SDimitry Andric                     options::OPT_fno_keep_persistent_storage_variables);
766081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
766181ad6265SDimitry Andric                     options::OPT_fno_complete_member_pointers);
7662bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7663bdd1243dSDimitry Andric                      options::OPT_fno_cxx_static_destructors);
76640b57cec5SDimitry Andric 
7665e8d8bef9SDimitry Andric   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7666e8d8bef9SDimitry Andric 
7667e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7668e8d8bef9SDimitry Andric                                options::OPT_mno_outline_atomics)) {
7669e8d8bef9SDimitry Andric     // Option -moutline-atomics supported for AArch64 target only.
7670e8d8bef9SDimitry Andric     if (!Triple.isAArch64()) {
7671e8d8bef9SDimitry Andric       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
76720eae32dcSDimitry Andric           << Triple.getArchName() << A->getOption().getName();
76730b57cec5SDimitry Andric     } else {
76740eae32dcSDimitry Andric       if (A->getOption().matches(options::OPT_moutline_atomics)) {
7675e8d8bef9SDimitry Andric         CmdArgs.push_back("-target-feature");
7676e8d8bef9SDimitry Andric         CmdArgs.push_back("+outline-atomics");
76770b57cec5SDimitry Andric       } else {
7678e8d8bef9SDimitry Andric         CmdArgs.push_back("-target-feature");
7679e8d8bef9SDimitry Andric         CmdArgs.push_back("-outline-atomics");
76800b57cec5SDimitry Andric       }
76810eae32dcSDimitry Andric     }
7682fe6060f1SDimitry Andric   } else if (Triple.isAArch64() &&
7683fe6060f1SDimitry Andric              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7684fe6060f1SDimitry Andric     CmdArgs.push_back("-target-feature");
7685fe6060f1SDimitry Andric     CmdArgs.push_back("+outline-atomics");
76860b57cec5SDimitry Andric   }
76870b57cec5SDimitry Andric 
7688bdd1243dSDimitry Andric   if (Triple.isAArch64() &&
7689bdd1243dSDimitry Andric       (Args.hasArg(options::OPT_mno_fmv) ||
76905f757f3fSDimitry Andric        (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7691bdd1243dSDimitry Andric        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7692bdd1243dSDimitry Andric     // Disable Function Multiversioning on AArch64 target.
7693bdd1243dSDimitry Andric     CmdArgs.push_back("-target-feature");
7694bdd1243dSDimitry Andric     CmdArgs.push_back("-fmv");
7695bdd1243dSDimitry Andric   }
7696bdd1243dSDimitry Andric 
76970b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
76980b57cec5SDimitry Andric                    (TC.getTriple().isOSBinFormatELF() ||
76990b57cec5SDimitry Andric                     TC.getTriple().isOSBinFormatCOFF()) &&
7700e8d8bef9SDimitry Andric                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
77010b57cec5SDimitry Andric                        !TC.getTriple().isOSNetBSD() &&
7702480093f4SDimitry Andric                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7703e8d8bef9SDimitry Andric                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
77040b57cec5SDimitry Andric     CmdArgs.push_back("-faddrsig");
77050b57cec5SDimitry Andric 
7706fe6060f1SDimitry Andric   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7707bdd1243dSDimitry Andric       (EH || UnwindTables || AsyncUnwindTables ||
770806c3fb27SDimitry Andric        DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7709fe6060f1SDimitry Andric     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7710fe6060f1SDimitry Andric 
77110b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
77120b57cec5SDimitry Andric     std::string Str = A->getAsString(Args);
77130b57cec5SDimitry Andric     if (!TC.getTriple().isOSBinFormatELF())
77140b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
77150b57cec5SDimitry Andric           << Str << TC.getTripleString();
77160b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Str));
77170b57cec5SDimitry Andric   }
77180b57cec5SDimitry Andric 
77190b57cec5SDimitry Andric   // Add the "-o out -x type src.c" flags last. This is done primarily to make
77200b57cec5SDimitry Andric   // the -cc1 command easier to edit when reproducing compiler crashes.
77210b57cec5SDimitry Andric   if (Output.getType() == types::TY_Dependencies) {
77220b57cec5SDimitry Andric     // Handled with other dependency code.
77230b57cec5SDimitry Andric   } else if (Output.isFilename()) {
7724480093f4SDimitry Andric     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7725480093f4SDimitry Andric         Output.getType() == clang::driver::types::TY_IFS) {
7726480093f4SDimitry Andric       SmallString<128> OutputFilename(Output.getFilename());
7727480093f4SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7728480093f4SDimitry Andric       CmdArgs.push_back("-o");
7729480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7730480093f4SDimitry Andric     } else {
77310b57cec5SDimitry Andric       CmdArgs.push_back("-o");
77320b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
7733480093f4SDimitry Andric     }
77340b57cec5SDimitry Andric   } else {
77350b57cec5SDimitry Andric     assert(Output.isNothing() && "Invalid output.");
77360b57cec5SDimitry Andric   }
77370b57cec5SDimitry Andric 
77380b57cec5SDimitry Andric   addDashXForInput(Args, Input, CmdArgs);
77390b57cec5SDimitry Andric 
77400b57cec5SDimitry Andric   ArrayRef<InputInfo> FrontendInputs = Input;
7741bdd1243dSDimitry Andric   if (IsExtractAPI)
774281ad6265SDimitry Andric     FrontendInputs = ExtractAPIInputs;
77430b57cec5SDimitry Andric   else if (Input.isNothing())
77440b57cec5SDimitry Andric     FrontendInputs = {};
77450b57cec5SDimitry Andric 
77460b57cec5SDimitry Andric   for (const InputInfo &Input : FrontendInputs) {
77470b57cec5SDimitry Andric     if (Input.isFilename())
77480b57cec5SDimitry Andric       CmdArgs.push_back(Input.getFilename());
77490b57cec5SDimitry Andric     else
77500b57cec5SDimitry Andric       Input.getInputArg().renderAsInput(Args, CmdArgs);
77510b57cec5SDimitry Andric   }
77520b57cec5SDimitry Andric 
7753fe6060f1SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
7754480093f4SDimitry Andric     // Invoke the CC1 directly in this process
775506c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
775606c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
775706c3fb27SDimitry Andric         Output, D.getPrependArg()));
77580b57cec5SDimitry Andric   } else {
775906c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
776006c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
776106c3fb27SDimitry Andric         Output, D.getPrependArg()));
77620b57cec5SDimitry Andric   }
77630b57cec5SDimitry Andric 
77640b57cec5SDimitry Andric   // Make the compile command echo its inputs for /showFilenames.
77650b57cec5SDimitry Andric   if (Output.getType() == types::TY_Object &&
77660b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_showFilenames,
77670b57cec5SDimitry Andric                    options::OPT__SLASH_showFilenames_, false)) {
776813138422SDimitry Andric     C.getJobs().getJobs().back()->PrintInputFilenames = true;
77690b57cec5SDimitry Andric   }
77700b57cec5SDimitry Andric 
77710b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_pg))
77725ffd83dbSDimitry Andric     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
77735ffd83dbSDimitry Andric         !Args.hasArg(options::OPT_mfentry))
77740b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
77750b57cec5SDimitry Andric                                                       << A->getAsString(Args);
77760b57cec5SDimitry Andric 
77770b57cec5SDimitry Andric   // Claim some arguments which clang supports automatically.
77780b57cec5SDimitry Andric 
77790b57cec5SDimitry Andric   // -fpch-preprocess is used with gcc to add a special marker in the output to
77800b57cec5SDimitry Andric   // include the PCH file.
77810b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
77820b57cec5SDimitry Andric 
77830b57cec5SDimitry Andric   // Claim some arguments which clang doesn't support, but we don't
77840b57cec5SDimitry Andric   // care to warn the user about.
77850b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
77860b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
77870b57cec5SDimitry Andric 
77880b57cec5SDimitry Andric   // Disable warnings for clang -E -emit-llvm foo.c
77890b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
77900b57cec5SDimitry Andric }
77910b57cec5SDimitry Andric 
Clang(const ToolChain & TC,bool HasIntegratedBackend)77920eae32dcSDimitry Andric Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
77930b57cec5SDimitry Andric     // CAUTION! The first constructor argument ("clang") is not arbitrary,
77940b57cec5SDimitry Andric     // as it is for other tools. Some operations on a Tool actually test
77950b57cec5SDimitry Andric     // whether that tool is Clang based on the Tool's Name as a string.
77960eae32dcSDimitry Andric     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
77970b57cec5SDimitry Andric 
~Clang()77980b57cec5SDimitry Andric Clang::~Clang() {}
77990b57cec5SDimitry Andric 
78000b57cec5SDimitry Andric /// Add options related to the Objective-C runtime/ABI.
78010b57cec5SDimitry Andric ///
78020b57cec5SDimitry Andric /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,const InputInfoList & inputs,ArgStringList & cmdArgs,RewriteKind rewriteKind) const78030b57cec5SDimitry Andric ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
78045ffd83dbSDimitry Andric                                       const InputInfoList &inputs,
78050b57cec5SDimitry Andric                                       ArgStringList &cmdArgs,
78060b57cec5SDimitry Andric                                       RewriteKind rewriteKind) const {
78070b57cec5SDimitry Andric   // Look for the controlling runtime option.
78080b57cec5SDimitry Andric   Arg *runtimeArg =
78090b57cec5SDimitry Andric       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
78100b57cec5SDimitry Andric                       options::OPT_fobjc_runtime_EQ);
78110b57cec5SDimitry Andric 
78120b57cec5SDimitry Andric   // Just forward -fobjc-runtime= to the frontend.  This supercedes
78130b57cec5SDimitry Andric   // options about fragility.
78140b57cec5SDimitry Andric   if (runtimeArg &&
78150b57cec5SDimitry Andric       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
78160b57cec5SDimitry Andric     ObjCRuntime runtime;
78170b57cec5SDimitry Andric     StringRef value = runtimeArg->getValue();
78180b57cec5SDimitry Andric     if (runtime.tryParse(value)) {
78190b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
78200b57cec5SDimitry Andric           << value;
78210b57cec5SDimitry Andric     }
78220b57cec5SDimitry Andric     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
78230b57cec5SDimitry Andric         (runtime.getVersion() >= VersionTuple(2, 0)))
78240b57cec5SDimitry Andric       if (!getToolChain().getTriple().isOSBinFormatELF() &&
78250b57cec5SDimitry Andric           !getToolChain().getTriple().isOSBinFormatCOFF()) {
78260b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
78270b57cec5SDimitry Andric             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
78280b57cec5SDimitry Andric           << runtime.getVersion().getMajor();
78290b57cec5SDimitry Andric       }
78300b57cec5SDimitry Andric 
78310b57cec5SDimitry Andric     runtimeArg->render(args, cmdArgs);
78320b57cec5SDimitry Andric     return runtime;
78330b57cec5SDimitry Andric   }
78340b57cec5SDimitry Andric 
78350b57cec5SDimitry Andric   // Otherwise, we'll need the ABI "version".  Version numbers are
78360b57cec5SDimitry Andric   // slightly confusing for historical reasons:
78370b57cec5SDimitry Andric   //   1 - Traditional "fragile" ABI
78380b57cec5SDimitry Andric   //   2 - Non-fragile ABI, version 1
78390b57cec5SDimitry Andric   //   3 - Non-fragile ABI, version 2
78400b57cec5SDimitry Andric   unsigned objcABIVersion = 1;
78410b57cec5SDimitry Andric   // If -fobjc-abi-version= is present, use that to set the version.
78420b57cec5SDimitry Andric   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
78430b57cec5SDimitry Andric     StringRef value = abiArg->getValue();
78440b57cec5SDimitry Andric     if (value == "1")
78450b57cec5SDimitry Andric       objcABIVersion = 1;
78460b57cec5SDimitry Andric     else if (value == "2")
78470b57cec5SDimitry Andric       objcABIVersion = 2;
78480b57cec5SDimitry Andric     else if (value == "3")
78490b57cec5SDimitry Andric       objcABIVersion = 3;
78500b57cec5SDimitry Andric     else
78510b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
78520b57cec5SDimitry Andric   } else {
78530b57cec5SDimitry Andric     // Otherwise, determine if we are using the non-fragile ABI.
78540b57cec5SDimitry Andric     bool nonFragileABIIsDefault =
78550b57cec5SDimitry Andric         (rewriteKind == RK_NonFragile ||
78560b57cec5SDimitry Andric          (rewriteKind == RK_None &&
78570b57cec5SDimitry Andric           getToolChain().IsObjCNonFragileABIDefault()));
78580b57cec5SDimitry Andric     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
78590b57cec5SDimitry Andric                      options::OPT_fno_objc_nonfragile_abi,
78600b57cec5SDimitry Andric                      nonFragileABIIsDefault)) {
78610b57cec5SDimitry Andric // Determine the non-fragile ABI version to use.
78620b57cec5SDimitry Andric #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
78630b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 1;
78640b57cec5SDimitry Andric #else
78650b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 2;
78660b57cec5SDimitry Andric #endif
78670b57cec5SDimitry Andric 
78680b57cec5SDimitry Andric       if (Arg *abiArg =
78690b57cec5SDimitry Andric               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
78700b57cec5SDimitry Andric         StringRef value = abiArg->getValue();
78710b57cec5SDimitry Andric         if (value == "1")
78720b57cec5SDimitry Andric           nonFragileABIVersion = 1;
78730b57cec5SDimitry Andric         else if (value == "2")
78740b57cec5SDimitry Andric           nonFragileABIVersion = 2;
78750b57cec5SDimitry Andric         else
78760b57cec5SDimitry Andric           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
78770b57cec5SDimitry Andric               << value;
78780b57cec5SDimitry Andric       }
78790b57cec5SDimitry Andric 
78800b57cec5SDimitry Andric       objcABIVersion = 1 + nonFragileABIVersion;
78810b57cec5SDimitry Andric     } else {
78820b57cec5SDimitry Andric       objcABIVersion = 1;
78830b57cec5SDimitry Andric     }
78840b57cec5SDimitry Andric   }
78850b57cec5SDimitry Andric 
78860b57cec5SDimitry Andric   // We don't actually care about the ABI version other than whether
78870b57cec5SDimitry Andric   // it's non-fragile.
78880b57cec5SDimitry Andric   bool isNonFragile = objcABIVersion != 1;
78890b57cec5SDimitry Andric 
78900b57cec5SDimitry Andric   // If we have no runtime argument, ask the toolchain for its default runtime.
78910b57cec5SDimitry Andric   // However, the rewriter only really supports the Mac runtime, so assume that.
78920b57cec5SDimitry Andric   ObjCRuntime runtime;
78930b57cec5SDimitry Andric   if (!runtimeArg) {
78940b57cec5SDimitry Andric     switch (rewriteKind) {
78950b57cec5SDimitry Andric     case RK_None:
78960b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
78970b57cec5SDimitry Andric       break;
78980b57cec5SDimitry Andric     case RK_Fragile:
78990b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
79000b57cec5SDimitry Andric       break;
79010b57cec5SDimitry Andric     case RK_NonFragile:
79020b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
79030b57cec5SDimitry Andric       break;
79040b57cec5SDimitry Andric     }
79050b57cec5SDimitry Andric 
79060b57cec5SDimitry Andric     // -fnext-runtime
79070b57cec5SDimitry Andric   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
79080b57cec5SDimitry Andric     // On Darwin, make this use the default behavior for the toolchain.
79090b57cec5SDimitry Andric     if (getToolChain().getTriple().isOSDarwin()) {
79100b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
79110b57cec5SDimitry Andric 
79120b57cec5SDimitry Andric       // Otherwise, build for a generic macosx port.
79130b57cec5SDimitry Andric     } else {
79140b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
79150b57cec5SDimitry Andric     }
79160b57cec5SDimitry Andric 
79170b57cec5SDimitry Andric     // -fgnu-runtime
79180b57cec5SDimitry Andric   } else {
79190b57cec5SDimitry Andric     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
79200b57cec5SDimitry Andric     // Legacy behaviour is to target the gnustep runtime if we are in
79210b57cec5SDimitry Andric     // non-fragile mode or the GCC runtime in fragile mode.
79220b57cec5SDimitry Andric     if (isNonFragile)
79230b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
79240b57cec5SDimitry Andric     else
79250b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
79260b57cec5SDimitry Andric   }
79270b57cec5SDimitry Andric 
79285ffd83dbSDimitry Andric   if (llvm::any_of(inputs, [](const InputInfo &input) {
79295ffd83dbSDimitry Andric         return types::isObjC(input.getType());
79305ffd83dbSDimitry Andric       }))
79310b57cec5SDimitry Andric     cmdArgs.push_back(
79320b57cec5SDimitry Andric         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
79330b57cec5SDimitry Andric   return runtime;
79340b57cec5SDimitry Andric }
79350b57cec5SDimitry Andric 
maybeConsumeDash(const std::string & EH,size_t & I)79360b57cec5SDimitry Andric static bool maybeConsumeDash(const std::string &EH, size_t &I) {
79370b57cec5SDimitry Andric   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
79380b57cec5SDimitry Andric   I += HaveDash;
79390b57cec5SDimitry Andric   return !HaveDash;
79400b57cec5SDimitry Andric }
79410b57cec5SDimitry Andric 
79420b57cec5SDimitry Andric namespace {
79430b57cec5SDimitry Andric struct EHFlags {
79440b57cec5SDimitry Andric   bool Synch = false;
79450b57cec5SDimitry Andric   bool Asynch = false;
79460b57cec5SDimitry Andric   bool NoUnwindC = false;
79470b57cec5SDimitry Andric };
79480b57cec5SDimitry Andric } // end anonymous namespace
79490b57cec5SDimitry Andric 
79500b57cec5SDimitry Andric /// /EH controls whether to run destructor cleanups when exceptions are
79510b57cec5SDimitry Andric /// thrown.  There are three modifiers:
79520b57cec5SDimitry Andric /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
79530b57cec5SDimitry Andric /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
79540b57cec5SDimitry Andric ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
79550b57cec5SDimitry Andric /// - c: Assume that extern "C" functions are implicitly nounwind.
79560b57cec5SDimitry Andric /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)79570b57cec5SDimitry Andric static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
79580b57cec5SDimitry Andric   EHFlags EH;
79590b57cec5SDimitry Andric 
79600b57cec5SDimitry Andric   std::vector<std::string> EHArgs =
79610b57cec5SDimitry Andric       Args.getAllArgValues(options::OPT__SLASH_EH);
79620b57cec5SDimitry Andric   for (auto EHVal : EHArgs) {
79630b57cec5SDimitry Andric     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
79640b57cec5SDimitry Andric       switch (EHVal[I]) {
79650b57cec5SDimitry Andric       case 'a':
79660b57cec5SDimitry Andric         EH.Asynch = maybeConsumeDash(EHVal, I);
79670b57cec5SDimitry Andric         if (EH.Asynch)
79680b57cec5SDimitry Andric           EH.Synch = false;
79690b57cec5SDimitry Andric         continue;
79700b57cec5SDimitry Andric       case 'c':
79710b57cec5SDimitry Andric         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
79720b57cec5SDimitry Andric         continue;
79730b57cec5SDimitry Andric       case 's':
79740b57cec5SDimitry Andric         EH.Synch = maybeConsumeDash(EHVal, I);
79750b57cec5SDimitry Andric         if (EH.Synch)
79760b57cec5SDimitry Andric           EH.Asynch = false;
79770b57cec5SDimitry Andric         continue;
79780b57cec5SDimitry Andric       default:
79790b57cec5SDimitry Andric         break;
79800b57cec5SDimitry Andric       }
79810b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
79820b57cec5SDimitry Andric       break;
79830b57cec5SDimitry Andric     }
79840b57cec5SDimitry Andric   }
79850b57cec5SDimitry Andric   // The /GX, /GX- flags are only processed if there are not /EH flags.
79860b57cec5SDimitry Andric   // The default is that /GX is not specified.
79870b57cec5SDimitry Andric   if (EHArgs.empty() &&
79880b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
79890b57cec5SDimitry Andric                    /*Default=*/false)) {
79900b57cec5SDimitry Andric     EH.Synch = true;
79910b57cec5SDimitry Andric     EH.NoUnwindC = true;
79920b57cec5SDimitry Andric   }
79930b57cec5SDimitry Andric 
799481ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel)) {
799581ad6265SDimitry Andric     EH.Synch = false;
799681ad6265SDimitry Andric     EH.NoUnwindC = false;
799781ad6265SDimitry Andric     EH.Asynch = false;
799881ad6265SDimitry Andric   }
799981ad6265SDimitry Andric 
80000b57cec5SDimitry Andric   return EH;
80010b57cec5SDimitry Andric }
80020b57cec5SDimitry Andric 
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs) const80030b57cec5SDimitry Andric void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
80045f757f3fSDimitry Andric                            ArgStringList &CmdArgs) const {
80055ffd83dbSDimitry Andric   bool isNVPTX = getToolChain().getTriple().isNVPTX();
80060b57cec5SDimitry Andric 
8007bdd1243dSDimitry Andric   ProcessVSRuntimeLibrary(Args, CmdArgs);
80080b57cec5SDimitry Andric 
80095ffd83dbSDimitry Andric   if (Arg *ShowIncludes =
80105ffd83dbSDimitry Andric           Args.getLastArg(options::OPT__SLASH_showIncludes,
80115ffd83dbSDimitry Andric                           options::OPT__SLASH_showIncludes_user)) {
80125ffd83dbSDimitry Andric     CmdArgs.push_back("--show-includes");
80135ffd83dbSDimitry Andric     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
80145ffd83dbSDimitry Andric       CmdArgs.push_back("-sys-header-deps");
80155ffd83dbSDimitry Andric   }
80160b57cec5SDimitry Andric 
80170b57cec5SDimitry Andric   // This controls whether or not we emit RTTI data for polymorphic types.
80180b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
80190b57cec5SDimitry Andric                    /*Default=*/false))
80200b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti-data");
80210b57cec5SDimitry Andric 
80220b57cec5SDimitry Andric   // This controls whether or not we emit stack-protector instrumentation.
80230b57cec5SDimitry Andric   // In MSVC, Buffer Security Check (/GS) is on by default.
80245ffd83dbSDimitry Andric   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
80250b57cec5SDimitry Andric                                /*Default=*/true)) {
80260b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
80270b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
80280b57cec5SDimitry Andric   }
80290b57cec5SDimitry Andric 
80300b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
803181ad6265SDimitry Andric 
80320b57cec5SDimitry Andric   EHFlags EH = parseClangCLEHFlags(D, Args);
80335ffd83dbSDimitry Andric   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
80340b57cec5SDimitry Andric     if (types::isCXX(InputType))
80350b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
80360b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
803706c3fb27SDimitry Andric     if (EH.Asynch)
803806c3fb27SDimitry Andric       CmdArgs.push_back("-fasync-exceptions");
80390b57cec5SDimitry Andric   }
80400b57cec5SDimitry Andric   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
80410b57cec5SDimitry Andric     CmdArgs.push_back("-fexternc-nounwind");
80420b57cec5SDimitry Andric 
80430b57cec5SDimitry Andric   // /EP should expand to -E -P.
80440b57cec5SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_EP)) {
80450b57cec5SDimitry Andric     CmdArgs.push_back("-E");
80460b57cec5SDimitry Andric     CmdArgs.push_back("-P");
80470b57cec5SDimitry Andric   }
80480b57cec5SDimitry Andric 
80490b57cec5SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
80500b57cec5SDimitry Andric                   options::OPT__SLASH_Zc_dllexportInlines,
80510b57cec5SDimitry Andric                   false)) {
80520b57cec5SDimitry Andric   CmdArgs.push_back("-fno-dllexport-inlines");
80530b57cec5SDimitry Andric  }
80540b57cec5SDimitry Andric 
805581ad6265SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
805681ad6265SDimitry Andric                   options::OPT__SLASH_Zc_wchar_t, false)) {
805781ad6265SDimitry Andric    CmdArgs.push_back("-fno-wchar");
805881ad6265SDimitry Andric  }
805981ad6265SDimitry Andric 
806081ad6265SDimitry Andric  if (Args.hasArg(options::OPT__SLASH_kernel)) {
806181ad6265SDimitry Andric    llvm::Triple::ArchType Arch = getToolChain().getArch();
806281ad6265SDimitry Andric    std::vector<std::string> Values =
806381ad6265SDimitry Andric        Args.getAllArgValues(options::OPT__SLASH_arch);
806481ad6265SDimitry Andric    if (!Values.empty()) {
806581ad6265SDimitry Andric      llvm::SmallSet<std::string, 4> SupportedArches;
806681ad6265SDimitry Andric      if (Arch == llvm::Triple::x86)
806781ad6265SDimitry Andric        SupportedArches.insert("IA32");
806881ad6265SDimitry Andric 
806981ad6265SDimitry Andric      for (auto &V : Values)
807081ad6265SDimitry Andric        if (!SupportedArches.contains(V))
807181ad6265SDimitry Andric          D.Diag(diag::err_drv_argument_not_allowed_with)
807281ad6265SDimitry Andric              << std::string("/arch:").append(V) << "/kernel";
807381ad6265SDimitry Andric    }
807481ad6265SDimitry Andric 
807581ad6265SDimitry Andric    CmdArgs.push_back("-fno-rtti");
807681ad6265SDimitry Andric    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
807781ad6265SDimitry Andric      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
807881ad6265SDimitry Andric                                                      << "/kernel";
807981ad6265SDimitry Andric  }
808081ad6265SDimitry Andric 
80810b57cec5SDimitry Andric   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
80820b57cec5SDimitry Andric   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
80830b57cec5SDimitry Andric   if (MostGeneralArg && BestCaseArg)
80840b57cec5SDimitry Andric     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
80850b57cec5SDimitry Andric         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
80860b57cec5SDimitry Andric 
80870b57cec5SDimitry Andric   if (MostGeneralArg) {
80880b57cec5SDimitry Andric     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
80890b57cec5SDimitry Andric     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
80900b57cec5SDimitry Andric     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
80910b57cec5SDimitry Andric 
80920b57cec5SDimitry Andric     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
80930b57cec5SDimitry Andric     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
80940b57cec5SDimitry Andric     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
80950b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
80960b57cec5SDimitry Andric           << FirstConflict->getAsString(Args)
80970b57cec5SDimitry Andric           << SecondConflict->getAsString(Args);
80980b57cec5SDimitry Andric 
80990b57cec5SDimitry Andric     if (SingleArg)
81000b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=single");
81010b57cec5SDimitry Andric     else if (MultipleArg)
81020b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=multiple");
81030b57cec5SDimitry Andric     else
81040b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=virtual");
81050b57cec5SDimitry Andric   }
81060b57cec5SDimitry Andric 
81075f757f3fSDimitry Andric   if (Args.hasArg(options::OPT_regcall4))
81085f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
81095f757f3fSDimitry Andric 
81100b57cec5SDimitry Andric   // Parse the default calling convention options.
81110b57cec5SDimitry Andric   if (Arg *CCArg =
81120b57cec5SDimitry Andric           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
81130b57cec5SDimitry Andric                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
81140b57cec5SDimitry Andric                           options::OPT__SLASH_Gregcall)) {
81150b57cec5SDimitry Andric     unsigned DCCOptId = CCArg->getOption().getID();
81160b57cec5SDimitry Andric     const char *DCCFlag = nullptr;
81175ffd83dbSDimitry Andric     bool ArchSupported = !isNVPTX;
81180b57cec5SDimitry Andric     llvm::Triple::ArchType Arch = getToolChain().getArch();
81190b57cec5SDimitry Andric     switch (DCCOptId) {
81200b57cec5SDimitry Andric     case options::OPT__SLASH_Gd:
81210b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=cdecl";
81220b57cec5SDimitry Andric       break;
81230b57cec5SDimitry Andric     case options::OPT__SLASH_Gr:
81240b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
81250b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=fastcall";
81260b57cec5SDimitry Andric       break;
81270b57cec5SDimitry Andric     case options::OPT__SLASH_Gz:
81280b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
81290b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=stdcall";
81300b57cec5SDimitry Andric       break;
81310b57cec5SDimitry Andric     case options::OPT__SLASH_Gv:
81320b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
81330b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=vectorcall";
81340b57cec5SDimitry Andric       break;
81350b57cec5SDimitry Andric     case options::OPT__SLASH_Gregcall:
81360b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
81370b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=regcall";
81380b57cec5SDimitry Andric       break;
81390b57cec5SDimitry Andric     }
81400b57cec5SDimitry Andric 
81410b57cec5SDimitry Andric     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
81420b57cec5SDimitry Andric     if (ArchSupported && DCCFlag)
81430b57cec5SDimitry Andric       CmdArgs.push_back(DCCFlag);
81440b57cec5SDimitry Andric   }
81450b57cec5SDimitry Andric 
81465f757f3fSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_Gregcall4))
81475f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
81485f757f3fSDimitry Andric 
81490b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
81500b57cec5SDimitry Andric 
81510b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
81520b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
81530b57cec5SDimitry Andric     CmdArgs.push_back("msvc");
81540b57cec5SDimitry Andric   }
81550b57cec5SDimitry Andric 
815681ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel))
815781ad6265SDimitry Andric     CmdArgs.push_back("-fms-kernel");
815881ad6265SDimitry Andric 
8159a324c340SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8160480093f4SDimitry Andric     StringRef GuardArgs = A->getValue();
8161fe6060f1SDimitry Andric     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8162fe6060f1SDimitry Andric     // "ehcont-".
8163fe6060f1SDimitry Andric     if (GuardArgs.equals_insensitive("cf")) {
8164480093f4SDimitry Andric       // Emit CFG instrumentation and the table of address-taken functions.
81650b57cec5SDimitry Andric       CmdArgs.push_back("-cfguard");
8166fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8167480093f4SDimitry Andric       // Emit only the table of address-taken functions.
8168480093f4SDimitry Andric       CmdArgs.push_back("-cfguard-no-checks");
8169fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("ehcont")) {
8170fe6060f1SDimitry Andric       // Emit EH continuation table.
8171fe6060f1SDimitry Andric       CmdArgs.push_back("-ehcontguard");
8172fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf-") ||
8173fe6060f1SDimitry Andric                GuardArgs.equals_insensitive("ehcont-")) {
8174480093f4SDimitry Andric       // Do nothing, but we might want to emit a security warning in future.
8175480093f4SDimitry Andric     } else {
8176480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8177480093f4SDimitry Andric     }
81782efbaac7SDimitry Andric     A->claim();
81790b57cec5SDimitry Andric   }
81800b57cec5SDimitry Andric }
81810b57cec5SDimitry Andric 
getBaseInputName(const ArgList & Args,const InputInfo & Input)81820b57cec5SDimitry Andric const char *Clang::getBaseInputName(const ArgList &Args,
81830b57cec5SDimitry Andric                                     const InputInfo &Input) {
81840b57cec5SDimitry Andric   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
81850b57cec5SDimitry Andric }
81860b57cec5SDimitry Andric 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)81870b57cec5SDimitry Andric const char *Clang::getBaseInputStem(const ArgList &Args,
81880b57cec5SDimitry Andric                                     const InputInfoList &Inputs) {
81890b57cec5SDimitry Andric   const char *Str = getBaseInputName(Args, Inputs[0]);
81900b57cec5SDimitry Andric 
81910b57cec5SDimitry Andric   if (const char *End = strrchr(Str, '.'))
81920b57cec5SDimitry Andric     return Args.MakeArgString(std::string(Str, End));
81930b57cec5SDimitry Andric 
81940b57cec5SDimitry Andric   return Str;
81950b57cec5SDimitry Andric }
81960b57cec5SDimitry Andric 
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)81970b57cec5SDimitry Andric const char *Clang::getDependencyFileName(const ArgList &Args,
81980b57cec5SDimitry Andric                                          const InputInfoList &Inputs) {
81990b57cec5SDimitry Andric   // FIXME: Think about this more.
82000b57cec5SDimitry Andric 
82010b57cec5SDimitry Andric   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8202a7dea167SDimitry Andric     SmallString<128> OutputFilename(OutputOpt->getValue());
8203a7dea167SDimitry Andric     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8204a7dea167SDimitry Andric     return Args.MakeArgString(OutputFilename);
82050b57cec5SDimitry Andric   }
8206a7dea167SDimitry Andric 
8207a7dea167SDimitry Andric   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
82080b57cec5SDimitry Andric }
82090b57cec5SDimitry Andric 
82100b57cec5SDimitry Andric // Begin ClangAs
82110b57cec5SDimitry Andric 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const82120b57cec5SDimitry Andric void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
82130b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
82140b57cec5SDimitry Andric   StringRef CPUName;
82150b57cec5SDimitry Andric   StringRef ABIName;
82160b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
82170b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
82180b57cec5SDimitry Andric 
82190b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
82200b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
82210b57cec5SDimitry Andric }
82220b57cec5SDimitry Andric 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const82230b57cec5SDimitry Andric void ClangAs::AddX86TargetArgs(const ArgList &Args,
82240b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
82255ffd83dbSDimitry Andric   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
82265ffd83dbSDimitry Andric                         /*IsLTO=*/false);
8227480093f4SDimitry Andric 
82280b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
82290b57cec5SDimitry Andric     StringRef Value = A->getValue();
82300b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
82310b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
82320b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
82330b57cec5SDimitry Andric     } else {
82340b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8235bdd1243dSDimitry Andric           << A->getSpelling() << Value;
82360b57cec5SDimitry Andric     }
82370b57cec5SDimitry Andric   }
82380b57cec5SDimitry Andric }
82390b57cec5SDimitry Andric 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const824006c3fb27SDimitry Andric void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
824106c3fb27SDimitry Andric                                      ArgStringList &CmdArgs) const {
824206c3fb27SDimitry Andric   CmdArgs.push_back("-target-abi");
824306c3fb27SDimitry Andric   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
824406c3fb27SDimitry Andric                                                getToolChain().getTriple())
824506c3fb27SDimitry Andric                         .data());
824606c3fb27SDimitry Andric }
824706c3fb27SDimitry Andric 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const82480b57cec5SDimitry Andric void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
82490b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
82500b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
82510b57cec5SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
82520b57cec5SDimitry Andric 
82530b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
82540b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
825506c3fb27SDimitry Andric 
825606c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_mdefault_build_attributes,
825706c3fb27SDimitry Andric                    options::OPT_mno_default_build_attributes, true)) {
825806c3fb27SDimitry Andric       CmdArgs.push_back("-mllvm");
825906c3fb27SDimitry Andric       CmdArgs.push_back("-riscv-add-build-attributes");
826006c3fb27SDimitry Andric   }
82610b57cec5SDimitry Andric }
82620b57cec5SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const82630b57cec5SDimitry Andric void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
82640b57cec5SDimitry Andric                            const InputInfo &Output, const InputInfoList &Inputs,
82650b57cec5SDimitry Andric                            const ArgList &Args,
82660b57cec5SDimitry Andric                            const char *LinkingOutput) const {
82670b57cec5SDimitry Andric   ArgStringList CmdArgs;
82680b57cec5SDimitry Andric 
82690b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
82700b57cec5SDimitry Andric   const InputInfo &Input = Inputs[0];
82710b57cec5SDimitry Andric 
82720b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
82730b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
82740b57cec5SDimitry Andric   const auto &D = getToolChain().getDriver();
82750b57cec5SDimitry Andric 
82760b57cec5SDimitry Andric   // Don't warn about "clang -w -c foo.s"
82770b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_w);
82780b57cec5SDimitry Andric   // and "clang -emit-llvm -c foo.s"
82790b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
82800b57cec5SDimitry Andric 
82810b57cec5SDimitry Andric   claimNoWarnArgs(Args);
82820b57cec5SDimitry Andric 
82830b57cec5SDimitry Andric   // Invoke ourselves in -cc1as mode.
82840b57cec5SDimitry Andric   //
82850b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
82860b57cec5SDimitry Andric   CmdArgs.push_back("-cc1as");
82870b57cec5SDimitry Andric 
82880b57cec5SDimitry Andric   // Add the "effective" target triple.
82890b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
82900b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
8291bdd1243dSDimitry Andric 
8292bdd1243dSDimitry Andric   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
82930b57cec5SDimitry Andric 
82940b57cec5SDimitry Andric   // Set the output mode, we currently only expect to be used as a real
82950b57cec5SDimitry Andric   // assembler.
82960b57cec5SDimitry Andric   CmdArgs.push_back("-filetype");
82970b57cec5SDimitry Andric   CmdArgs.push_back("obj");
82980b57cec5SDimitry Andric 
82990b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
83000b57cec5SDimitry Andric   // -save-temps or preprocessed assembly.
83010b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
83020b57cec5SDimitry Andric   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
83030b57cec5SDimitry Andric 
83040b57cec5SDimitry Andric   // Add the target cpu
8305349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
83060b57cec5SDimitry Andric   if (!CPU.empty()) {
83070b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
83080b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
83090b57cec5SDimitry Andric   }
83100b57cec5SDimitry Andric 
83110b57cec5SDimitry Andric   // Add the target features
83125ffd83dbSDimitry Andric   getTargetFeatures(D, Triple, Args, CmdArgs, true);
83130b57cec5SDimitry Andric 
83140b57cec5SDimitry Andric   // Ignore explicit -force_cpusubtype_ALL option.
83150b57cec5SDimitry Andric   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
83160b57cec5SDimitry Andric 
83170b57cec5SDimitry Andric   // Pass along any -I options so we get proper .include search paths.
83180b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
83190b57cec5SDimitry Andric 
83200b57cec5SDimitry Andric   // Determine the original source input.
83210eae32dcSDimitry Andric   auto FindSource = [](const Action *S) -> const Action * {
83220eae32dcSDimitry Andric     while (S->getKind() != Action::InputClass) {
83230eae32dcSDimitry Andric       assert(!S->getInputs().empty() && "unexpected root action!");
83240eae32dcSDimitry Andric       S = S->getInputs()[0];
83250b57cec5SDimitry Andric     }
83260eae32dcSDimitry Andric     return S;
83270eae32dcSDimitry Andric   };
83280eae32dcSDimitry Andric   const Action *SourceAction = FindSource(&JA);
83290b57cec5SDimitry Andric 
83300b57cec5SDimitry Andric   // Forward -g and handle debug info related flags, assuming we are dealing
83310b57cec5SDimitry Andric   // with an actual assembly file.
83320b57cec5SDimitry Andric   bool WantDebug = false;
83330b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_Group);
8334fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
83350b57cec5SDimitry Andric     WantDebug = !A->getOption().matches(options::OPT_g0) &&
83360b57cec5SDimitry Andric                 !A->getOption().matches(options::OPT_ggdb0);
8337480093f4SDimitry Andric 
833806c3fb27SDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
833906c3fb27SDimitry Andric       llvm::codegenoptions::NoDebugInfo;
83400b57cec5SDimitry Andric 
83410eae32dcSDimitry Andric   // Add the -fdebug-compilation-dir flag if needed.
83420eae32dcSDimitry Andric   const char *DebugCompilationDir =
83430eae32dcSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
83440eae32dcSDimitry Andric 
83450b57cec5SDimitry Andric   if (SourceAction->getType() == types::TY_Asm ||
83460b57cec5SDimitry Andric       SourceAction->getType() == types::TY_PP_Asm) {
83470b57cec5SDimitry Andric     // You might think that it would be ok to set DebugInfoKind outside of
83480b57cec5SDimitry Andric     // the guard for source type, however there is a test which asserts
83490b57cec5SDimitry Andric     // that some assembler invocation receives no -debug-info-kind,
83500b57cec5SDimitry Andric     // and it's not clear whether that test is just overly restrictive.
835106c3fb27SDimitry Andric     DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
835206c3fb27SDimitry Andric                                : llvm::codegenoptions::NoDebugInfo);
83530b57cec5SDimitry Andric 
835481ad6265SDimitry Andric     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
835581ad6265SDimitry Andric                          CmdArgs);
83560b57cec5SDimitry Andric 
83570b57cec5SDimitry Andric     // Set the AT_producer to the clang version when using the integrated
83580b57cec5SDimitry Andric     // assembler on assembly source files.
83590b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-producer");
83600b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
83610b57cec5SDimitry Andric 
83620b57cec5SDimitry Andric     // And pass along -I options
83630b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_I);
83640b57cec5SDimitry Andric   }
8365bdd1243dSDimitry Andric   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
83660b57cec5SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
83670b57cec5SDimitry Andric                           llvm::DebuggerKind::Default);
8368fe6060f1SDimitry Andric   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
83690b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
83700b57cec5SDimitry Andric 
83710b57cec5SDimitry Andric   // Handle -fPIC et al -- the relocation-model affects the assembler
83720b57cec5SDimitry Andric   // for some targets.
83730b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
83740b57cec5SDimitry Andric   unsigned PICLevel;
83750b57cec5SDimitry Andric   bool IsPIE;
83760b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
83770b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
83780b57cec5SDimitry Andric 
83790b57cec5SDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
83800b57cec5SDimitry Andric   if (RMName) {
83810b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
83820b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
83830b57cec5SDimitry Andric   }
83840b57cec5SDimitry Andric 
83850b57cec5SDimitry Andric   // Optionally embed the -cc1as level arguments into the debug info, for build
83860b57cec5SDimitry Andric   // analysis.
83870b57cec5SDimitry Andric   if (getToolChain().UseDwarfDebugFlags()) {
83880b57cec5SDimitry Andric     ArgStringList OriginalArgs;
83890b57cec5SDimitry Andric     for (const auto &Arg : Args)
83900b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
83910b57cec5SDimitry Andric 
83920b57cec5SDimitry Andric     SmallString<256> Flags;
83930b57cec5SDimitry Andric     const char *Exec = getToolChain().getDriver().getClangProgramPath();
83945ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
83950b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
83960b57cec5SDimitry Andric       SmallString<128> EscapedArg;
83970b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
83980b57cec5SDimitry Andric       Flags += " ";
83990b57cec5SDimitry Andric       Flags += EscapedArg;
84000b57cec5SDimitry Andric     }
84010b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-flags");
84020b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Flags));
84030b57cec5SDimitry Andric   }
84040b57cec5SDimitry Andric 
84050b57cec5SDimitry Andric   // FIXME: Add -static support, once we have it.
84060b57cec5SDimitry Andric 
84070b57cec5SDimitry Andric   // Add target specific flags.
84080b57cec5SDimitry Andric   switch (getToolChain().getArch()) {
84090b57cec5SDimitry Andric   default:
84100b57cec5SDimitry Andric     break;
84110b57cec5SDimitry Andric 
84120b57cec5SDimitry Andric   case llvm::Triple::mips:
84130b57cec5SDimitry Andric   case llvm::Triple::mipsel:
84140b57cec5SDimitry Andric   case llvm::Triple::mips64:
84150b57cec5SDimitry Andric   case llvm::Triple::mips64el:
84160b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
84170b57cec5SDimitry Andric     break;
84180b57cec5SDimitry Andric 
84190b57cec5SDimitry Andric   case llvm::Triple::x86:
84200b57cec5SDimitry Andric   case llvm::Triple::x86_64:
84210b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
84220b57cec5SDimitry Andric     break;
84230b57cec5SDimitry Andric 
84240b57cec5SDimitry Andric   case llvm::Triple::arm:
84250b57cec5SDimitry Andric   case llvm::Triple::armeb:
84260b57cec5SDimitry Andric   case llvm::Triple::thumb:
84270b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
84280b57cec5SDimitry Andric     // This isn't in AddARMTargetArgs because we want to do this for assembly
84290b57cec5SDimitry Andric     // only, not C/C++.
84300b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
84310b57cec5SDimitry Andric                      options::OPT_mno_default_build_attributes, true)) {
84320b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
84330b57cec5SDimitry Andric         CmdArgs.push_back("-arm-add-build-attributes");
84340b57cec5SDimitry Andric     }
84350b57cec5SDimitry Andric     break;
84360b57cec5SDimitry Andric 
8437e8d8bef9SDimitry Andric   case llvm::Triple::aarch64:
8438e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_32:
8439e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_be:
8440e8d8bef9SDimitry Andric     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8441e8d8bef9SDimitry Andric       CmdArgs.push_back("-mllvm");
8442e8d8bef9SDimitry Andric       CmdArgs.push_back("-aarch64-mark-bti-property");
8443e8d8bef9SDimitry Andric     }
8444e8d8bef9SDimitry Andric     break;
8445e8d8bef9SDimitry Andric 
844606c3fb27SDimitry Andric   case llvm::Triple::loongarch32:
844706c3fb27SDimitry Andric   case llvm::Triple::loongarch64:
844806c3fb27SDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
844906c3fb27SDimitry Andric     break;
845006c3fb27SDimitry Andric 
84510b57cec5SDimitry Andric   case llvm::Triple::riscv32:
84520b57cec5SDimitry Andric   case llvm::Triple::riscv64:
84530b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
84540b57cec5SDimitry Andric     break;
84550b57cec5SDimitry Andric   }
84560b57cec5SDimitry Andric 
84570b57cec5SDimitry Andric   // Consume all the warning flags. Usually this would be handled more
84580b57cec5SDimitry Andric   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
84590b57cec5SDimitry Andric   // doesn't handle that so rather than warning about unused flags that are
84600b57cec5SDimitry Andric   // actually used, we'll lie by omission instead.
84610b57cec5SDimitry Andric   // FIXME: Stop lying and consume only the appropriate driver flags
84620b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_W_Group);
84630b57cec5SDimitry Andric 
84640b57cec5SDimitry Andric   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
84650b57cec5SDimitry Andric                                     getToolChain().getDriver());
84660b57cec5SDimitry Andric 
84670b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
84680b57cec5SDimitry Andric 
846906c3fb27SDimitry Andric   if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
84700eae32dcSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
84710eae32dcSDimitry Andric                        Output.getFilename());
84720eae32dcSDimitry Andric 
84730eae32dcSDimitry Andric   // Fixup any previous commands that use -object-file-name because when we
84740eae32dcSDimitry Andric   // generated them, the final .obj name wasn't yet known.
84750eae32dcSDimitry Andric   for (Command &J : C.getJobs()) {
84760eae32dcSDimitry Andric     if (SourceAction != FindSource(&J.getSource()))
84770eae32dcSDimitry Andric       continue;
84780eae32dcSDimitry Andric     auto &JArgs = J.getArguments();
84790eae32dcSDimitry Andric     for (unsigned I = 0; I < JArgs.size(); ++I) {
84805f757f3fSDimitry Andric       if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
84810eae32dcSDimitry Andric           Output.isFilename()) {
84820eae32dcSDimitry Andric        ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
84830eae32dcSDimitry Andric        addDebugObjectName(Args, NewArgs, DebugCompilationDir,
84840eae32dcSDimitry Andric                           Output.getFilename());
84850eae32dcSDimitry Andric        NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
84860eae32dcSDimitry Andric        J.replaceArguments(NewArgs);
84870eae32dcSDimitry Andric        break;
84880eae32dcSDimitry Andric       }
84890eae32dcSDimitry Andric     }
84900eae32dcSDimitry Andric   }
84910eae32dcSDimitry Andric 
84920b57cec5SDimitry Andric   assert(Output.isFilename() && "Unexpected lipo output.");
84930b57cec5SDimitry Andric   CmdArgs.push_back("-o");
84940b57cec5SDimitry Andric   CmdArgs.push_back(Output.getFilename());
84950b57cec5SDimitry Andric 
84960b57cec5SDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
84970b57cec5SDimitry Andric   Arg *A;
84980b57cec5SDimitry Andric   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
84990b57cec5SDimitry Andric       T.isOSBinFormatELF()) {
85000b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-output");
8501e8d8bef9SDimitry Andric     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
85020b57cec5SDimitry Andric   }
85030b57cec5SDimitry Andric 
8504e8d8bef9SDimitry Andric   if (Triple.isAMDGPU())
850581ad6265SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8506e8d8bef9SDimitry Andric 
85070b57cec5SDimitry Andric   assert(Input.isFilename() && "Invalid input.");
85080b57cec5SDimitry Andric   CmdArgs.push_back(Input.getFilename());
85090b57cec5SDimitry Andric 
85100b57cec5SDimitry Andric   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8511e8d8bef9SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
8512e8d8bef9SDimitry Andric     // Invoke cc1as directly in this process.
851306c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
851406c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
851506c3fb27SDimitry Andric         Output, D.getPrependArg()));
8516e8d8bef9SDimitry Andric   } else {
851706c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
851806c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
851906c3fb27SDimitry Andric         Output, D.getPrependArg()));
8520e8d8bef9SDimitry Andric   }
85210b57cec5SDimitry Andric }
85220b57cec5SDimitry Andric 
85230b57cec5SDimitry Andric // Begin OffloadBundler
85240b57cec5SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const85250b57cec5SDimitry Andric void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
85260b57cec5SDimitry Andric                                   const InputInfo &Output,
85270b57cec5SDimitry Andric                                   const InputInfoList &Inputs,
85280b57cec5SDimitry Andric                                   const llvm::opt::ArgList &TCArgs,
85290b57cec5SDimitry Andric                                   const char *LinkingOutput) const {
85300b57cec5SDimitry Andric   // The version with only one output is expected to refer to a bundling job.
85310b57cec5SDimitry Andric   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
85320b57cec5SDimitry Andric 
85330b57cec5SDimitry Andric   // The bundling command looks like this:
85340b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
85350b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
853681ad6265SDimitry Andric   //   -output=output_file
853781ad6265SDimitry Andric   //   -input=unbundle_file_host
853881ad6265SDimitry Andric   //   -input=unbundle_file_tgt1
853981ad6265SDimitry Andric   //   -input=unbundle_file_tgt2
85400b57cec5SDimitry Andric 
85410b57cec5SDimitry Andric   ArgStringList CmdArgs;
85420b57cec5SDimitry Andric 
85430b57cec5SDimitry Andric   // Get the type.
85440b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
85450b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
85460b57cec5SDimitry Andric 
85470b57cec5SDimitry Andric   assert(JA.getInputs().size() == Inputs.size() &&
85480b57cec5SDimitry Andric          "Not have inputs for all dependence actions??");
85490b57cec5SDimitry Andric 
85500b57cec5SDimitry Andric   // Get the targets.
85510b57cec5SDimitry Andric   SmallString<128> Triples;
85520b57cec5SDimitry Andric   Triples += "-targets=";
85530b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
85540b57cec5SDimitry Andric     if (I)
85550b57cec5SDimitry Andric       Triples += ',';
85560b57cec5SDimitry Andric 
85570b57cec5SDimitry Andric     // Find ToolChain for this input.
85580b57cec5SDimitry Andric     Action::OffloadKind CurKind = Action::OFK_Host;
85590b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
85600b57cec5SDimitry Andric     const Action *CurDep = JA.getInputs()[I];
85610b57cec5SDimitry Andric 
85620b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
85630b57cec5SDimitry Andric       CurTC = nullptr;
85640b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
85650b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
85660b57cec5SDimitry Andric         CurKind = A->getOffloadingDeviceKind();
85670b57cec5SDimitry Andric         CurTC = TC;
85680b57cec5SDimitry Andric       });
85690b57cec5SDimitry Andric     }
85700b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(CurKind);
8571349cc55cSDimitry Andric     Triples += '-';
8572349cc55cSDimitry Andric     Triples += CurTC->getTriple().normalize();
8573349cc55cSDimitry Andric     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
85740eae32dcSDimitry Andric         !StringRef(CurDep->getOffloadingArch()).empty()) {
8575349cc55cSDimitry Andric       Triples += '-';
85760b57cec5SDimitry Andric       Triples += CurDep->getOffloadingArch();
85770b57cec5SDimitry Andric     }
8578349cc55cSDimitry Andric 
8579349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8580349cc55cSDimitry Andric     //       with each toolchain.
8581349cc55cSDimitry Andric     StringRef GPUArchName;
8582349cc55cSDimitry Andric     if (CurKind == Action::OFK_OpenMP) {
8583349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8584349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8585349cc55cSDimitry Andric         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
858606c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8587349cc55cSDimitry Andric         if (Arch) {
8588349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8589349cc55cSDimitry Andric           Triples += "-";
8590349cc55cSDimitry Andric           break;
8591349cc55cSDimitry Andric         }
8592349cc55cSDimitry Andric       }
8593349cc55cSDimitry Andric       Triples += GPUArchName.str();
8594349cc55cSDimitry Andric     }
85950b57cec5SDimitry Andric   }
85960b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
85970b57cec5SDimitry Andric 
85980b57cec5SDimitry Andric   // Get bundled file command.
85990b57cec5SDimitry Andric   CmdArgs.push_back(
860081ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
86010b57cec5SDimitry Andric 
86020b57cec5SDimitry Andric   // Get unbundled files command.
86030b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
860481ad6265SDimitry Andric     SmallString<128> UB;
860581ad6265SDimitry Andric     UB += "-input=";
86060b57cec5SDimitry Andric 
86070b57cec5SDimitry Andric     // Find ToolChain for this input.
86080b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
86090b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
86100b57cec5SDimitry Andric       CurTC = nullptr;
86110b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
86120b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
86130b57cec5SDimitry Andric         CurTC = TC;
86140b57cec5SDimitry Andric       });
86156e75b2fbSDimitry Andric       UB += C.addTempFile(
86166e75b2fbSDimitry Andric           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
86176e75b2fbSDimitry Andric     } else {
86180b57cec5SDimitry Andric       UB += CurTC->getInputFilename(Inputs[I]);
86190b57cec5SDimitry Andric     }
86200b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
862181ad6265SDimitry Andric   }
86225f757f3fSDimitry Andric   if (TCArgs.hasFlag(options::OPT_offload_compress,
86235f757f3fSDimitry Andric                      options::OPT_no_offload_compress, false))
86245f757f3fSDimitry Andric     CmdArgs.push_back("-compress");
86255f757f3fSDimitry Andric   if (TCArgs.hasArg(options::OPT_v))
86265f757f3fSDimitry Andric     CmdArgs.push_back("-verbose");
86270b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8628a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
86295ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
86300b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8631bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Output));
86320b57cec5SDimitry Andric }
86330b57cec5SDimitry Andric 
ConstructJobMultipleOutputs(Compilation & C,const JobAction & JA,const InputInfoList & Outputs,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const86340b57cec5SDimitry Andric void OffloadBundler::ConstructJobMultipleOutputs(
86350b57cec5SDimitry Andric     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
86360b57cec5SDimitry Andric     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
86370b57cec5SDimitry Andric     const char *LinkingOutput) const {
86380b57cec5SDimitry Andric   // The version with multiple outputs is expected to refer to a unbundling job.
86390b57cec5SDimitry Andric   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
86400b57cec5SDimitry Andric 
86410b57cec5SDimitry Andric   // The unbundling command looks like this:
86420b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
86430b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
864481ad6265SDimitry Andric   //   -input=input_file
864581ad6265SDimitry Andric   //   -output=unbundle_file_host
864681ad6265SDimitry Andric   //   -output=unbundle_file_tgt1
864781ad6265SDimitry Andric   //   -output=unbundle_file_tgt2
86480b57cec5SDimitry Andric   //   -unbundle
86490b57cec5SDimitry Andric 
86500b57cec5SDimitry Andric   ArgStringList CmdArgs;
86510b57cec5SDimitry Andric 
86520b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
86530b57cec5SDimitry Andric   InputInfo Input = Inputs.front();
86540b57cec5SDimitry Andric 
86550b57cec5SDimitry Andric   // Get the type.
86560b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
86570b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
86580b57cec5SDimitry Andric 
86590b57cec5SDimitry Andric   // Get the targets.
86600b57cec5SDimitry Andric   SmallString<128> Triples;
86610b57cec5SDimitry Andric   Triples += "-targets=";
86620b57cec5SDimitry Andric   auto DepInfo = UA.getDependentActionsInfo();
86630b57cec5SDimitry Andric   for (unsigned I = 0; I < DepInfo.size(); ++I) {
86640b57cec5SDimitry Andric     if (I)
86650b57cec5SDimitry Andric       Triples += ',';
86660b57cec5SDimitry Andric 
86670b57cec5SDimitry Andric     auto &Dep = DepInfo[I];
86680b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8669349cc55cSDimitry Andric     Triples += '-';
8670349cc55cSDimitry Andric     Triples += Dep.DependentToolChain->getTriple().normalize();
8671349cc55cSDimitry Andric     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8672349cc55cSDimitry Andric          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8673349cc55cSDimitry Andric         !Dep.DependentBoundArch.empty()) {
8674349cc55cSDimitry Andric       Triples += '-';
86750b57cec5SDimitry Andric       Triples += Dep.DependentBoundArch;
86760b57cec5SDimitry Andric     }
8677349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8678349cc55cSDimitry Andric     //       with each toolchain.
8679349cc55cSDimitry Andric     StringRef GPUArchName;
8680349cc55cSDimitry Andric     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8681349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8682349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8683349cc55cSDimitry Andric         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
868406c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8685349cc55cSDimitry Andric         if (Arch) {
8686349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8687349cc55cSDimitry Andric           Triples += "-";
8688349cc55cSDimitry Andric           break;
8689349cc55cSDimitry Andric         }
8690349cc55cSDimitry Andric       }
8691349cc55cSDimitry Andric       Triples += GPUArchName.str();
8692349cc55cSDimitry Andric     }
86930b57cec5SDimitry Andric   }
86940b57cec5SDimitry Andric 
86950b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
86960b57cec5SDimitry Andric 
86970b57cec5SDimitry Andric   // Get bundled file command.
86980b57cec5SDimitry Andric   CmdArgs.push_back(
869981ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
87000b57cec5SDimitry Andric 
87010b57cec5SDimitry Andric   // Get unbundled files command.
87020b57cec5SDimitry Andric   for (unsigned I = 0; I < Outputs.size(); ++I) {
870381ad6265SDimitry Andric     SmallString<128> UB;
870481ad6265SDimitry Andric     UB += "-output=";
87050b57cec5SDimitry Andric     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
87060b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
870781ad6265SDimitry Andric   }
87080b57cec5SDimitry Andric   CmdArgs.push_back("-unbundle");
8709e8d8bef9SDimitry Andric   CmdArgs.push_back("-allow-missing-bundles");
87105f757f3fSDimitry Andric   if (TCArgs.hasArg(options::OPT_v))
87115f757f3fSDimitry Andric     CmdArgs.push_back("-verbose");
87120b57cec5SDimitry Andric 
87130b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8714a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
87155ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
87160b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8717bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Outputs));
8718a7dea167SDimitry Andric }
87191fd87a68SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & Args,const char * LinkingOutput) const872081ad6265SDimitry Andric void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
872181ad6265SDimitry Andric                                    const InputInfo &Output,
872281ad6265SDimitry Andric                                    const InputInfoList &Inputs,
872381ad6265SDimitry Andric                                    const llvm::opt::ArgList &Args,
872481ad6265SDimitry Andric                                    const char *LinkingOutput) const {
872581ad6265SDimitry Andric   ArgStringList CmdArgs;
872681ad6265SDimitry Andric 
872781ad6265SDimitry Andric   // Add the output file name.
872881ad6265SDimitry Andric   assert(Output.isFilename() && "Invalid output.");
872981ad6265SDimitry Andric   CmdArgs.push_back("-o");
873081ad6265SDimitry Andric   CmdArgs.push_back(Output.getFilename());
873181ad6265SDimitry Andric 
873281ad6265SDimitry Andric   // Create the inputs to bundle the needed metadata.
873381ad6265SDimitry Andric   for (const InputInfo &Input : Inputs) {
873481ad6265SDimitry Andric     const Action *OffloadAction = Input.getAction();
873581ad6265SDimitry Andric     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
873681ad6265SDimitry Andric     const ArgList &TCArgs =
873781ad6265SDimitry Andric         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
873881ad6265SDimitry Andric                               OffloadAction->getOffloadingDeviceKind());
873981ad6265SDimitry Andric     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
874006c3fb27SDimitry Andric     StringRef Arch = OffloadAction->getOffloadingArch()
874181ad6265SDimitry Andric                          ? OffloadAction->getOffloadingArch()
874281ad6265SDimitry Andric                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
874381ad6265SDimitry Andric     StringRef Kind =
874481ad6265SDimitry Andric       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
874581ad6265SDimitry Andric 
874681ad6265SDimitry Andric     ArgStringList Features;
874781ad6265SDimitry Andric     SmallVector<StringRef> FeatureArgs;
8748753f127fSDimitry Andric     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8749753f127fSDimitry Andric                       false);
875081ad6265SDimitry Andric     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
87515f757f3fSDimitry Andric                   [](StringRef Arg) { return !Arg.starts_with("-target"); });
875281ad6265SDimitry Andric 
875306c3fb27SDimitry Andric     if (TC->getTriple().isAMDGPU()) {
875406c3fb27SDimitry Andric       for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
875506c3fb27SDimitry Andric         FeatureArgs.emplace_back(
875606c3fb27SDimitry Andric             Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
875706c3fb27SDimitry Andric       }
875806c3fb27SDimitry Andric     }
875906c3fb27SDimitry Andric 
876006c3fb27SDimitry Andric     // TODO: We need to pass in the full target-id and handle it properly in the
876106c3fb27SDimitry Andric     // linker wrapper.
876281ad6265SDimitry Andric     SmallVector<std::string> Parts{
876381ad6265SDimitry Andric         "file=" + File.str(),
876481ad6265SDimitry Andric         "triple=" + TC->getTripleString(),
87657a6dacacSDimitry Andric         "arch=" + Arch.str(),
876681ad6265SDimitry Andric         "kind=" + Kind.str(),
876781ad6265SDimitry Andric     };
876881ad6265SDimitry Andric 
876906c3fb27SDimitry Andric     if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
877006c3fb27SDimitry Andric         TC->getTriple().isAMDGPU())
877181ad6265SDimitry Andric       for (StringRef Feature : FeatureArgs)
877281ad6265SDimitry Andric         Parts.emplace_back("feature=" + Feature.str());
877381ad6265SDimitry Andric 
877481ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
877581ad6265SDimitry Andric   }
877681ad6265SDimitry Andric 
877781ad6265SDimitry Andric   C.addCommand(std::make_unique<Command>(
877881ad6265SDimitry Andric       JA, *this, ResponseFileSupport::None(),
877981ad6265SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
878081ad6265SDimitry Andric       CmdArgs, Inputs, Output));
878181ad6265SDimitry Andric }
878281ad6265SDimitry Andric 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const87831fd87a68SDimitry Andric void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
87841fd87a68SDimitry Andric                                  const InputInfo &Output,
87851fd87a68SDimitry Andric                                  const InputInfoList &Inputs,
87861fd87a68SDimitry Andric                                  const ArgList &Args,
87871fd87a68SDimitry Andric                                  const char *LinkingOutput) const {
8788d56accc7SDimitry Andric   const Driver &D = getToolChain().getDriver();
8789d56accc7SDimitry Andric   const llvm::Triple TheTriple = getToolChain().getTriple();
87901fd87a68SDimitry Andric   ArgStringList CmdArgs;
87911fd87a68SDimitry Andric 
8792d56accc7SDimitry Andric   // Pass the CUDA path to the linker wrapper tool.
879381ad6265SDimitry Andric   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
879481ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains(Kind);
879581ad6265SDimitry Andric     for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8796d56accc7SDimitry Andric       const ToolChain *TC = I.second;
8797d56accc7SDimitry Andric       if (TC->getTriple().isNVPTX()) {
8798d56accc7SDimitry Andric         CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8799d56accc7SDimitry Andric         if (CudaInstallation.isValid())
8800d56accc7SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
8801d56accc7SDimitry Andric               "--cuda-path=" + CudaInstallation.getInstallPath()));
8802d56accc7SDimitry Andric         break;
8803d56accc7SDimitry Andric       }
8804d56accc7SDimitry Andric     }
88051fd87a68SDimitry Andric   }
88061fd87a68SDimitry Andric 
88071fd87a68SDimitry Andric   // Pass in the optimization level to use for LTO.
88081fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
88091fd87a68SDimitry Andric     StringRef OOpt;
88101fd87a68SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
88111fd87a68SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
88121fd87a68SDimitry Andric       OOpt = "3";
88131fd87a68SDimitry Andric     else if (A->getOption().matches(options::OPT_O)) {
88141fd87a68SDimitry Andric       OOpt = A->getValue();
88151fd87a68SDimitry Andric       if (OOpt == "g")
88161fd87a68SDimitry Andric         OOpt = "1";
88171fd87a68SDimitry Andric       else if (OOpt == "s" || OOpt == "z")
88181fd87a68SDimitry Andric         OOpt = "2";
88191fd87a68SDimitry Andric     } else if (A->getOption().matches(options::OPT_O0))
88201fd87a68SDimitry Andric       OOpt = "0";
88211fd87a68SDimitry Andric     if (!OOpt.empty())
8822753f127fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
88231fd87a68SDimitry Andric   }
88241fd87a68SDimitry Andric 
8825753f127fSDimitry Andric   CmdArgs.push_back(
8826753f127fSDimitry Andric       Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
88271fd87a68SDimitry Andric   if (Args.hasArg(options::OPT_v))
8828bdd1243dSDimitry Andric     CmdArgs.push_back("--wrapper-verbose");
88291fd87a68SDimitry Andric 
88301fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8831753f127fSDimitry Andric     if (!A->getOption().matches(options::OPT_g0))
8832753f127fSDimitry Andric       CmdArgs.push_back("--device-debug");
88331fd87a68SDimitry Andric   }
88341fd87a68SDimitry Andric 
88355f757f3fSDimitry Andric   // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
88365f757f3fSDimitry Andric   // that it is used by lld.
88375f757f3fSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
88385f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mllvm"));
88395f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
88405f757f3fSDimitry Andric         Twine("--amdhsa-code-object-version=") + A->getValue()));
88415f757f3fSDimitry Andric   }
88425f757f3fSDimitry Andric 
88431fd87a68SDimitry Andric   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8844bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
88451fd87a68SDimitry Andric 
88461fd87a68SDimitry Andric   // Forward remarks passes to the LLVM backend in the wrapper.
88471fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8848fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8849fcaf7f86SDimitry Andric                                          A->getValue()));
88501fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8851fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
8852fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
88531fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8854fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
8855fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
88561fd87a68SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
8857753f127fSDimitry Andric     CmdArgs.push_back("--save-temps");
88581fd87a68SDimitry Andric 
8859d56accc7SDimitry Andric   // Construct the link job so we can wrap around it.
8860d56accc7SDimitry Andric   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8861d56accc7SDimitry Andric   const auto &LinkCommand = C.getJobs().getJobs().back();
8862d56accc7SDimitry Andric 
886381ad6265SDimitry Andric   // Forward -Xoffload-linker<-triple> arguments to the device link job.
8864753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8865753f127fSDimitry Andric     StringRef Val = A->getValue(0);
886681ad6265SDimitry Andric     if (Val.empty())
886781ad6265SDimitry Andric       CmdArgs.push_back(
8868753f127fSDimitry Andric           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
886981ad6265SDimitry Andric     else
887081ad6265SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
8871753f127fSDimitry Andric           "--device-linker=" +
887281ad6265SDimitry Andric           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8873753f127fSDimitry Andric           A->getValue(1)));
887481ad6265SDimitry Andric   }
887581ad6265SDimitry Andric   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
887681ad6265SDimitry Andric 
8877bdd1243dSDimitry Andric   // Embed bitcode instead of an object in JIT mode.
8878bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8879bdd1243dSDimitry Andric                    options::OPT_fno_openmp_target_jit, false))
8880bdd1243dSDimitry Andric     CmdArgs.push_back("--embed-bitcode");
8881bdd1243dSDimitry Andric 
8882753f127fSDimitry Andric   // Forward `-mllvm` arguments to the LLVM invocations if present.
8883753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8884753f127fSDimitry Andric     CmdArgs.push_back("-mllvm");
8885753f127fSDimitry Andric     CmdArgs.push_back(A->getValue());
8886753f127fSDimitry Andric     A->claim();
8887753f127fSDimitry Andric   }
8888753f127fSDimitry Andric 
88891fd87a68SDimitry Andric   // Add the linker arguments to be forwarded by the wrapper.
8890753f127fSDimitry Andric   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8891753f127fSDimitry Andric                                        LinkCommand->getExecutable()));
88921fd87a68SDimitry Andric   CmdArgs.push_back("--");
88931fd87a68SDimitry Andric   for (const char *LinkArg : LinkCommand->getArguments())
88941fd87a68SDimitry Andric     CmdArgs.push_back(LinkArg);
88951fd87a68SDimitry Andric 
88961fd87a68SDimitry Andric   const char *Exec =
88971fd87a68SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
88981fd87a68SDimitry Andric 
88991fd87a68SDimitry Andric   // Replace the executable and arguments of the link job with the
89001fd87a68SDimitry Andric   // wrapper.
89011fd87a68SDimitry Andric   LinkCommand->replaceExecutable(Exec);
89021fd87a68SDimitry Andric   LinkCommand->replaceArguments(CmdArgs);
89031fd87a68SDimitry Andric }
8904