brintos

brintos / llvm-project-archived public Read only

0
0
Text · 365.1 KiB · 0380568 Raw
9302 lines · cpp
1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "Clang.h"10#include "Arch/ARM.h"11#include "Arch/LoongArch.h"12#include "Arch/Mips.h"13#include "Arch/PPC.h"14#include "Arch/RISCV.h"15#include "Arch/Sparc.h"16#include "Arch/SystemZ.h"17#include "Hexagon.h"18#include "PS4CPU.h"19#include "ToolChains/Cuda.h"20#include "clang/Basic/CLWarnings.h"21#include "clang/Basic/CodeGenOptions.h"22#include "clang/Basic/HeaderInclude.h"23#include "clang/Basic/LangOptions.h"24#include "clang/Basic/MakeSupport.h"25#include "clang/Basic/ObjCRuntime.h"26#include "clang/Basic/Version.h"27#include "clang/Config/config.h"28#include "clang/Driver/Action.h"29#include "clang/Driver/CommonArgs.h"30#include "clang/Driver/Distro.h"31#include "clang/Driver/InputInfo.h"32#include "clang/Driver/SanitizerArgs.h"33#include "clang/Driver/Types.h"34#include "clang/Driver/XRayArgs.h"35#include "clang/Options/OptionUtils.h"36#include "clang/Options/Options.h"37#include "llvm/ADT/ScopeExit.h"38#include "llvm/ADT/SmallSet.h"39#include "llvm/ADT/StringExtras.h"40#include "llvm/BinaryFormat/Magic.h"41#include "llvm/Config/llvm-config.h"42#include "llvm/Frontend/Debug/Options.h"43#include "llvm/Object/ObjectFile.h"44#include "llvm/Option/ArgList.h"45#include "llvm/ProfileData/InstrProfReader.h"46#include "llvm/Support/CodeGen.h"47#include "llvm/Support/Compiler.h"48#include "llvm/Support/Compression.h"49#include "llvm/Support/Error.h"50#include "llvm/Support/FileSystem.h"51#include "llvm/Support/Path.h"52#include "llvm/Support/Process.h"53#include "llvm/Support/YAMLParser.h"54#include "llvm/TargetParser/AArch64TargetParser.h"55#include "llvm/TargetParser/ARMTargetParserCommon.h"56#include "llvm/TargetParser/Host.h"57#include "llvm/TargetParser/LoongArchTargetParser.h"58#include "llvm/TargetParser/PPCTargetParser.h"59#include "llvm/TargetParser/RISCVISAInfo.h"60#include "llvm/TargetParser/RISCVTargetParser.h"61#include <cctype>62 63using namespace clang::driver;64using namespace clang::driver::tools;65using namespace clang;66using namespace llvm::opt;67 68static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {69  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,70                               options::OPT_fminimize_whitespace,71                               options::OPT_fno_minimize_whitespace,72                               options::OPT_fkeep_system_includes,73                               options::OPT_fno_keep_system_includes)) {74    if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&75        !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {76      D.Diag(clang::diag::err_drv_argument_only_allowed_with)77          << A->getBaseArg().getAsString(Args)78          << (D.IsCLMode() ? "/E, /P or /EP" : "-E");79    }80  }81}82 83static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {84  // In gcc, only ARM checks this, but it seems reasonable to check universally.85  if (Args.hasArg(options::OPT_static))86    if (const Arg *A =87            Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))88      D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)89                                                      << "-static";90}91 92/// Apply \a Work on the current tool chain \a RegularToolChain and any other93/// offloading tool chain that is associated with the current action \a JA.94static void95forAllAssociatedToolChains(Compilation &C, const JobAction &JA,96                           const ToolChain &RegularToolChain,97                           llvm::function_ref<void(const ToolChain &)> Work) {98  // Apply Work on the current/regular tool chain.99  Work(RegularToolChain);100 101  // Apply Work on all the offloading tool chains associated with the current102  // action.103  for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,104                                   Action::OFK_HIP, Action::OFK_SYCL}) {105    if (JA.isHostOffloading(Kind)) {106      auto TCs = C.getOffloadToolChains(Kind);107      for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)108        Work(*II->second);109    } else if (JA.isDeviceOffloading(Kind))110      Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());111  }112}113 114static bool115shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,116                                          const llvm::Triple &Triple) {117  // We use the zero-cost exception tables for Objective-C if the non-fragile118  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and119  // later.120  if (runtime.isNonFragile())121    return true;122 123  if (!Triple.isMacOSX())124    return false;125 126  return (!Triple.isMacOSXVersionLT(10, 5) &&127          (Triple.getArch() == llvm::Triple::x86_64 ||128           Triple.getArch() == llvm::Triple::arm));129}130 131/// Adds exception related arguments to the driver command arguments. There's a132/// main flag, -fexceptions and also language specific flags to enable/disable133/// C++ and Objective-C exceptions. This makes it possible to for example134/// disable C++ exceptions but enable Objective-C exceptions.135static bool addExceptionArgs(const ArgList &Args, types::ID InputType,136                             const ToolChain &TC, bool KernelOrKext,137                             const ObjCRuntime &objcRuntime,138                             ArgStringList &CmdArgs) {139  const llvm::Triple &Triple = TC.getTriple();140 141  if (KernelOrKext) {142    // -mkernel and -fapple-kext imply no exceptions, so claim exception related143    // arguments now to avoid warnings about unused arguments.144    Args.ClaimAllArgs(options::OPT_fexceptions);145    Args.ClaimAllArgs(options::OPT_fno_exceptions);146    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);147    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);148    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);149    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);150    Args.ClaimAllArgs(options::OPT_fasync_exceptions);151    Args.ClaimAllArgs(options::OPT_fno_async_exceptions);152    return false;153  }154 155  // See if the user explicitly enabled exceptions.156  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,157                         false);158 159  // Async exceptions are Windows MSVC only.160  if (Triple.isWindowsMSVCEnvironment()) {161    bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,162                            options::OPT_fno_async_exceptions, false);163    if (EHa) {164      CmdArgs.push_back("-fasync-exceptions");165      EH = true;166    }167  }168 169  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This170  // is not necessarily sensible, but follows GCC.171  if (types::isObjC(InputType) &&172      Args.hasFlag(options::OPT_fobjc_exceptions,173                   options::OPT_fno_objc_exceptions, true)) {174    CmdArgs.push_back("-fobjc-exceptions");175 176    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);177  }178 179  if (types::isCXX(InputType)) {180    // Disable C++ EH by default on XCore and PS4/PS5.181    bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&182                                !Triple.isPS() && !Triple.isDriverKit();183    Arg *ExceptionArg = Args.getLastArg(184        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,185        options::OPT_fexceptions, options::OPT_fno_exceptions);186    if (ExceptionArg)187      CXXExceptionsEnabled =188          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||189          ExceptionArg->getOption().matches(options::OPT_fexceptions);190 191    if (CXXExceptionsEnabled) {192      CmdArgs.push_back("-fcxx-exceptions");193 194      EH = true;195    }196  }197 198  // OPT_fignore_exceptions means exception could still be thrown,199  // but no clean up or catch would happen in current module.200  // So we do not set EH to false.201  Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);202 203  Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,204                    options::OPT_fno_assume_nothrow_exception_dtor);205 206  if (EH)207    CmdArgs.push_back("-fexceptions");208  return EH;209}210 211static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,212                                 const JobAction &JA) {213  bool Default = true;214  if (TC.getTriple().isOSDarwin()) {215    // The native darwin assembler doesn't support the linker_option directives,216    // so we disable them if we think the .s file will be passed to it.217    Default = TC.useIntegratedAs();218  }219  // The linker_option directives are intended for host compilation.220  if (JA.isDeviceOffloading(Action::OFK_Cuda) ||221      JA.isDeviceOffloading(Action::OFK_HIP))222    Default = false;223  return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,224                      Default);225}226 227/// Add a CC1 option to specify the debug compilation directory.228static const char *addDebugCompDirArg(const ArgList &Args,229                                      ArgStringList &CmdArgs,230                                      const llvm::vfs::FileSystem &VFS) {231  std::string DebugCompDir;232  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,233                               options::OPT_fdebug_compilation_dir_EQ))234    DebugCompDir = A->getValue();235 236  if (DebugCompDir.empty()) {237    if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())238      DebugCompDir = std::move(*CWD);239    else240      return nullptr;241  }242  CmdArgs.push_back(243      Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));244  StringRef Path(CmdArgs.back());245  return Path.substr(Path.find('=') + 1).data();246}247 248static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,249                               const char *DebugCompilationDir,250                               const char *OutputFileName) {251  // No need to generate a value for -object-file-name if it was provided.252  for (auto *Arg : Args.filtered(options::OPT_Xclang))253    if (StringRef(Arg->getValue()).starts_with("-object-file-name"))254      return;255 256  if (Args.hasArg(options::OPT_object_file_name_EQ))257    return;258 259  SmallString<128> ObjFileNameForDebug(OutputFileName);260  if (ObjFileNameForDebug != "-" &&261      !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&262      (!DebugCompilationDir ||263       llvm::sys::path::is_absolute(DebugCompilationDir))) {264    // Make the path absolute in the debug infos like MSVC does.265    llvm::sys::fs::make_absolute(ObjFileNameForDebug);266  }267  // If the object file name is a relative path, then always use Windows268  // backslash style as -object-file-name is used for embedding object file path269  // in codeview and it can only be generated when targeting on Windows.270  // Otherwise, just use native absolute path.271  llvm::sys::path::Style Style =272      llvm::sys::path::is_absolute(ObjFileNameForDebug)273          ? llvm::sys::path::Style::native274          : llvm::sys::path::Style::windows_backslash;275  llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,276                               Style);277  CmdArgs.push_back(278      Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));279}280 281/// Add a CC1 and CC1AS option to specify the debug file path prefix map.282static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,283                                 const ArgList &Args, ArgStringList &CmdArgs) {284  auto AddOneArg = [&](StringRef Map, StringRef Name) {285    if (!Map.contains('='))286      D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;287    else288      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));289  };290 291  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,292                                    options::OPT_fdebug_prefix_map_EQ)) {293    AddOneArg(A->getValue(), A->getOption().getName());294    A->claim();295  }296  std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();297  if (GlobalRemapEntry.empty())298    return;299  AddOneArg(GlobalRemapEntry, "environment");300}301 302/// Add a CC1 and CC1AS option to specify the macro file path prefix map.303static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,304                                 ArgStringList &CmdArgs) {305  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,306                                    options::OPT_fmacro_prefix_map_EQ)) {307    StringRef Map = A->getValue();308    if (!Map.contains('='))309      D.Diag(diag::err_drv_invalid_argument_to_option)310          << Map << A->getOption().getName();311    else312      CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));313    A->claim();314  }315}316 317/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.318static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,319                                   ArgStringList &CmdArgs) {320  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,321                                    options::OPT_fcoverage_prefix_map_EQ)) {322    StringRef Map = A->getValue();323    if (!Map.contains('='))324      D.Diag(diag::err_drv_invalid_argument_to_option)325          << Map << A->getOption().getName();326    else327      CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));328    A->claim();329  }330}331 332/// Add -x lang to \p CmdArgs for \p Input.333static void addDashXForInput(const ArgList &Args, const InputInfo &Input,334                             ArgStringList &CmdArgs) {335  // When using -verify-pch, we don't want to provide the type336  // 'precompiled-header' if it was inferred from the file extension337  if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)338    return;339 340  CmdArgs.push_back("-x");341  if (Args.hasArg(options::OPT_rewrite_objc))342    CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));343  else {344    // Map the driver type to the frontend type. This is mostly an identity345    // mapping, except that the distinction between module interface units346    // and other source files does not exist at the frontend layer.347    const char *ClangType;348    switch (Input.getType()) {349    case types::TY_CXXModule:350      ClangType = "c++";351      break;352    case types::TY_PP_CXXModule:353      ClangType = "c++-cpp-output";354      break;355    default:356      ClangType = types::getTypeName(Input.getType());357      break;358    }359    CmdArgs.push_back(ClangType);360  }361}362 363static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,364                                   const JobAction &JA, const InputInfo &Output,365                                   const ArgList &Args, SanitizerArgs &SanArgs,366                                   ArgStringList &CmdArgs) {367  const Driver &D = TC.getDriver();368  const llvm::Triple &T = TC.getTriple();369  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,370                                         options::OPT_fprofile_generate_EQ,371                                         options::OPT_fno_profile_generate);372  if (PGOGenerateArg &&373      PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))374    PGOGenerateArg = nullptr;375 376  auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);377 378  auto *ProfileGenerateArg = Args.getLastArg(379      options::OPT_fprofile_instr_generate,380      options::OPT_fprofile_instr_generate_EQ,381      options::OPT_fno_profile_instr_generate);382  if (ProfileGenerateArg &&383      ProfileGenerateArg->getOption().matches(384          options::OPT_fno_profile_instr_generate))385    ProfileGenerateArg = nullptr;386 387  if (PGOGenerateArg && ProfileGenerateArg)388    D.Diag(diag::err_drv_argument_not_allowed_with)389        << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();390 391  auto *ProfileUseArg = getLastProfileUseArg(Args);392 393  if (PGOGenerateArg && ProfileUseArg)394    D.Diag(diag::err_drv_argument_not_allowed_with)395        << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();396 397  if (ProfileGenerateArg && ProfileUseArg)398    D.Diag(diag::err_drv_argument_not_allowed_with)399        << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();400 401  if (CSPGOGenerateArg && PGOGenerateArg) {402    D.Diag(diag::err_drv_argument_not_allowed_with)403        << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();404    PGOGenerateArg = nullptr;405  }406 407  if (TC.getTriple().isOSAIX()) {408    if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))409      D.Diag(diag::err_drv_unsupported_opt_for_target)410          << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();411  }412 413  if (ProfileGenerateArg) {414    if (ProfileGenerateArg->getOption().matches(415            options::OPT_fprofile_instr_generate_EQ))416      CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +417                                           ProfileGenerateArg->getValue()));418    // The default is to use Clang Instrumentation.419    CmdArgs.push_back("-fprofile-instrument=clang");420    if (TC.getTriple().isWindowsMSVCEnvironment() &&421        Args.hasFlag(options::OPT_frtlib_defaultlib,422                     options::OPT_fno_rtlib_defaultlib, true)) {423      // Add dependent lib for clang_rt.profile424      CmdArgs.push_back(Args.MakeArgString(425          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));426    }427  }428 429  if (auto *ColdFuncCoverageArg = Args.getLastArg(430          options::OPT_fprofile_generate_cold_function_coverage,431          options::OPT_fprofile_generate_cold_function_coverage_EQ)) {432    SmallString<128> Path(433        ColdFuncCoverageArg->getOption().matches(434            options::OPT_fprofile_generate_cold_function_coverage_EQ)435            ? ColdFuncCoverageArg->getValue()436            : "");437    llvm::sys::path::append(Path, "default_%m.profraw");438    // FIXME: Idealy the file path should be passed through439    // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is440    // shared with other profile use path(see PGOOptions), we need to refactor441    // PGOOptions to make it work.442    CmdArgs.push_back("-mllvm");443    CmdArgs.push_back(Args.MakeArgString(444        Twine("--instrument-cold-function-only-path=") + Path));445    CmdArgs.push_back("-mllvm");446    CmdArgs.push_back("--pgo-instrument-cold-function-only");447    CmdArgs.push_back("-mllvm");448    CmdArgs.push_back("--pgo-function-entry-coverage");449    CmdArgs.push_back("-fprofile-instrument=sample-coldcov");450  }451 452  if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {453    if (!PGOGenerateArg && !CSPGOGenerateArg)454      D.Diag(clang::diag::err_drv_argument_only_allowed_with)455          << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";456    CmdArgs.push_back("-mllvm");457    CmdArgs.push_back("--pgo-temporal-instrumentation");458  }459 460  Arg *PGOGenArg = nullptr;461  if (PGOGenerateArg) {462    assert(!CSPGOGenerateArg);463    PGOGenArg = PGOGenerateArg;464    CmdArgs.push_back("-fprofile-instrument=llvm");465  }466  if (CSPGOGenerateArg) {467    assert(!PGOGenerateArg);468    PGOGenArg = CSPGOGenerateArg;469    CmdArgs.push_back("-fprofile-instrument=csllvm");470  }471  if (PGOGenArg) {472    if (TC.getTriple().isWindowsMSVCEnvironment() &&473        Args.hasFlag(options::OPT_frtlib_defaultlib,474                     options::OPT_fno_rtlib_defaultlib, true)) {475      // Add dependent lib for clang_rt.profile476      CmdArgs.push_back(Args.MakeArgString(477          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));478    }479    if (PGOGenArg->getOption().matches(480            PGOGenerateArg ? options::OPT_fprofile_generate_EQ481                           : options::OPT_fcs_profile_generate_EQ)) {482      SmallString<128> Path(PGOGenArg->getValue());483      llvm::sys::path::append(Path, "default_%m.profraw");484      CmdArgs.push_back(485          Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));486    }487  }488 489  if (ProfileUseArg) {490    SmallString<128> UsePathBuf;491    StringRef UsePath;492    if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))493      UsePath = ProfileUseArg->getValue();494    else if ((ProfileUseArg->getOption().matches(495                  options::OPT_fprofile_use_EQ) ||496              ProfileUseArg->getOption().matches(497                  options::OPT_fprofile_instr_use))) {498      UsePathBuf =499          ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();500      if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))501        llvm::sys::path::append(UsePathBuf, "default.profdata");502      UsePath = UsePathBuf;503    }504    auto ReaderOrErr =505        llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());506    if (auto E = ReaderOrErr.takeError()) {507      auto DiagID = D.getDiags().getCustomDiagID(508          DiagnosticsEngine::Error, "Error in reading profile %0: %1");509      llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {510        D.Diag(DiagID) << UsePath.str() << EI.message();511      });512    } else {513      std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =514          std::move(ReaderOrErr.get());515      StringRef UseKind;516      // Currently memprof profiles are only added at the IR level. Mark the517      // profile type as IR in that case as well and the subsequent matching518      // needs to detect which is available (might be one or both).519      if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {520        if (PGOReader->hasCSIRLevelProfile())521          UseKind = "csllvm";522        else523          UseKind = "llvm";524      } else525        UseKind = "clang";526 527      CmdArgs.push_back(528          Args.MakeArgString("-fprofile-instrument-use=" + UseKind));529      CmdArgs.push_back(530          Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));531    }532  }533 534  bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,535                                   options::OPT_fno_test_coverage, false) ||536                      Args.hasArg(options::OPT_coverage);537  bool EmitCovData = TC.needsGCovInstrumentation(Args);538 539  if (Args.hasFlag(options::OPT_fcoverage_mapping,540                   options::OPT_fno_coverage_mapping, false)) {541    if (!ProfileGenerateArg)542      D.Diag(clang::diag::err_drv_argument_only_allowed_with)543          << "-fcoverage-mapping"544          << "-fprofile-instr-generate";545 546    CmdArgs.push_back("-fcoverage-mapping");547  }548 549  if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,550                   false)) {551    if (!Args.hasFlag(options::OPT_fcoverage_mapping,552                      options::OPT_fno_coverage_mapping, false))553      D.Diag(clang::diag::err_drv_argument_only_allowed_with)554          << "-fcoverage-mcdc"555          << "-fcoverage-mapping";556 557    CmdArgs.push_back("-fcoverage-mcdc");558  }559 560  StringRef CoverageCompDir;561  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,562                               options::OPT_fcoverage_compilation_dir_EQ))563    CoverageCompDir = A->getValue();564  if (CoverageCompDir.empty()) {565    if (auto CWD = D.getVFS().getCurrentWorkingDirectory())566      CmdArgs.push_back(567          Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));568  } else569    CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +570                                         CoverageCompDir));571 572  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {573    auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);574    if (!Args.hasArg(options::OPT_coverage))575      D.Diag(clang::diag::err_drv_argument_only_allowed_with)576          << "-fprofile-exclude-files="577          << "--coverage";578 579    StringRef v = Arg->getValue();580    CmdArgs.push_back(581        Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));582  }583 584  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {585    auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);586    if (!Args.hasArg(options::OPT_coverage))587      D.Diag(clang::diag::err_drv_argument_only_allowed_with)588          << "-fprofile-filter-files="589          << "--coverage";590 591    StringRef v = Arg->getValue();592    CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));593  }594 595  if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {596    StringRef Val = A->getValue();597    if (Val == "atomic" || Val == "prefer-atomic")598      CmdArgs.push_back("-fprofile-update=atomic");599    else if (Val != "single")600      D.Diag(diag::err_drv_unsupported_option_argument)601          << A->getSpelling() << Val;602  }603  if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {604    if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)605      D.Diag(clang::diag::err_drv_argument_only_allowed_with)606          << A->getSpelling()607          << "-fprofile-generate, -fprofile-instr-generate, or "608             "-fcs-profile-generate";609    else {610      CmdArgs.push_back("-fprofile-continuous");611      // Platforms that require a bias variable:612      if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {613        CmdArgs.push_back("-mllvm");614        CmdArgs.push_back("-runtime-counter-relocation");615      }616      // -fprofile-instr-generate does not decide the profile file name in the617      // FE, and so it does not define the filename symbol618      // (__llvm_profile_filename). Instead, the runtime uses the name619      // "default.profraw" for the profile file. When continuous mode is ON, we620      // will create the filename symbol so that we can insert the "%c"621      // modifier.622      if (ProfileGenerateArg &&623          (ProfileGenerateArg->getOption().matches(624               options::OPT_fprofile_instr_generate) ||625           (ProfileGenerateArg->getOption().matches(626                options::OPT_fprofile_instr_generate_EQ) &&627            strlen(ProfileGenerateArg->getValue()) == 0)))628        CmdArgs.push_back("-fprofile-instrument-path=default.profraw");629    }630  }631 632  int FunctionGroups = 1;633  int SelectedFunctionGroup = 0;634  if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {635    StringRef Val = A->getValue();636    if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)637      D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;638  }639  if (const auto *A =640          Args.getLastArg(options::OPT_fprofile_selected_function_group)) {641    StringRef Val = A->getValue();642    if (Val.getAsInteger(0, SelectedFunctionGroup) ||643        SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)644      D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;645  }646  if (FunctionGroups != 1)647    CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +648                                         Twine(FunctionGroups)));649  if (SelectedFunctionGroup != 0)650    CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +651                                         Twine(SelectedFunctionGroup)));652 653  // Leave -fprofile-dir= an unused argument unless .gcda emission is654  // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider655  // the flag used. There is no -fno-profile-dir, so the user has no656  // targeted way to suppress the warning.657  Arg *FProfileDir = nullptr;658  if (Args.hasArg(options::OPT_fprofile_arcs) ||659      Args.hasArg(options::OPT_coverage))660    FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);661 662  // Put the .gcno and .gcda files (if needed) next to the primary output file,663  // or fall back to a file in the current directory for `clang -c --coverage664  // d/a.c` in the absence of -o.665  if (EmitCovNotes || EmitCovData) {666    SmallString<128> CoverageFilename;667    if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {668      // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a669      // path separator.670      CoverageFilename = DumpDir->getValue();671      CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());672    } else if (Arg *FinalOutput =673                   C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {674      CoverageFilename = FinalOutput->getValue();675    } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {676      CoverageFilename = FinalOutput->getValue();677    } else {678      CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());679    }680    if (llvm::sys::path::is_relative(CoverageFilename))681      (void)D.getVFS().makeAbsolute(CoverageFilename);682    llvm::sys::path::replace_extension(CoverageFilename, "gcno");683    if (EmitCovNotes) {684      CmdArgs.push_back(685          Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));686    }687 688    if (EmitCovData) {689      if (FProfileDir) {690        SmallString<128> Gcno = std::move(CoverageFilename);691        CoverageFilename = FProfileDir->getValue();692        llvm::sys::path::append(CoverageFilename, Gcno);693      }694      llvm::sys::path::replace_extension(CoverageFilename, "gcda");695      CmdArgs.push_back(696          Args.MakeArgString("-coverage-data-file=" + CoverageFilename));697    }698  }699}700 701static void702RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,703                        llvm::codegenoptions::DebugInfoKind DebugInfoKind,704                        unsigned DwarfVersion,705                        llvm::DebuggerKind DebuggerTuning) {706  addDebugInfoKind(CmdArgs, DebugInfoKind);707  if (DwarfVersion > 0)708    CmdArgs.push_back(709        Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));710  switch (DebuggerTuning) {711  case llvm::DebuggerKind::GDB:712    CmdArgs.push_back("-debugger-tuning=gdb");713    break;714  case llvm::DebuggerKind::LLDB:715    CmdArgs.push_back("-debugger-tuning=lldb");716    break;717  case llvm::DebuggerKind::SCE:718    CmdArgs.push_back("-debugger-tuning=sce");719    break;720  case llvm::DebuggerKind::DBX:721    CmdArgs.push_back("-debugger-tuning=dbx");722    break;723  default:724    break;725  }726}727 728static void RenderDebugInfoCompressionArgs(const ArgList &Args,729                                           ArgStringList &CmdArgs,730                                           const Driver &D,731                                           const ToolChain &TC) {732  const Arg *A = Args.getLastArg(options::OPT_gz_EQ);733  if (!A)734    return;735  if (checkDebugInfoOption(A, Args, D, TC)) {736    StringRef Value = A->getValue();737    if (Value == "none") {738      CmdArgs.push_back("--compress-debug-sections=none");739    } else if (Value == "zlib") {740      if (llvm::compression::zlib::isAvailable()) {741        CmdArgs.push_back(742            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));743      } else {744        D.Diag(diag::warn_debug_compression_unavailable) << "zlib";745      }746    } else if (Value == "zstd") {747      if (llvm::compression::zstd::isAvailable()) {748        CmdArgs.push_back(749            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));750      } else {751        D.Diag(diag::warn_debug_compression_unavailable) << "zstd";752      }753    } else {754      D.Diag(diag::err_drv_unsupported_option_argument)755          << A->getSpelling() << Value;756    }757  }758}759 760static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,761                                                 const ArgList &Args,762                                                 ArgStringList &CmdArgs,763                                                 bool IsCC1As = false) {764  // If no version was requested by the user, use the default value from the765  // back end. This is consistent with the value returned from766  // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without767  // requiring the corresponding llvm to have the AMDGPU target enabled,768  // provided the user (e.g. front end tests) can use the default.769  if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {770    unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);771    CmdArgs.insert(CmdArgs.begin() + 1,772                   Args.MakeArgString(Twine("--amdhsa-code-object-version=") +773                                      Twine(CodeObjVer)));774    CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");775    // -cc1as does not accept -mcode-object-version option.776    if (!IsCC1As)777      CmdArgs.insert(CmdArgs.begin() + 1,778                     Args.MakeArgString(Twine("-mcode-object-version=") +779                                        Twine(CodeObjVer)));780  }781}782 783static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {784  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =785      D.getVFS().getBufferForFile(Path);786  if (!MemBuf)787    return false;788  llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());789  if (Magic == llvm::file_magic::unknown)790    return false;791  // Return true for both raw Clang AST files and object files which may792  // contain a __clangast section.793  if (Magic == llvm::file_magic::clang_ast)794    return true;795  Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =796      llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);797  return !Obj.takeError();798}799 800static bool gchProbe(const Driver &D, StringRef Path) {801  llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);802  if (!Status)803    return false;804 805  if (Status->isDirectory()) {806    std::error_code EC;807    for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;808         !EC && DI != DE; DI = DI.increment(EC)) {809      if (maybeHasClangPchSignature(D, DI->path()))810        return true;811    }812    D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;813    return false;814  }815 816  if (maybeHasClangPchSignature(D, Path))817    return true;818  D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;819  return false;820}821 822void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,823                                    const Driver &D, const ArgList &Args,824                                    ArgStringList &CmdArgs,825                                    const InputInfo &Output,826                                    const InputInfoList &Inputs) const {827  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();828 829  CheckPreprocessingOptions(D, Args);830 831  Args.AddLastArg(CmdArgs, options::OPT_C);832  Args.AddLastArg(CmdArgs, options::OPT_CC);833 834  // Handle dependency file generation.835  Arg *ArgM = Args.getLastArg(options::OPT_MM);836  if (!ArgM)837    ArgM = Args.getLastArg(options::OPT_M);838  Arg *ArgMD = Args.getLastArg(options::OPT_MMD);839  if (!ArgMD)840    ArgMD = Args.getLastArg(options::OPT_MD);841 842  // -M and -MM imply -w.843  if (ArgM)844    CmdArgs.push_back("-w");845  else846    ArgM = ArgMD;847 848  if (ArgM) {849    if (!JA.isDeviceOffloading(Action::OFK_HIP)) {850      // Determine the output location.851      const char *DepFile;852      if (Arg *MF = Args.getLastArg(options::OPT_MF)) {853        DepFile = MF->getValue();854        C.addFailureResultFile(DepFile, &JA);855      } else if (Output.getType() == types::TY_Dependencies) {856        DepFile = Output.getFilename();857      } else if (!ArgMD) {858        DepFile = "-";859      } else {860        DepFile = getDependencyFileName(Args, Inputs);861        C.addFailureResultFile(DepFile, &JA);862      }863      CmdArgs.push_back("-dependency-file");864      CmdArgs.push_back(DepFile);865    }866    // Cmake generates dependency files using all compilation options specified867    // by users. Claim those not used for dependency files.868    if (JA.isOffloading(Action::OFK_HIP)) {869      Args.ClaimAllArgs(options::OPT_offload_compress);870      Args.ClaimAllArgs(options::OPT_no_offload_compress);871      Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);872    }873 874    bool HasTarget = false;875    for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {876      HasTarget = true;877      A->claim();878      if (A->getOption().matches(options::OPT_MT)) {879        A->render(Args, CmdArgs);880      } else {881        CmdArgs.push_back("-MT");882        SmallString<128> Quoted;883        quoteMakeTarget(A->getValue(), Quoted);884        CmdArgs.push_back(Args.MakeArgString(Quoted));885      }886    }887 888    // Add a default target if one wasn't specified.889    if (!HasTarget) {890      const char *DepTarget;891 892      // If user provided -o, that is the dependency target, except893      // when we are only generating a dependency file.894      Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);895      if (OutputOpt && Output.getType() != types::TY_Dependencies) {896        DepTarget = OutputOpt->getValue();897      } else {898        // Otherwise derive from the base input.899        //900        // FIXME: This should use the computed output file location.901        SmallString<128> P(Inputs[0].getBaseInput());902        llvm::sys::path::replace_extension(P, "o");903        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));904      }905 906      CmdArgs.push_back("-MT");907      SmallString<128> Quoted;908      quoteMakeTarget(DepTarget, Quoted);909      CmdArgs.push_back(Args.MakeArgString(Quoted));910    }911 912    if (ArgM->getOption().matches(options::OPT_M) ||913        ArgM->getOption().matches(options::OPT_MD))914      CmdArgs.push_back("-sys-header-deps");915    if ((isa<PrecompileJobAction>(JA) &&916         !Args.hasArg(options::OPT_fno_module_file_deps)) ||917        Args.hasArg(options::OPT_fmodule_file_deps))918      CmdArgs.push_back("-module-file-deps");919  }920 921  if (Args.hasArg(options::OPT_MG)) {922    if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||923        ArgM->getOption().matches(options::OPT_MMD))924      D.Diag(diag::err_drv_mg_requires_m_or_mm);925    CmdArgs.push_back("-MG");926  }927 928  Args.AddLastArg(CmdArgs, options::OPT_MP);929  Args.AddLastArg(CmdArgs, options::OPT_MV);930 931  // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen932  // before we -I or -include anything else, because we must pick up the933  // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,934  // rather than from e.g. /usr/local/include.935  if (JA.isOffloading(Action::OFK_Cuda))936    getToolChain().AddCudaIncludeArgs(Args, CmdArgs);937  if (JA.isOffloading(Action::OFK_HIP))938    getToolChain().AddHIPIncludeArgs(Args, CmdArgs);939  if (JA.isOffloading(Action::OFK_SYCL))940    getToolChain().addSYCLIncludeArgs(Args, CmdArgs);941 942  // If we are offloading to a target via OpenMP we need to include the943  // openmp_wrappers folder which contains alternative system headers.944  if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&945      !Args.hasArg(options::OPT_nostdinc) &&946      Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,947                   true) &&948      getToolChain().getTriple().isGPU()) {949    if (!Args.hasArg(options::OPT_nobuiltininc)) {950      // Add openmp_wrappers/* to our system include path.  This lets us wrap951      // standard library headers.952      SmallString<128> P(D.ResourceDir);953      llvm::sys::path::append(P, "include");954      llvm::sys::path::append(P, "openmp_wrappers");955      CmdArgs.push_back("-internal-isystem");956      CmdArgs.push_back(Args.MakeArgString(P));957    }958 959    CmdArgs.push_back("-include");960    CmdArgs.push_back("__clang_openmp_device_functions.h");961  }962 963  if (Args.hasArg(options::OPT_foffload_via_llvm)) {964    // Add llvm_wrappers/* to our system include path.  This lets us wrap965    // standard library headers and other headers.966    SmallString<128> P(D.ResourceDir);967    llvm::sys::path::append(P, "include", "llvm_offload_wrappers");968    CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});969    if (JA.isDeviceOffloading(Action::OFK_OpenMP))970      CmdArgs.push_back("__llvm_offload_device.h");971    else972      CmdArgs.push_back("__llvm_offload_host.h");973  }974 975  // Add -i* options, and automatically translate to976  // -include-pch/-include-pth for transparent PCH support. It's977  // wonky, but we include looking for .gch so we can support seamless978  // replacement into a build system already set up to be generating979  // .gch files.980 981  if (getToolChain().getDriver().IsCLMode()) {982    const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);983    const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);984    if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&985        JA.getKind() <= Action::AssembleJobClass) {986      CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));987      // -fpch-instantiate-templates is the default when creating988      // precomp using /Yc989      if (Args.hasFlag(options::OPT_fpch_instantiate_templates,990                       options::OPT_fno_pch_instantiate_templates, true))991        CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));992    }993    if (YcArg || YuArg) {994      StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();995      if (!isa<PrecompileJobAction>(JA)) {996        CmdArgs.push_back("-include-pch");997        CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(998            C, !ThroughHeader.empty()999                   ? ThroughHeader1000                   : llvm::sys::path::filename(Inputs[0].getBaseInput()))));1001      }1002 1003      if (ThroughHeader.empty()) {1004        CmdArgs.push_back(Args.MakeArgString(1005            Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));1006      } else {1007        CmdArgs.push_back(1008            Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));1009      }1010    }1011  }1012 1013  bool RenderedImplicitInclude = false;1014  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {1015    if (A->getOption().matches(options::OPT_include) &&1016        D.getProbePrecompiled()) {1017      // Handling of gcc-style gch precompiled headers.1018      bool IsFirstImplicitInclude = !RenderedImplicitInclude;1019      RenderedImplicitInclude = true;1020 1021      bool FoundPCH = false;1022      SmallString<128> P(A->getValue());1023      // We want the files to have a name like foo.h.pch. Add a dummy extension1024      // so that replace_extension does the right thing.1025      P += ".dummy";1026      llvm::sys::path::replace_extension(P, "pch");1027      if (D.getVFS().exists(P))1028        FoundPCH = true;1029 1030      if (!FoundPCH) {1031        // For GCC compat, probe for a file or directory ending in .gch instead.1032        llvm::sys::path::replace_extension(P, "gch");1033        FoundPCH = gchProbe(D, P.str());1034      }1035 1036      if (FoundPCH) {1037        if (IsFirstImplicitInclude) {1038          A->claim();1039          CmdArgs.push_back("-include-pch");1040          CmdArgs.push_back(Args.MakeArgString(P));1041          continue;1042        } else {1043          // Ignore the PCH if not first on command line and emit warning.1044          D.Diag(diag::warn_drv_pch_not_first_include) << P1045                                                       << A->getAsString(Args);1046        }1047      }1048    } else if (A->getOption().matches(options::OPT_isystem_after)) {1049      // Handling of paths which must come late.  These entries are handled by1050      // the toolchain itself after the resource dir is inserted in the right1051      // search order.1052      // Do not claim the argument so that the use of the argument does not1053      // silently go unnoticed on toolchains which do not honour the option.1054      continue;1055    } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {1056      // Translated to -internal-isystem by the driver, no need to pass to cc1.1057      continue;1058    } else if (A->getOption().matches(options::OPT_ibuiltininc)) {1059      // This is used only by the driver. No need to pass to cc1.1060      continue;1061    }1062 1063    // Not translated, render as usual.1064    A->claim();1065    A->render(Args, CmdArgs);1066  }1067 1068  Args.addAllArgs(CmdArgs,1069                  {options::OPT_D, options::OPT_U, options::OPT_I_Group,1070                   options::OPT_F, options::OPT_embed_dir_EQ});1071 1072  // Add -Wp, and -Xpreprocessor if using the preprocessor.1073 1074  // FIXME: There is a very unfortunate problem here, some troubled1075  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To1076  // really support that we would have to parse and then translate1077  // those options. :(1078  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,1079                       options::OPT_Xpreprocessor);1080 1081  // -I- is a deprecated GCC feature, reject it.1082  if (Arg *A = Args.getLastArg(options::OPT_I_))1083    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);1084 1085  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an1086  // -isysroot to the CC1 invocation.1087  StringRef sysroot = C.getSysRoot();1088  if (sysroot != "") {1089    if (!Args.hasArg(options::OPT_isysroot)) {1090      CmdArgs.push_back("-isysroot");1091      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));1092    }1093  }1094 1095  // Parse additional include paths from environment variables.1096  // FIXME: We should probably sink the logic for handling these from the1097  // frontend into the driver. It will allow deleting 4 otherwise unused flags.1098  // CPATH - included following the user specified includes (but prior to1099  // builtin and standard includes).1100  addDirectoryList(Args, CmdArgs, "-I", "CPATH");1101  // C_INCLUDE_PATH - system includes enabled when compiling C.1102  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");1103  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.1104  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");1105  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.1106  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");1107  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.1108  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");1109 1110  // While adding the include arguments, we also attempt to retrieve the1111  // arguments of related offloading toolchains or arguments that are specific1112  // of an offloading programming model.1113 1114  // Add C++ include arguments, if needed.1115  if (types::isCXX(Inputs[0].getType())) {1116    bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);1117    forAllAssociatedToolChains(1118        C, JA, getToolChain(),1119        [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {1120          HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)1121                             : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);1122        });1123  }1124 1125  // If we are compiling for a GPU target we want to override the system headers1126  // with ones created by the 'libc' project if present.1127  // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the1128  //       OffloadKind as an argument.1129  if (!Args.hasArg(options::OPT_nostdinc) &&1130      Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,1131                   true) &&1132      !Args.hasArg(options::OPT_nobuiltininc) &&1133      (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {1134    // TODO: CUDA / HIP include their own headers for some common functions1135    // implemented here. We'll need to clean those up so they do not conflict.1136    SmallString<128> P(D.ResourceDir);1137    llvm::sys::path::append(P, "include");1138    llvm::sys::path::append(P, "llvm_libc_wrappers");1139    CmdArgs.push_back("-internal-isystem");1140    CmdArgs.push_back(Args.MakeArgString(P));1141  }1142 1143  // Add system include arguments for all targets but IAMCU.1144  if (!IsIAMCU)1145    forAllAssociatedToolChains(C, JA, getToolChain(),1146                               [&Args, &CmdArgs](const ToolChain &TC) {1147                                 TC.AddClangSystemIncludeArgs(Args, CmdArgs);1148                               });1149  else {1150    // For IAMCU add special include arguments.1151    getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);1152  }1153 1154  addMacroPrefixMapArg(D, Args, CmdArgs);1155  addCoveragePrefixMapArg(D, Args, CmdArgs);1156 1157  Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,1158                  options::OPT_fno_file_reproducible);1159 1160  if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {1161    CmdArgs.push_back("-source-date-epoch");1162    CmdArgs.push_back(Args.MakeArgString(Epoch));1163  }1164 1165  Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,1166                    options::OPT_fno_define_target_os_macros);1167}1168 1169// FIXME: Move to target hook.1170static bool isSignedCharDefault(const llvm::Triple &Triple) {1171  switch (Triple.getArch()) {1172  default:1173    return true;1174 1175  case llvm::Triple::aarch64:1176  case llvm::Triple::aarch64_32:1177  case llvm::Triple::aarch64_be:1178  case llvm::Triple::arm:1179  case llvm::Triple::armeb:1180  case llvm::Triple::thumb:1181  case llvm::Triple::thumbeb:1182    if (Triple.isOSDarwin() || Triple.isOSWindows())1183      return true;1184    return false;1185 1186  case llvm::Triple::ppc:1187  case llvm::Triple::ppc64:1188    if (Triple.isOSDarwin())1189      return true;1190    return false;1191 1192  case llvm::Triple::csky:1193  case llvm::Triple::hexagon:1194  case llvm::Triple::msp430:1195  case llvm::Triple::ppcle:1196  case llvm::Triple::ppc64le:1197  case llvm::Triple::riscv32:1198  case llvm::Triple::riscv64:1199  case llvm::Triple::systemz:1200  case llvm::Triple::xcore:1201  case llvm::Triple::xtensa:1202    return false;1203  }1204}1205 1206static bool hasMultipleInvocations(const llvm::Triple &Triple,1207                                   const ArgList &Args) {1208  // Supported only on Darwin where we invoke the compiler multiple times1209  // followed by an invocation to lipo.1210  if (!Triple.isOSDarwin())1211    return false;1212  // If more than one "-arch <arch>" is specified, we're targeting multiple1213  // architectures resulting in a fat binary.1214  return Args.getAllArgValues(options::OPT_arch).size() > 1;1215}1216 1217static bool checkRemarksOptions(const Driver &D, const ArgList &Args,1218                                const llvm::Triple &Triple) {1219  // When enabling remarks, we need to error if:1220  // * The remark file is specified but we're targeting multiple architectures,1221  // which means more than one remark file is being generated.1222  bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);1223  bool hasExplicitOutputFile =1224      Args.getLastArg(options::OPT_foptimization_record_file_EQ);1225  if (hasMultipleInvocations && hasExplicitOutputFile) {1226    D.Diag(diag::err_drv_invalid_output_with_multiple_archs)1227        << "-foptimization-record-file";1228    return false;1229  }1230  return true;1231}1232 1233static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,1234                                 const llvm::Triple &Triple,1235                                 const InputInfo &Input,1236                                 const InputInfo &Output, const JobAction &JA) {1237  StringRef Format = "yaml";1238  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))1239    Format = A->getValue();1240 1241  CmdArgs.push_back("-opt-record-file");1242 1243  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);1244  if (A) {1245    CmdArgs.push_back(A->getValue());1246  } else {1247    bool hasMultipleArchs =1248        Triple.isOSDarwin() && // Only supported on Darwin platforms.1249        Args.getAllArgValues(options::OPT_arch).size() > 1;1250 1251    SmallString<128> F;1252 1253    if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {1254      if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))1255        F = FinalOutput->getValue();1256    } else {1257      if (Format != "yaml" && // For YAML, keep the original behavior.1258          Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.1259          Output.isFilename())1260        F = Output.getFilename();1261    }1262 1263    if (F.empty()) {1264      // Use the input filename.1265      F = llvm::sys::path::stem(Input.getBaseInput());1266 1267      // If we're compiling for an offload architecture (i.e. a CUDA device),1268      // we need to make the file name for the device compilation different1269      // from the host compilation.1270      if (!JA.isDeviceOffloading(Action::OFK_None) &&1271          !JA.isDeviceOffloading(Action::OFK_Host)) {1272        llvm::sys::path::replace_extension(F, "");1273        F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),1274                                                 Triple.normalize());1275        F += "-";1276        F += JA.getOffloadingArch();1277      }1278    }1279 1280    // If we're having more than one "-arch", we should name the files1281    // differently so that every cc1 invocation writes to a different file.1282    // We're doing that by appending "-<arch>" with "<arch>" being the arch1283    // name from the triple.1284    if (hasMultipleArchs) {1285      // First, remember the extension.1286      SmallString<64> OldExtension = llvm::sys::path::extension(F);1287      // then, remove it.1288      llvm::sys::path::replace_extension(F, "");1289      // attach -<arch> to it.1290      F += "-";1291      F += Triple.getArchName();1292      // put back the extension.1293      llvm::sys::path::replace_extension(F, OldExtension);1294    }1295 1296    SmallString<32> Extension;1297    Extension += "opt.";1298    Extension += Format;1299 1300    llvm::sys::path::replace_extension(F, Extension);1301    CmdArgs.push_back(Args.MakeArgString(F));1302  }1303 1304  if (const Arg *A =1305          Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {1306    CmdArgs.push_back("-opt-record-passes");1307    CmdArgs.push_back(A->getValue());1308  }1309 1310  if (!Format.empty()) {1311    CmdArgs.push_back("-opt-record-format");1312    CmdArgs.push_back(Format.data());1313  }1314}1315 1316void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {1317  if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,1318                    options::OPT_fno_aapcs_bitfield_width, true))1319    CmdArgs.push_back("-fno-aapcs-bitfield-width");1320 1321  if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))1322    CmdArgs.push_back("-faapcs-bitfield-load");1323}1324 1325namespace {1326void RenderARMABI(const Driver &D, const llvm::Triple &Triple,1327                  const ArgList &Args, ArgStringList &CmdArgs) {1328  // Select the ABI to use.1329  // FIXME: Support -meabi.1330  // FIXME: Parts of this are duplicated in the backend, unify this somehow.1331  const char *ABIName = nullptr;1332  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))1333    ABIName = A->getValue();1334  else1335    ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();1336 1337  CmdArgs.push_back("-target-abi");1338  CmdArgs.push_back(ABIName);1339}1340 1341void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {1342  auto StrictAlignIter =1343      llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {1344        return Arg == "+strict-align" || Arg == "-strict-align";1345      });1346  if (StrictAlignIter != CmdArgs.rend() &&1347      StringRef(*StrictAlignIter) == "+strict-align")1348    CmdArgs.push_back("-Wunaligned-access");1349}1350}1351 1352static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,1353                                    ArgStringList &CmdArgs, bool isAArch64) {1354  const llvm::Triple &Triple = TC.getEffectiveTriple();1355  const Arg *A = isAArch641356                     ? Args.getLastArg(options::OPT_msign_return_address_EQ,1357                                       options::OPT_mbranch_protection_EQ)1358                     : Args.getLastArg(options::OPT_mbranch_protection_EQ);1359  if (!A) {1360    if (Triple.isOSOpenBSD() && isAArch64) {1361      CmdArgs.push_back("-msign-return-address=non-leaf");1362      CmdArgs.push_back("-msign-return-address-key=a_key");1363      CmdArgs.push_back("-mbranch-target-enforce");1364    }1365    return;1366  }1367 1368  const Driver &D = TC.getDriver();1369  if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))1370    D.Diag(diag::warn_incompatible_branch_protection_option)1371        << Triple.getArchName();1372 1373  StringRef Scope, Key;1374  bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;1375 1376  if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {1377    Scope = A->getValue();1378    if (Scope != "none" && Scope != "non-leaf" && Scope != "all")1379      D.Diag(diag::err_drv_unsupported_option_argument)1380          << A->getSpelling() << Scope;1381    Key = "a_key";1382    IndirectBranches = Triple.isOSOpenBSD() && isAArch64;1383    BranchProtectionPAuthLR = false;1384    GuardedControlStack = false;1385  } else {1386    StringRef DiagMsg;1387    llvm::ARM::ParsedBranchProtection PBP;1388    bool EnablePAuthLR = false;1389 1390    // To know if we need to enable PAuth-LR As part of the standard branch1391    // protection option, it needs to be determined if the feature has been1392    // activated in the `march` argument. This information is stored within the1393    // CmdArgs variable and can be found using a search.1394    if (isAArch64) {1395      auto isPAuthLR = [](const char *member) {1396        llvm::AArch64::ExtensionInfo pauthlr_extension =1397            llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);1398        return pauthlr_extension.PosTargetFeature == member;1399      };1400 1401      if (llvm::any_of(CmdArgs, isPAuthLR))1402        EnablePAuthLR = true;1403    }1404    if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,1405                                          EnablePAuthLR))1406      D.Diag(diag::err_drv_unsupported_option_argument)1407          << A->getSpelling() << DiagMsg;1408    if (!isAArch64 && PBP.Key == "b_key")1409      D.Diag(diag::warn_unsupported_branch_protection)1410          << "b-key" << A->getAsString(Args);1411    Scope = PBP.Scope;1412    Key = PBP.Key;1413    BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;1414    IndirectBranches = PBP.BranchTargetEnforcement;1415    GuardedControlStack = PBP.GuardedControlStack;1416  }1417 1418  Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,1419                                           options::OPT_fno_ptrauth_returns);1420  bool HasPtrauthReturns =1421      PtrauthReturnsArg &&1422      PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);1423  // GCS is currently untested with ptrauth-returns, but enabling this could be1424  // allowed in future after testing with a suitable system.1425  if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {1426    if (Triple.getEnvironment() == llvm::Triple::PAuthTest)1427      D.Diag(diag::err_drv_unsupported_opt_for_target)1428          << A->getAsString(Args) << Triple.getTriple();1429    else if (HasPtrauthReturns)1430      D.Diag(diag::err_drv_incompatible_options)1431          << A->getAsString(Args) << "-fptrauth-returns";1432  }1433 1434  CmdArgs.push_back(1435      Args.MakeArgString(Twine("-msign-return-address=") + Scope));1436  if (Scope != "none")1437    CmdArgs.push_back(1438        Args.MakeArgString(Twine("-msign-return-address-key=") + Key));1439  if (BranchProtectionPAuthLR)1440    CmdArgs.push_back(1441        Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));1442  if (IndirectBranches)1443    CmdArgs.push_back("-mbranch-target-enforce");1444 1445  if (GuardedControlStack)1446    CmdArgs.push_back("-mguarded-control-stack");1447}1448 1449void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,1450                             ArgStringList &CmdArgs, bool KernelOrKext) const {1451  RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);1452 1453  // Determine floating point ABI from the options & target defaults.1454  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);1455  if (ABI == arm::FloatABI::Soft) {1456    // Floating point operations and argument passing are soft.1457    // FIXME: This changes CPP defines, we need -target-soft-float.1458    CmdArgs.push_back("-msoft-float");1459    CmdArgs.push_back("-mfloat-abi");1460    CmdArgs.push_back("soft");1461  } else if (ABI == arm::FloatABI::SoftFP) {1462    // Floating point operations are hard, but argument passing is soft.1463    CmdArgs.push_back("-mfloat-abi");1464    CmdArgs.push_back("soft");1465  } else {1466    // Floating point operations and argument passing are hard.1467    assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");1468    CmdArgs.push_back("-mfloat-abi");1469    CmdArgs.push_back("hard");1470  }1471 1472  // Forward the -mglobal-merge option for explicit control over the pass.1473  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,1474                               options::OPT_mno_global_merge)) {1475    CmdArgs.push_back("-mllvm");1476    if (A->getOption().matches(options::OPT_mno_global_merge))1477      CmdArgs.push_back("-arm-global-merge=false");1478    else1479      CmdArgs.push_back("-arm-global-merge=true");1480  }1481 1482  if (!Args.hasFlag(options::OPT_mimplicit_float,1483                    options::OPT_mno_implicit_float, true))1484    CmdArgs.push_back("-no-implicit-float");1485 1486  if (Args.getLastArg(options::OPT_mcmse))1487    CmdArgs.push_back("-mcmse");1488 1489  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);1490 1491  // Enable/disable return address signing and indirect branch targets.1492  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);1493 1494  AddUnalignedAccessWarning(CmdArgs);1495}1496 1497void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,1498                                const ArgList &Args, bool KernelOrKext,1499                                ArgStringList &CmdArgs) const {1500  const ToolChain &TC = getToolChain();1501 1502  // Add the target features1503  getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);1504 1505  // Add target specific flags.1506  switch (TC.getArch()) {1507  default:1508    break;1509 1510  case llvm::Triple::arm:1511  case llvm::Triple::armeb:1512  case llvm::Triple::thumb:1513  case llvm::Triple::thumbeb:1514    // Use the effective triple, which takes into account the deployment target.1515    AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);1516    break;1517 1518  case llvm::Triple::aarch64:1519  case llvm::Triple::aarch64_32:1520  case llvm::Triple::aarch64_be:1521    AddAArch64TargetArgs(Args, CmdArgs);1522    break;1523 1524  case llvm::Triple::loongarch32:1525  case llvm::Triple::loongarch64:1526    AddLoongArchTargetArgs(Args, CmdArgs);1527    break;1528 1529  case llvm::Triple::mips:1530  case llvm::Triple::mipsel:1531  case llvm::Triple::mips64:1532  case llvm::Triple::mips64el:1533    AddMIPSTargetArgs(Args, CmdArgs);1534    break;1535 1536  case llvm::Triple::ppc:1537  case llvm::Triple::ppcle:1538  case llvm::Triple::ppc64:1539  case llvm::Triple::ppc64le:1540    AddPPCTargetArgs(Args, CmdArgs);1541    break;1542 1543  case llvm::Triple::riscv32:1544  case llvm::Triple::riscv64:1545    AddRISCVTargetArgs(Args, CmdArgs);1546    break;1547 1548  case llvm::Triple::sparc:1549  case llvm::Triple::sparcel:1550  case llvm::Triple::sparcv9:1551    AddSparcTargetArgs(Args, CmdArgs);1552    break;1553 1554  case llvm::Triple::systemz:1555    AddSystemZTargetArgs(Args, CmdArgs);1556    break;1557 1558  case llvm::Triple::x86:1559  case llvm::Triple::x86_64:1560    AddX86TargetArgs(Args, CmdArgs);1561    break;1562 1563  case llvm::Triple::lanai:1564    AddLanaiTargetArgs(Args, CmdArgs);1565    break;1566 1567  case llvm::Triple::hexagon:1568    AddHexagonTargetArgs(Args, CmdArgs);1569    break;1570 1571  case llvm::Triple::wasm32:1572  case llvm::Triple::wasm64:1573    AddWebAssemblyTargetArgs(Args, CmdArgs);1574    break;1575 1576  case llvm::Triple::ve:1577    AddVETargetArgs(Args, CmdArgs);1578    break;1579  }1580}1581 1582namespace {1583void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,1584                      ArgStringList &CmdArgs) {1585  const char *ABIName = nullptr;1586  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))1587    ABIName = A->getValue();1588  else if (Triple.isOSDarwin())1589    ABIName = "darwinpcs";1590  // TODO: we probably want to have some target hook here.1591  else if (Triple.isOSLinux() &&1592           Triple.getEnvironment() == llvm::Triple::PAuthTest)1593    ABIName = "pauthtest";1594  else1595    ABIName = "aapcs";1596 1597  CmdArgs.push_back("-target-abi");1598  CmdArgs.push_back(ABIName);1599}1600}1601 1602void Clang::AddAArch64TargetArgs(const ArgList &Args,1603                                 ArgStringList &CmdArgs) const {1604  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();1605 1606  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||1607      Args.hasArg(options::OPT_mkernel) ||1608      Args.hasArg(options::OPT_fapple_kext))1609    CmdArgs.push_back("-disable-red-zone");1610 1611  if (!Args.hasFlag(options::OPT_mimplicit_float,1612                    options::OPT_mno_implicit_float, true))1613    CmdArgs.push_back("-no-implicit-float");1614 1615  RenderAArch64ABI(Triple, Args, CmdArgs);1616 1617  // Forward the -mglobal-merge option for explicit control over the pass.1618  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,1619                               options::OPT_mno_global_merge)) {1620    CmdArgs.push_back("-mllvm");1621    if (A->getOption().matches(options::OPT_mno_global_merge))1622      CmdArgs.push_back("-aarch64-enable-global-merge=false");1623    else1624      CmdArgs.push_back("-aarch64-enable-global-merge=true");1625  }1626 1627  // Handle -msve_vector_bits=<bits>1628  auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,1629                              StringRef VScaleMax) {1630    StringRef Val = A->getValue();1631    const Driver &D = getToolChain().getDriver();1632    if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||1633        Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||1634        Val == "1024+" || Val == "2048+") {1635      unsigned Bits = 0;1636      if (!Val.consume_back("+")) {1637        bool Invalid = Val.getAsInteger(10, Bits);1638        (void)Invalid;1639        assert(!Invalid && "Failed to parse value");1640        CmdArgs.push_back(1641            Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));1642      }1643 1644      bool Invalid = Val.getAsInteger(10, Bits);1645      (void)Invalid;1646      assert(!Invalid && "Failed to parse value");1647 1648      CmdArgs.push_back(1649          Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));1650    } else if (Val == "scalable") {1651      // Silently drop requests for vector-length agnostic code as it's implied.1652    } else {1653      // Handle the unsupported values passed to msve-vector-bits.1654      D.Diag(diag::err_drv_unsupported_option_argument)1655          << A->getSpelling() << Val;1656    }1657  };1658  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))1659    HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");1660  if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))1661    HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");1662 1663  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);1664 1665  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {1666    CmdArgs.push_back("-tune-cpu");1667    if (strcmp(A->getValue(), "native") == 0)1668      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));1669    else1670      CmdArgs.push_back(A->getValue());1671  }1672 1673  AddUnalignedAccessWarning(CmdArgs);1674 1675  if (Triple.isOSDarwin() ||1676      (Triple.isOSLinux() &&1677       Triple.getEnvironment() == llvm::Triple::PAuthTest)) {1678    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,1679                      options::OPT_fno_ptrauth_intrinsics);1680    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,1681                      options::OPT_fno_ptrauth_calls);1682    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,1683                      options::OPT_fno_ptrauth_returns);1684    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,1685                      options::OPT_fno_ptrauth_auth_traps);1686    Args.addOptInFlag(1687        CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,1688        options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);1689    Args.addOptInFlag(1690        CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,1691        options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);1692    Args.addOptInFlag(1693        CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,1694        options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);1695    Args.addOptInFlag(1696        CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,1697        options::OPT_fno_ptrauth_function_pointer_type_discrimination);1698    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,1699                      options::OPT_fno_ptrauth_indirect_gotos);1700  }1701  if (Triple.isOSLinux() &&1702      Triple.getEnvironment() == llvm::Triple::PAuthTest) {1703    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,1704                      options::OPT_fno_ptrauth_init_fini);1705    Args.addOptInFlag(1706        CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,1707        options::OPT_fno_ptrauth_init_fini_address_discrimination);1708    Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,1709                      options::OPT_fno_ptrauth_elf_got);1710  }1711  Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,1712                    options::OPT_fno_aarch64_jump_table_hardening);1713 1714  Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,1715                    options::OPT_fno_ptrauth_objc_isa);1716  Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,1717                    options::OPT_fno_ptrauth_objc_interface_sel);1718  Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,1719                    options::OPT_fno_ptrauth_objc_class_ro);1720 1721  // Enable/disable return address signing and indirect branch targets.1722  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);1723}1724 1725void Clang::AddLoongArchTargetArgs(const ArgList &Args,1726                                   ArgStringList &CmdArgs) const {1727  const llvm::Triple &Triple = getToolChain().getTriple();1728 1729  CmdArgs.push_back("-target-abi");1730  CmdArgs.push_back(1731      loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)1732          .data());1733 1734  // Handle -mtune.1735  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {1736    std::string TuneCPU = A->getValue();1737    TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);1738    CmdArgs.push_back("-tune-cpu");1739    CmdArgs.push_back(Args.MakeArgString(TuneCPU));1740  }1741 1742  if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,1743                               options::OPT_mno_annotate_tablejump)) {1744    if (A->getOption().matches(options::OPT_mannotate_tablejump)) {1745      CmdArgs.push_back("-mllvm");1746      CmdArgs.push_back("-loongarch-annotate-tablejump");1747    }1748  }1749}1750 1751void Clang::AddMIPSTargetArgs(const ArgList &Args,1752                              ArgStringList &CmdArgs) const {1753  const Driver &D = getToolChain().getDriver();1754  StringRef CPUName;1755  StringRef ABIName;1756  const llvm::Triple &Triple = getToolChain().getTriple();1757  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);1758 1759  CmdArgs.push_back("-target-abi");1760  CmdArgs.push_back(ABIName.data());1761 1762  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);1763  if (ABI == mips::FloatABI::Soft) {1764    // Floating point operations and argument passing are soft.1765    CmdArgs.push_back("-msoft-float");1766    CmdArgs.push_back("-mfloat-abi");1767    CmdArgs.push_back("soft");1768  } else {1769    // Floating point operations and argument passing are hard.1770    assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");1771    CmdArgs.push_back("-mfloat-abi");1772    CmdArgs.push_back("hard");1773  }1774 1775  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,1776                               options::OPT_mno_ldc1_sdc1)) {1777    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {1778      CmdArgs.push_back("-mllvm");1779      CmdArgs.push_back("-mno-ldc1-sdc1");1780    }1781  }1782 1783  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,1784                               options::OPT_mno_check_zero_division)) {1785    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {1786      CmdArgs.push_back("-mllvm");1787      CmdArgs.push_back("-mno-check-zero-division");1788    }1789  }1790 1791  if (Args.getLastArg(options::OPT_mfix4300)) {1792    CmdArgs.push_back("-mllvm");1793    CmdArgs.push_back("-mfix4300");1794  }1795 1796  if (Arg *A = Args.getLastArg(options::OPT_G)) {1797    StringRef v = A->getValue();1798    CmdArgs.push_back("-mllvm");1799    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));1800    A->claim();1801  }1802 1803  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);1804  Arg *ABICalls =1805      Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);1806 1807  // -mabicalls is the default for many MIPS environments, even with -fno-pic.1808  // -mgpopt is the default for static, -fno-pic environments but these two1809  // options conflict. We want to be certain that -mno-abicalls -mgpopt is1810  // the only case where -mllvm -mgpopt is passed.1811  // NOTE: We need a warning here or in the backend to warn when -mgpopt is1812  //       passed explicitly when compiling something with -mabicalls1813  //       (implictly) in affect. Currently the warning is in the backend.1814  //1815  // When the ABI in use is  N64, we also need to determine the PIC mode that1816  // is in use, as -fno-pic for N64 implies -mno-abicalls.1817  bool NoABICalls =1818      ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);1819 1820  llvm::Reloc::Model RelocationModel;1821  unsigned PICLevel;1822  bool IsPIE;1823  std::tie(RelocationModel, PICLevel, IsPIE) =1824      ParsePICArgs(getToolChain(), Args);1825 1826  NoABICalls = NoABICalls ||1827               (RelocationModel == llvm::Reloc::Static && ABIName == "n64");1828 1829  bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);1830  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.1831  if (NoABICalls && (!GPOpt || WantGPOpt)) {1832    CmdArgs.push_back("-mllvm");1833    CmdArgs.push_back("-mgpopt");1834 1835    Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,1836                                      options::OPT_mno_local_sdata);1837    Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,1838                                       options::OPT_mno_extern_sdata);1839    Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,1840                                        options::OPT_mno_embedded_data);1841    if (LocalSData) {1842      CmdArgs.push_back("-mllvm");1843      if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {1844        CmdArgs.push_back("-mlocal-sdata=1");1845      } else {1846        CmdArgs.push_back("-mlocal-sdata=0");1847      }1848      LocalSData->claim();1849    }1850 1851    if (ExternSData) {1852      CmdArgs.push_back("-mllvm");1853      if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {1854        CmdArgs.push_back("-mextern-sdata=1");1855      } else {1856        CmdArgs.push_back("-mextern-sdata=0");1857      }1858      ExternSData->claim();1859    }1860 1861    if (EmbeddedData) {1862      CmdArgs.push_back("-mllvm");1863      if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {1864        CmdArgs.push_back("-membedded-data=1");1865      } else {1866        CmdArgs.push_back("-membedded-data=0");1867      }1868      EmbeddedData->claim();1869    }1870 1871  } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)1872    D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);1873 1874  if (GPOpt)1875    GPOpt->claim();1876 1877  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {1878    StringRef Val = StringRef(A->getValue());1879    if (mips::hasCompactBranches(CPUName)) {1880      if (Val == "never" || Val == "always" || Val == "optimal") {1881        CmdArgs.push_back("-mllvm");1882        CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));1883      } else1884        D.Diag(diag::err_drv_unsupported_option_argument)1885            << A->getSpelling() << Val;1886    } else1887      D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;1888  }1889 1890  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,1891                               options::OPT_mno_relax_pic_calls)) {1892    if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {1893      CmdArgs.push_back("-mllvm");1894      CmdArgs.push_back("-mips-jalr-reloc=0");1895    }1896  }1897}1898 1899void Clang::AddPPCTargetArgs(const ArgList &Args,1900                             ArgStringList &CmdArgs) const {1901  const Driver &D = getToolChain().getDriver();1902  const llvm::Triple &T = getToolChain().getTriple();1903  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {1904    CmdArgs.push_back("-tune-cpu");1905    StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());1906    CmdArgs.push_back(Args.MakeArgString(CPU.str()));1907  }1908 1909  // Select the ABI to use.1910  const char *ABIName = nullptr;1911  if (T.isOSBinFormatELF()) {1912    switch (getToolChain().getArch()) {1913    case llvm::Triple::ppc64: {1914      if (T.isPPC64ELFv2ABI())1915        ABIName = "elfv2";1916      else1917        ABIName = "elfv1";1918      break;1919    }1920    case llvm::Triple::ppc64le:1921      ABIName = "elfv2";1922      break;1923    default:1924      break;1925    }1926  }1927 1928  bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();1929  bool VecExtabi = false;1930  for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {1931    StringRef V = A->getValue();1932    if (V == "ieeelongdouble") {1933      IEEELongDouble = true;1934      A->claim();1935    } else if (V == "ibmlongdouble") {1936      IEEELongDouble = false;1937      A->claim();1938    } else if (V == "vec-default") {1939      VecExtabi = false;1940      A->claim();1941    } else if (V == "vec-extabi") {1942      VecExtabi = true;1943      A->claim();1944    } else if (V == "elfv1") {1945      ABIName = "elfv1";1946      A->claim();1947    } else if (V == "elfv2") {1948      ABIName = "elfv2";1949      A->claim();1950    } else if (V != "altivec")1951      // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore1952      // the option if given as we don't have backend support for any targets1953      // that don't use the altivec abi.1954      ABIName = A->getValue();1955  }1956  if (IEEELongDouble)1957    CmdArgs.push_back("-mabi=ieeelongdouble");1958  if (VecExtabi) {1959    if (!T.isOSAIX())1960      D.Diag(diag::err_drv_unsupported_opt_for_target)1961          << "-mabi=vec-extabi" << T.str();1962    CmdArgs.push_back("-mabi=vec-extabi");1963  }1964 1965  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))1966    CmdArgs.push_back("-disable-red-zone");1967 1968  ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);1969  if (FloatABI == ppc::FloatABI::Soft) {1970    // Floating point operations and argument passing are soft.1971    CmdArgs.push_back("-msoft-float");1972    CmdArgs.push_back("-mfloat-abi");1973    CmdArgs.push_back("soft");1974  } else {1975    // Floating point operations and argument passing are hard.1976    assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");1977    CmdArgs.push_back("-mfloat-abi");1978    CmdArgs.push_back("hard");1979  }1980 1981  if (ABIName) {1982    CmdArgs.push_back("-target-abi");1983    CmdArgs.push_back(ABIName);1984  }1985}1986 1987void Clang::AddRISCVTargetArgs(const ArgList &Args,1988                               ArgStringList &CmdArgs) const {1989  const llvm::Triple &Triple = getToolChain().getTriple();1990  StringRef ABIName = riscv::getRISCVABI(Args, Triple);1991 1992  CmdArgs.push_back("-target-abi");1993  CmdArgs.push_back(ABIName.data());1994 1995  if (Arg *A = Args.getLastArg(options::OPT_G)) {1996    CmdArgs.push_back("-msmall-data-limit");1997    CmdArgs.push_back(A->getValue());1998  }1999 2000  if (!Args.hasFlag(options::OPT_mimplicit_float,2001                    options::OPT_mno_implicit_float, true))2002    CmdArgs.push_back("-no-implicit-float");2003 2004  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {2005    CmdArgs.push_back("-tune-cpu");2006    if (strcmp(A->getValue(), "native") == 0)2007      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));2008    else2009      CmdArgs.push_back(A->getValue());2010  }2011 2012  // Handle -mrvv-vector-bits=<bits>2013  if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {2014    StringRef Val = A->getValue();2015    const Driver &D = getToolChain().getDriver();2016 2017    // Get minimum VLen from march.2018    unsigned MinVLen = 0;2019    std::string Arch = riscv::getRISCVArch(Args, Triple);2020    auto ISAInfo = llvm::RISCVISAInfo::parseArchString(2021        Arch, /*EnableExperimentalExtensions*/ true);2022    // Ignore parsing error.2023    if (!errorToBool(ISAInfo.takeError()))2024      MinVLen = (*ISAInfo)->getMinVLen();2025 2026    // If the value is "zvl", use MinVLen from march. Otherwise, try to parse2027    // as integer as long as we have a MinVLen.2028    unsigned Bits = 0;2029    if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {2030      Bits = MinVLen;2031    } else if (!Val.getAsInteger(10, Bits)) {2032      // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that2033      // at least MinVLen.2034      if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||2035          Bits > 65536 || !llvm::isPowerOf2_32(Bits))2036        Bits = 0;2037    }2038 2039    // If we got a valid value try to use it.2040    if (Bits != 0) {2041      unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;2042      CmdArgs.push_back(2043          Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));2044      CmdArgs.push_back(2045          Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));2046    } else if (Val != "scalable") {2047      // Handle the unsupported values passed to mrvv-vector-bits.2048      D.Diag(diag::err_drv_unsupported_option_argument)2049          << A->getSpelling() << Val;2050    }2051  }2052}2053 2054void Clang::AddSparcTargetArgs(const ArgList &Args,2055                               ArgStringList &CmdArgs) const {2056  sparc::FloatABI FloatABI =2057      sparc::getSparcFloatABI(getToolChain().getDriver(), Args);2058 2059  if (FloatABI == sparc::FloatABI::Soft) {2060    // Floating point operations and argument passing are soft.2061    CmdArgs.push_back("-msoft-float");2062    CmdArgs.push_back("-mfloat-abi");2063    CmdArgs.push_back("soft");2064  } else {2065    // Floating point operations and argument passing are hard.2066    assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");2067    CmdArgs.push_back("-mfloat-abi");2068    CmdArgs.push_back("hard");2069  }2070 2071  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {2072    StringRef Name = A->getValue();2073    std::string TuneCPU;2074    if (Name == "native")2075      TuneCPU = std::string(llvm::sys::getHostCPUName());2076    else2077      TuneCPU = std::string(Name);2078 2079    CmdArgs.push_back("-tune-cpu");2080    CmdArgs.push_back(Args.MakeArgString(TuneCPU));2081  }2082}2083 2084void Clang::AddSystemZTargetArgs(const ArgList &Args,2085                                 ArgStringList &CmdArgs) const {2086  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {2087    CmdArgs.push_back("-tune-cpu");2088    if (strcmp(A->getValue(), "native") == 0)2089      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));2090    else2091      CmdArgs.push_back(A->getValue());2092  }2093 2094  bool HasBackchain =2095      Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);2096  bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,2097                                     options::OPT_mno_packed_stack, false);2098  systemz::FloatABI FloatABI =2099      systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);2100  bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);2101  if (HasBackchain && HasPackedStack && !HasSoftFloat) {2102    const Driver &D = getToolChain().getDriver();2103    D.Diag(diag::err_drv_unsupported_opt)2104      << "-mpacked-stack -mbackchain -mhard-float";2105  }2106  if (HasBackchain)2107    CmdArgs.push_back("-mbackchain");2108  if (HasPackedStack)2109    CmdArgs.push_back("-mpacked-stack");2110  if (HasSoftFloat) {2111    // Floating point operations and argument passing are soft.2112    CmdArgs.push_back("-msoft-float");2113    CmdArgs.push_back("-mfloat-abi");2114    CmdArgs.push_back("soft");2115  }2116}2117 2118void Clang::AddX86TargetArgs(const ArgList &Args,2119                             ArgStringList &CmdArgs) const {2120  const Driver &D = getToolChain().getDriver();2121  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);2122 2123  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||2124      Args.hasArg(options::OPT_mkernel) ||2125      Args.hasArg(options::OPT_fapple_kext))2126    CmdArgs.push_back("-disable-red-zone");2127 2128  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,2129                    options::OPT_mno_tls_direct_seg_refs, true))2130    CmdArgs.push_back("-mno-tls-direct-seg-refs");2131 2132  // Default to avoid implicit floating-point for kernel/kext code, but allow2133  // that to be overridden with -mno-soft-float.2134  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||2135                          Args.hasArg(options::OPT_fapple_kext));2136  if (Arg *A = Args.getLastArg(2137          options::OPT_msoft_float, options::OPT_mno_soft_float,2138          options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {2139    const Option &O = A->getOption();2140    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||2141                       O.matches(options::OPT_msoft_float));2142  }2143  if (NoImplicitFloat)2144    CmdArgs.push_back("-no-implicit-float");2145 2146  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {2147    StringRef Value = A->getValue();2148    if (Value == "intel" || Value == "att") {2149      CmdArgs.push_back("-mllvm");2150      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));2151      CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));2152    } else {2153      D.Diag(diag::err_drv_unsupported_option_argument)2154          << A->getSpelling() << Value;2155    }2156  } else if (D.IsCLMode()) {2157    CmdArgs.push_back("-mllvm");2158    CmdArgs.push_back("-x86-asm-syntax=intel");2159  }2160 2161  if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,2162                               options::OPT_mno_skip_rax_setup))2163    if (A->getOption().matches(options::OPT_mskip_rax_setup))2164      CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));2165 2166  // Set flags to support MCU ABI.2167  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {2168    CmdArgs.push_back("-mfloat-abi");2169    CmdArgs.push_back("soft");2170    CmdArgs.push_back("-mstack-alignment=4");2171  }2172 2173  // Handle -mtune.2174 2175  // Default to "generic" unless -march is present or targetting the PS4/PS5.2176  std::string TuneCPU;2177  if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())2178    TuneCPU = "generic";2179 2180  // Override based on -mtune.2181  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {2182    StringRef Name = A->getValue();2183 2184    if (Name == "native") {2185      Name = llvm::sys::getHostCPUName();2186      if (!Name.empty())2187        TuneCPU = std::string(Name);2188    } else2189      TuneCPU = std::string(Name);2190  }2191 2192  if (!TuneCPU.empty()) {2193    CmdArgs.push_back("-tune-cpu");2194    CmdArgs.push_back(Args.MakeArgString(TuneCPU));2195  }2196}2197 2198void Clang::AddHexagonTargetArgs(const ArgList &Args,2199                                 ArgStringList &CmdArgs) const {2200  CmdArgs.push_back("-mqdsp6-compat");2201  CmdArgs.push_back("-Wreturn-type");2202 2203  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {2204    CmdArgs.push_back("-mllvm");2205    CmdArgs.push_back(2206        Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));2207  }2208 2209  if (!Args.hasArg(options::OPT_fno_short_enums))2210    CmdArgs.push_back("-fshort-enums");2211  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {2212    CmdArgs.push_back("-mllvm");2213    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");2214  }2215  CmdArgs.push_back("-mllvm");2216  CmdArgs.push_back("-machine-sink-split=0");2217}2218 2219void Clang::AddLanaiTargetArgs(const ArgList &Args,2220                               ArgStringList &CmdArgs) const {2221  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {2222    StringRef CPUName = A->getValue();2223 2224    CmdArgs.push_back("-target-cpu");2225    CmdArgs.push_back(Args.MakeArgString(CPUName));2226  }2227  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {2228    StringRef Value = A->getValue();2229    // Only support mregparm=4 to support old usage. Report error for all other2230    // cases.2231    int Mregparm;2232    if (Value.getAsInteger(10, Mregparm)) {2233      if (Mregparm != 4) {2234        getToolChain().getDriver().Diag(2235            diag::err_drv_unsupported_option_argument)2236            << A->getSpelling() << Value;2237      }2238    }2239  }2240}2241 2242void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,2243                                     ArgStringList &CmdArgs) const {2244  // Default to "hidden" visibility.2245  if (!Args.hasArg(options::OPT_fvisibility_EQ,2246                   options::OPT_fvisibility_ms_compat))2247    CmdArgs.push_back("-fvisibility=hidden");2248}2249 2250void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {2251  // Floating point operations and argument passing are hard.2252  CmdArgs.push_back("-mfloat-abi");2253  CmdArgs.push_back("hard");2254}2255 2256void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,2257                                    StringRef Target, const InputInfo &Output,2258                                    const InputInfo &Input, const ArgList &Args) const {2259  // If this is a dry run, do not create the compilation database file.2260  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))2261    return;2262 2263  using llvm::yaml::escape;2264  const Driver &D = getToolChain().getDriver();2265 2266  if (!CompilationDatabase) {2267    std::error_code EC;2268    auto File = std::make_unique<llvm::raw_fd_ostream>(2269        Filename, EC,2270        llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);2271    if (EC) {2272      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename2273                                                       << EC.message();2274      return;2275    }2276    CompilationDatabase = std::move(File);2277  }2278  auto &CDB = *CompilationDatabase;2279  auto CWD = D.getVFS().getCurrentWorkingDirectory();2280  if (!CWD)2281    CWD = ".";2282  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";2283  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";2284  if (Output.isFilename())2285    CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";2286  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";2287  SmallString<128> Buf;2288  Buf = "-x";2289  Buf += types::getTypeName(Input.getType());2290  CDB << ", \"" << escape(Buf) << "\"";2291  if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {2292    Buf = "--sysroot=";2293    Buf += D.SysRoot;2294    CDB << ", \"" << escape(Buf) << "\"";2295  }2296  CDB << ", \"" << escape(Input.getFilename()) << "\"";2297  if (Output.isFilename())2298    CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";2299  for (auto &A: Args) {2300    auto &O = A->getOption();2301    // Skip language selection, which is positional.2302    if (O.getID() == options::OPT_x)2303      continue;2304    // Skip writing dependency output and the compilation database itself.2305    if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)2306      continue;2307    if (O.getID() == options::OPT_gen_cdb_fragment_path)2308      continue;2309    // Skip inputs.2310    if (O.getKind() == Option::InputClass)2311      continue;2312    // Skip output.2313    if (O.getID() == options::OPT_o)2314      continue;2315    // All other arguments are quoted and appended.2316    ArgStringList ASL;2317    A->render(Args, ASL);2318    for (auto &it: ASL)2319      CDB << ", \"" << escape(it) << "\"";2320  }2321  Buf = "--target=";2322  Buf += Target;2323  CDB << ", \"" << escape(Buf) << "\"]},\n";2324}2325 2326void Clang::DumpCompilationDatabaseFragmentToDir(2327    StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,2328    const InputInfo &Input, const llvm::opt::ArgList &Args) const {2329  // If this is a dry run, do not create the compilation database file.2330  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))2331    return;2332 2333  if (CompilationDatabase)2334    DumpCompilationDatabase(C, "", Target, Output, Input, Args);2335 2336  SmallString<256> Path = Dir;2337  const auto &Driver = C.getDriver();2338  Driver.getVFS().makeAbsolute(Path);2339  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);2340  if (Err) {2341    Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();2342    return;2343  }2344 2345  llvm::sys::path::append(2346      Path,2347      Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");2348  int FD;2349  SmallString<256> TempPath;2350  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,2351                                        llvm::sys::fs::OF_Text);2352  if (Err) {2353    Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();2354    return;2355  }2356  CompilationDatabase =2357      std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);2358  DumpCompilationDatabase(C, "", Target, Output, Input, Args);2359}2360 2361static bool CheckARMImplicitITArg(StringRef Value) {2362  return Value == "always" || Value == "never" || Value == "arm" ||2363         Value == "thumb";2364}2365 2366static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,2367                                 StringRef Value) {2368  CmdArgs.push_back("-mllvm");2369  CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));2370}2371 2372static void CollectArgsForIntegratedAssembler(Compilation &C,2373                                              const ArgList &Args,2374                                              ArgStringList &CmdArgs,2375                                              const Driver &D) {2376  // Default to -mno-relax-all.2377  //2378  // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This2379  // cannot be done by assembler branch relaxation as it needs a free temporary2380  // register. Because of this, branch relaxation is handled by a MachineIR pass2381  // before the assembler. Forcing assembler branch relaxation for -O0 makes the2382  // MachineIR branch relaxation inaccurate and it will miss cases where an2383  // indirect branch is necessary.2384  Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,2385                    options::OPT_mno_relax_all);2386 2387  // Only default to -mincremental-linker-compatible if we think we are2388  // targeting the MSVC linker.2389  bool DefaultIncrementalLinkerCompatible =2390      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();2391  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,2392                   options::OPT_mno_incremental_linker_compatible,2393                   DefaultIncrementalLinkerCompatible))2394    CmdArgs.push_back("-mincremental-linker-compatible");2395 2396  Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);2397 2398  Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,2399                    options::OPT_fno_emit_compact_unwind_non_canonical);2400 2401  // If you add more args here, also add them to the block below that2402  // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".2403 2404  // When passing -I arguments to the assembler we sometimes need to2405  // unconditionally take the next argument.  For example, when parsing2406  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the2407  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'2408  // arg after parsing the '-I' arg.2409  bool TakeNextArg = false;2410 2411  const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();2412  bool IsELF = Triple.isOSBinFormatELF();2413  bool Crel = false, ExperimentalCrel = false;2414  bool ImplicitMapSyms = false;2415  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();2416  bool UseNoExecStack = false;2417  bool Msa = false;2418  const char *MipsTargetFeature = nullptr;2419  llvm::SmallVector<const char *> SparcTargetFeatures;2420  StringRef ImplicitIt;2421  for (const Arg *A :2422       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,2423                     options::OPT_mimplicit_it_EQ)) {2424    A->claim();2425 2426    if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {2427      switch (C.getDefaultToolChain().getArch()) {2428      case llvm::Triple::arm:2429      case llvm::Triple::armeb:2430      case llvm::Triple::thumb:2431      case llvm::Triple::thumbeb:2432        // Only store the value; the last value set takes effect.2433        ImplicitIt = A->getValue();2434        if (!CheckARMImplicitITArg(ImplicitIt))2435          D.Diag(diag::err_drv_unsupported_option_argument)2436              << A->getSpelling() << ImplicitIt;2437        continue;2438      default:2439        break;2440      }2441    }2442 2443    for (StringRef Value : A->getValues()) {2444      if (TakeNextArg) {2445        CmdArgs.push_back(Value.data());2446        TakeNextArg = false;2447        continue;2448      }2449 2450      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&2451          Value == "-mbig-obj")2452        continue; // LLVM handles bigobj automatically2453 2454      auto Equal = Value.split('=');2455      auto checkArg = [&](bool ValidTarget,2456                          std::initializer_list<const char *> Set) {2457        if (!ValidTarget) {2458          D.Diag(diag::err_drv_unsupported_opt_for_target)2459              << (Twine("-Wa,") + Equal.first + "=").str()2460              << Triple.getTriple();2461        } else if (!llvm::is_contained(Set, Equal.second)) {2462          D.Diag(diag::err_drv_unsupported_option_argument)2463              << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;2464        }2465      };2466      switch (C.getDefaultToolChain().getArch()) {2467      default:2468        break;2469      case llvm::Triple::x86:2470      case llvm::Triple::x86_64:2471        if (Equal.first == "-mrelax-relocations" ||2472            Equal.first == "--mrelax-relocations") {2473          UseRelaxRelocations = Equal.second == "yes";2474          checkArg(IsELF, {"yes", "no"});2475          continue;2476        }2477        if (Value == "-msse2avx") {2478          CmdArgs.push_back("-msse2avx");2479          continue;2480        }2481        break;2482      case llvm::Triple::wasm32:2483      case llvm::Triple::wasm64:2484        if (Value == "--no-type-check") {2485          CmdArgs.push_back("-mno-type-check");2486          continue;2487        }2488        break;2489      case llvm::Triple::thumb:2490      case llvm::Triple::thumbeb:2491      case llvm::Triple::arm:2492      case llvm::Triple::armeb:2493        if (Equal.first == "-mimplicit-it") {2494          // Only store the value; the last value set takes effect.2495          ImplicitIt = Equal.second;2496          checkArg(true, {"always", "never", "arm", "thumb"});2497          continue;2498        }2499        if (Value == "-mthumb")2500          // -mthumb has already been processed in ComputeLLVMTriple()2501          // recognize but skip over here.2502          continue;2503        break;2504      case llvm::Triple::aarch64:2505      case llvm::Triple::aarch64_be:2506      case llvm::Triple::aarch64_32:2507        if (Equal.first == "-mmapsyms") {2508          ImplicitMapSyms = Equal.second == "implicit";2509          checkArg(IsELF, {"default", "implicit"});2510          continue;2511        }2512        break;2513      case llvm::Triple::mips:2514      case llvm::Triple::mipsel:2515      case llvm::Triple::mips64:2516      case llvm::Triple::mips64el:2517        if (Value == "--trap") {2518          CmdArgs.push_back("-target-feature");2519          CmdArgs.push_back("+use-tcc-in-div");2520          continue;2521        }2522        if (Value == "--break") {2523          CmdArgs.push_back("-target-feature");2524          CmdArgs.push_back("-use-tcc-in-div");2525          continue;2526        }2527        if (Value.starts_with("-msoft-float")) {2528          CmdArgs.push_back("-target-feature");2529          CmdArgs.push_back("+soft-float");2530          continue;2531        }2532        if (Value.starts_with("-mhard-float")) {2533          CmdArgs.push_back("-target-feature");2534          CmdArgs.push_back("-soft-float");2535          continue;2536        }2537        if (Value == "-mmsa") {2538          Msa = true;2539          continue;2540        }2541        if (Value == "-mno-msa") {2542          Msa = false;2543          continue;2544        }2545        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)2546                                .Case("-mips1", "+mips1")2547                                .Case("-mips2", "+mips2")2548                                .Case("-mips3", "+mips3")2549                                .Case("-mips4", "+mips4")2550                                .Case("-mips5", "+mips5")2551                                .Case("-mips32", "+mips32")2552                                .Case("-mips32r2", "+mips32r2")2553                                .Case("-mips32r3", "+mips32r3")2554                                .Case("-mips32r5", "+mips32r5")2555                                .Case("-mips32r6", "+mips32r6")2556                                .Case("-mips64", "+mips64")2557                                .Case("-mips64r2", "+mips64r2")2558                                .Case("-mips64r3", "+mips64r3")2559                                .Case("-mips64r5", "+mips64r5")2560                                .Case("-mips64r6", "+mips64r6")2561                                .Default(nullptr);2562        if (MipsTargetFeature)2563          continue;2564        break;2565 2566      case llvm::Triple::sparc:2567      case llvm::Triple::sparcel:2568      case llvm::Triple::sparcv9:2569        if (Value == "--undeclared-regs") {2570          // LLVM already allows undeclared use of G registers, so this option2571          // becomes a no-op. This solely exists for GNU compatibility.2572          // TODO implement --no-undeclared-regs2573          continue;2574        }2575        SparcTargetFeatures =2576            llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)2577                .Case("-Av8", {"-v8plus"})2578                .Case("-Av8plus", {"+v8plus", "+v9"})2579                .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})2580                .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})2581                .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})2582                .Case("-Av9", {"+v9"})2583                .Case("-Av9a", {"+v9", "+vis"})2584                .Case("-Av9b", {"+v9", "+vis", "+vis2"})2585                .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})2586                .Default({});2587        if (!SparcTargetFeatures.empty())2588          continue;2589        break;2590      }2591 2592      if (Value == "-force_cpusubtype_ALL") {2593        // Do nothing, this is the default and we don't support anything else.2594      } else if (Value == "-L") {2595        CmdArgs.push_back("-msave-temp-labels");2596      } else if (Value == "--fatal-warnings") {2597        CmdArgs.push_back("-massembler-fatal-warnings");2598      } else if (Value == "--no-warn" || Value == "-W") {2599        CmdArgs.push_back("-massembler-no-warn");2600      } else if (Value == "--noexecstack") {2601        UseNoExecStack = true;2602      } else if (Value.starts_with("-compress-debug-sections") ||2603                 Value.starts_with("--compress-debug-sections") ||2604                 Value == "-nocompress-debug-sections" ||2605                 Value == "--nocompress-debug-sections") {2606        CmdArgs.push_back(Value.data());2607      } else if (Value == "--crel") {2608        Crel = true;2609      } else if (Value == "--no-crel") {2610        Crel = false;2611      } else if (Value == "--allow-experimental-crel") {2612        ExperimentalCrel = true;2613      } else if (Value.starts_with("-I")) {2614        CmdArgs.push_back(Value.data());2615        // We need to consume the next argument if the current arg is a plain2616        // -I. The next arg will be the include directory.2617        if (Value == "-I")2618          TakeNextArg = true;2619      } else if (Value.starts_with("-gdwarf-")) {2620        // "-gdwarf-N" options are not cc1as options.2621        unsigned DwarfVersion = DwarfVersionNum(Value);2622        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.2623          CmdArgs.push_back(Value.data());2624        } else {2625          RenderDebugEnablingArgs(Args, CmdArgs,2626                                  llvm::codegenoptions::DebugInfoConstructor,2627                                  DwarfVersion, llvm::DebuggerKind::Default);2628        }2629      } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||2630                 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {2631        // Do nothing, we'll validate it later.2632      } else if (Value == "-defsym" || Value == "--defsym") {2633        if (A->getNumValues() != 2) {2634          D.Diag(diag::err_drv_defsym_invalid_format) << Value;2635          break;2636        }2637        const char *S = A->getValue(1);2638        auto Pair = StringRef(S).split('=');2639        auto Sym = Pair.first;2640        auto SVal = Pair.second;2641 2642        if (Sym.empty() || SVal.empty()) {2643          D.Diag(diag::err_drv_defsym_invalid_format) << S;2644          break;2645        }2646        int64_t IVal;2647        if (SVal.getAsInteger(0, IVal)) {2648          D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;2649          break;2650        }2651        CmdArgs.push_back("--defsym");2652        TakeNextArg = true;2653      } else if (Value == "-fdebug-compilation-dir") {2654        CmdArgs.push_back("-fdebug-compilation-dir");2655        TakeNextArg = true;2656      } else if (Value.consume_front("-fdebug-compilation-dir=")) {2657        // The flag is a -Wa / -Xassembler argument and Options doesn't2658        // parse the argument, so this isn't automatically aliased to2659        // -fdebug-compilation-dir (without '=') here.2660        CmdArgs.push_back("-fdebug-compilation-dir");2661        CmdArgs.push_back(Value.data());2662      } else if (Value == "--version") {2663        D.PrintVersion(C, llvm::outs());2664      } else {2665        D.Diag(diag::err_drv_unsupported_option_argument)2666            << A->getSpelling() << Value;2667      }2668    }2669  }2670  if (ImplicitIt.size())2671    AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);2672  if (Crel) {2673    if (!ExperimentalCrel)2674      D.Diag(diag::err_drv_experimental_crel);2675    if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {2676      CmdArgs.push_back("--crel");2677    } else {2678      D.Diag(diag::err_drv_unsupported_opt_for_target)2679          << "-Wa,--crel" << D.getTargetTriple();2680    }2681  }2682  if (ImplicitMapSyms)2683    CmdArgs.push_back("-mmapsyms=implicit");2684  if (Msa)2685    CmdArgs.push_back("-mmsa");2686  if (!UseRelaxRelocations)2687    CmdArgs.push_back("-mrelax-relocations=no");2688  if (UseNoExecStack)2689    CmdArgs.push_back("-mnoexecstack");2690  if (MipsTargetFeature != nullptr) {2691    CmdArgs.push_back("-target-feature");2692    CmdArgs.push_back(MipsTargetFeature);2693  }2694 2695  for (const char *Feature : SparcTargetFeatures) {2696    CmdArgs.push_back("-target-feature");2697    CmdArgs.push_back(Feature);2698  }2699 2700  // forward -fembed-bitcode to assmebler2701  if (C.getDriver().embedBitcodeEnabled() ||2702      C.getDriver().embedBitcodeMarkerOnly())2703    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);2704 2705  if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {2706    CmdArgs.push_back("-as-secure-log-file");2707    CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));2708  }2709}2710 2711static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,2712                                       bool OFastEnabled, const ArgList &Args,2713                                       ArgStringList &CmdArgs,2714                                       const JobAction &JA) {2715  // List of veclibs which when used with -fveclib imply -fno-math-errno.2716  constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),2717                                                llvm::StringLiteral("SLEEF")};2718  bool NoMathErrnoWasImpliedByVecLib = false;2719  const Arg *VecLibArg = nullptr;2720  // Track the arg (if any) that enabled errno after -fveclib for diagnostics.2721  const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;2722 2723  // Handle various floating point optimization flags, mapping them to the2724  // appropriate LLVM code generation flags. This is complicated by several2725  // "umbrella" flags, so we do this by stepping through the flags incrementally2726  // adjusting what we think is enabled/disabled, then at the end setting the2727  // LLVM flags based on the final state.2728  bool HonorINFs = true;2729  bool HonorNaNs = true;2730  bool ApproxFunc = false;2731  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.2732  bool MathErrno = TC.IsMathErrnoDefault();2733  bool AssociativeMath = false;2734  bool ReciprocalMath = false;2735  bool SignedZeros = true;2736  bool TrappingMath = false; // Implemented via -ffp-exception-behavior2737  bool TrappingMathPresent = false; // Is trapping-math in args, and not2738                                    // overriden by ffp-exception-behavior?2739  bool RoundingFPMath = false;2740  // -ffp-model values: strict, fast, precise2741  StringRef FPModel = "";2742  // -ffp-exception-behavior options: strict, maytrap, ignore2743  StringRef FPExceptionBehavior = "";2744  // -ffp-eval-method options: double, extended, source2745  StringRef FPEvalMethod = "";2746  llvm::DenormalMode DenormalFPMath =2747      TC.getDefaultDenormalModeForType(Args, JA);2748  llvm::DenormalMode DenormalFP32Math =2749      TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());2750 2751  // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.2752  // If one wasn't given by the user, don't pass it here.2753  StringRef FPContract;2754  StringRef LastSeenFfpContractOption;2755  StringRef LastFpContractOverrideOption;2756  bool SeenUnsafeMathModeOption = false;2757  if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&2758      !JA.isOffloading(Action::OFK_HIP))2759    FPContract = "on";2760  bool StrictFPModel = false;2761  StringRef Float16ExcessPrecision = "";2762  StringRef BFloat16ExcessPrecision = "";2763  LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;2764  std::string ComplexRangeStr;2765  StringRef LastComplexRangeOption;2766 2767  // Lambda to set fast-math options. This is also used by -ffp-model=fast2768  auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {2769    if (Aggressive) {2770      HonorINFs = false;2771      HonorNaNs = false;2772      setComplexRange(D, CallerOption, LangOptions::ComplexRangeKind::CX_Basic,2773                      LastComplexRangeOption, Range);2774    } else {2775      HonorINFs = true;2776      HonorNaNs = true;2777      setComplexRange(D, CallerOption,2778                      LangOptions::ComplexRangeKind::CX_Promoted,2779                      LastComplexRangeOption, Range);2780    }2781    MathErrno = false;2782    AssociativeMath = true;2783    ReciprocalMath = true;2784    ApproxFunc = true;2785    SignedZeros = false;2786    TrappingMath = false;2787    RoundingFPMath = false;2788    FPExceptionBehavior = "";2789    FPContract = "fast";2790    SeenUnsafeMathModeOption = true;2791  };2792 2793  // Lambda to consolidate common handling for fp-contract2794  auto restoreFPContractState = [&]() {2795    // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.2796    // For other targets, if the state has been changed by one of the2797    // unsafe-math umbrella options a subsequent -fno-fast-math or2798    // -fno-unsafe-math-optimizations option reverts to the last value seen for2799    // the -ffp-contract option or "on" if we have not seen the -ffp-contract2800    // option. If we have not seen an unsafe-math option or -ffp-contract,2801    // we leave the FPContract state unchanged.2802    if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&2803        !JA.isOffloading(Action::OFK_HIP)) {2804      if (LastSeenFfpContractOption != "")2805        FPContract = LastSeenFfpContractOption;2806      else if (SeenUnsafeMathModeOption)2807        FPContract = "on";2808    }2809    // In this case, we're reverting to the last explicit fp-contract option2810    // or the platform default2811    LastFpContractOverrideOption = "";2812  };2813 2814  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {2815    CmdArgs.push_back("-mlimit-float-precision");2816    CmdArgs.push_back(A->getValue());2817  }2818 2819  for (const Arg *A : Args) {2820    auto CheckMathErrnoForVecLib =2821        llvm::make_scope_exit([&, MathErrnoBeforeArg = MathErrno] {2822          if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)2823            ArgThatEnabledMathErrnoAfterVecLib = A;2824        });2825 2826    switch (A->getOption().getID()) {2827    // If this isn't an FP option skip the claim below2828    default: continue;2829 2830    case options::OPT_fcx_limited_range:2831      setComplexRange(D, A->getSpelling(),2832                      LangOptions::ComplexRangeKind::CX_Basic,2833                      LastComplexRangeOption, Range);2834      break;2835    case options::OPT_fno_cx_limited_range:2836      setComplexRange(D, A->getSpelling(),2837                      LangOptions::ComplexRangeKind::CX_Full,2838                      LastComplexRangeOption, Range);2839      break;2840    case options::OPT_fcx_fortran_rules:2841      setComplexRange(D, A->getSpelling(),2842                      LangOptions::ComplexRangeKind::CX_Improved,2843                      LastComplexRangeOption, Range);2844      break;2845    case options::OPT_fno_cx_fortran_rules:2846      setComplexRange(D, A->getSpelling(),2847                      LangOptions::ComplexRangeKind::CX_Full,2848                      LastComplexRangeOption, Range);2849      break;2850    case options::OPT_fcomplex_arithmetic_EQ: {2851      LangOptions::ComplexRangeKind RangeVal;2852      StringRef Val = A->getValue();2853      if (Val == "full")2854        RangeVal = LangOptions::ComplexRangeKind::CX_Full;2855      else if (Val == "improved")2856        RangeVal = LangOptions::ComplexRangeKind::CX_Improved;2857      else if (Val == "promoted")2858        RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;2859      else if (Val == "basic")2860        RangeVal = LangOptions::ComplexRangeKind::CX_Basic;2861      else {2862        D.Diag(diag::err_drv_unsupported_option_argument)2863            << A->getSpelling() << Val;2864        break;2865      }2866      setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,2867                      LastComplexRangeOption, Range);2868      break;2869    }2870    case options::OPT_ffp_model_EQ: {2871      // If -ffp-model= is seen, reset to fno-fast-math2872      HonorINFs = true;2873      HonorNaNs = true;2874      ApproxFunc = false;2875      // Turning *off* -ffast-math restores the toolchain default.2876      MathErrno = TC.IsMathErrnoDefault();2877      AssociativeMath = false;2878      ReciprocalMath = false;2879      SignedZeros = true;2880 2881      StringRef Val = A->getValue();2882      if (OFastEnabled && Val != "aggressive") {2883        // Only -ffp-model=aggressive is compatible with -OFast, ignore.2884        D.Diag(clang::diag::warn_drv_overriding_option)2885            << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";2886        break;2887      }2888      StrictFPModel = false;2889      if (!FPModel.empty() && FPModel != Val)2890        D.Diag(clang::diag::warn_drv_overriding_option)2891            << Args.MakeArgString("-ffp-model=" + FPModel)2892            << Args.MakeArgString("-ffp-model=" + Val);2893      if (Val == "fast") {2894        FPModel = Val;2895        applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));2896        // applyFastMath sets fp-contract="fast"2897        LastFpContractOverrideOption = "-ffp-model=fast";2898      } else if (Val == "aggressive") {2899        FPModel = Val;2900        applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));2901        // applyFastMath sets fp-contract="fast"2902        LastFpContractOverrideOption = "-ffp-model=aggressive";2903      } else if (Val == "precise") {2904        FPModel = Val;2905        FPContract = "on";2906        LastFpContractOverrideOption = "-ffp-model=precise";2907        setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),2908                        LangOptions::ComplexRangeKind::CX_Full,2909                        LastComplexRangeOption, Range);2910      } else if (Val == "strict") {2911        StrictFPModel = true;2912        FPExceptionBehavior = "strict";2913        FPModel = Val;2914        FPContract = "off";2915        LastFpContractOverrideOption = "-ffp-model=strict";2916        TrappingMath = true;2917        RoundingFPMath = true;2918        setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),2919                        LangOptions::ComplexRangeKind::CX_Full,2920                        LastComplexRangeOption, Range);2921      } else2922        D.Diag(diag::err_drv_unsupported_option_argument)2923            << A->getSpelling() << Val;2924      break;2925    }2926 2927    // Options controlling individual features2928    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;2929    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;2930    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;2931    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;2932    case options::OPT_fapprox_func:         ApproxFunc = true;        break;2933    case options::OPT_fno_approx_func:      ApproxFunc = false;       break;2934    case options::OPT_fmath_errno:          MathErrno = true;         break;2935    case options::OPT_fno_math_errno:       MathErrno = false;        break;2936    case options::OPT_fassociative_math:    AssociativeMath = true;   break;2937    case options::OPT_fno_associative_math: AssociativeMath = false;  break;2938    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;2939    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;2940    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;2941    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;2942    case options::OPT_ftrapping_math:2943      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&2944          FPExceptionBehavior != "strict")2945        // Warn that previous value of option is overridden.2946        D.Diag(clang::diag::warn_drv_overriding_option)2947            << Args.MakeArgString("-ffp-exception-behavior=" +2948                                  FPExceptionBehavior)2949            << "-ftrapping-math";2950      TrappingMath = true;2951      TrappingMathPresent = true;2952      FPExceptionBehavior = "strict";2953      break;2954    case options::OPT_fveclib:2955      VecLibArg = A;2956      NoMathErrnoWasImpliedByVecLib =2957          llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());2958      if (NoMathErrnoWasImpliedByVecLib)2959        MathErrno = false;2960      break;2961    case options::OPT_fno_trapping_math:2962      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&2963          FPExceptionBehavior != "ignore")2964        // Warn that previous value of option is overridden.2965        D.Diag(clang::diag::warn_drv_overriding_option)2966            << Args.MakeArgString("-ffp-exception-behavior=" +2967                                  FPExceptionBehavior)2968            << "-fno-trapping-math";2969      TrappingMath = false;2970      TrappingMathPresent = true;2971      FPExceptionBehavior = "ignore";2972      break;2973 2974    case options::OPT_frounding_math:2975      RoundingFPMath = true;2976      break;2977 2978    case options::OPT_fno_rounding_math:2979      RoundingFPMath = false;2980      break;2981 2982    case options::OPT_fdenormal_fp_math_EQ:2983      DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());2984      DenormalFP32Math = DenormalFPMath;2985      if (!DenormalFPMath.isValid()) {2986        D.Diag(diag::err_drv_invalid_value)2987            << A->getAsString(Args) << A->getValue();2988      }2989      break;2990 2991    case options::OPT_fdenormal_fp_math_f32_EQ:2992      DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());2993      if (!DenormalFP32Math.isValid()) {2994        D.Diag(diag::err_drv_invalid_value)2995            << A->getAsString(Args) << A->getValue();2996      }2997      break;2998 2999    // Validate and pass through -ffp-contract option.3000    case options::OPT_ffp_contract: {3001      StringRef Val = A->getValue();3002      if (Val == "fast" || Val == "on" || Val == "off" ||3003          Val == "fast-honor-pragmas") {3004        if (Val != FPContract && LastFpContractOverrideOption != "") {3005          D.Diag(clang::diag::warn_drv_overriding_option)3006              << LastFpContractOverrideOption3007              << Args.MakeArgString("-ffp-contract=" + Val);3008        }3009 3010        FPContract = Val;3011        LastSeenFfpContractOption = Val;3012        LastFpContractOverrideOption = "";3013      } else3014        D.Diag(diag::err_drv_unsupported_option_argument)3015            << A->getSpelling() << Val;3016      break;3017    }3018 3019    // Validate and pass through -ffp-exception-behavior option.3020    case options::OPT_ffp_exception_behavior_EQ: {3021      StringRef Val = A->getValue();3022      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&3023          FPExceptionBehavior != Val)3024        // Warn that previous value of option is overridden.3025        D.Diag(clang::diag::warn_drv_overriding_option)3026            << Args.MakeArgString("-ffp-exception-behavior=" +3027                                  FPExceptionBehavior)3028            << Args.MakeArgString("-ffp-exception-behavior=" + Val);3029      TrappingMath = TrappingMathPresent = false;3030      if (Val == "ignore" || Val == "maytrap")3031        FPExceptionBehavior = Val;3032      else if (Val == "strict") {3033        FPExceptionBehavior = Val;3034        TrappingMath = TrappingMathPresent = true;3035      } else3036        D.Diag(diag::err_drv_unsupported_option_argument)3037            << A->getSpelling() << Val;3038      break;3039    }3040 3041    // Validate and pass through -ffp-eval-method option.3042    case options::OPT_ffp_eval_method_EQ: {3043      StringRef Val = A->getValue();3044      if (Val == "double" || Val == "extended" || Val == "source")3045        FPEvalMethod = Val;3046      else3047        D.Diag(diag::err_drv_unsupported_option_argument)3048            << A->getSpelling() << Val;3049      break;3050    }3051 3052    case options::OPT_fexcess_precision_EQ: {3053      StringRef Val = A->getValue();3054      const llvm::Triple::ArchType Arch = TC.getArch();3055      if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {3056        if (Val == "standard" || Val == "fast")3057          Float16ExcessPrecision = Val;3058        // To make it GCC compatible, allow the value of "16" which3059        // means disable excess precision, the same meaning than clang's3060        // equivalent value "none".3061        else if (Val == "16")3062          Float16ExcessPrecision = "none";3063        else3064          D.Diag(diag::err_drv_unsupported_option_argument)3065              << A->getSpelling() << Val;3066      } else {3067        if (!(Val == "standard" || Val == "fast"))3068          D.Diag(diag::err_drv_unsupported_option_argument)3069              << A->getSpelling() << Val;3070      }3071      BFloat16ExcessPrecision = Float16ExcessPrecision;3072      break;3073    }3074    case options::OPT_ffinite_math_only:3075      HonorINFs = false;3076      HonorNaNs = false;3077      break;3078    case options::OPT_fno_finite_math_only:3079      HonorINFs = true;3080      HonorNaNs = true;3081      break;3082 3083    case options::OPT_funsafe_math_optimizations:3084      AssociativeMath = true;3085      ReciprocalMath = true;3086      SignedZeros = false;3087      ApproxFunc = true;3088      TrappingMath = false;3089      FPExceptionBehavior = "";3090      FPContract = "fast";3091      LastFpContractOverrideOption = "-funsafe-math-optimizations";3092      SeenUnsafeMathModeOption = true;3093      break;3094    case options::OPT_fno_unsafe_math_optimizations:3095      AssociativeMath = false;3096      ReciprocalMath = false;3097      SignedZeros = true;3098      ApproxFunc = false;3099      restoreFPContractState();3100      break;3101 3102    case options::OPT_Ofast:3103      // If -Ofast is the optimization level, then -ffast-math should be enabled3104      if (!OFastEnabled)3105        continue;3106      [[fallthrough]];3107    case options::OPT_ffast_math:3108      applyFastMath(true, A->getSpelling());3109      if (A->getOption().getID() == options::OPT_Ofast)3110        LastFpContractOverrideOption = "-Ofast";3111      else3112        LastFpContractOverrideOption = "-ffast-math";3113      break;3114    case options::OPT_fno_fast_math:3115      HonorINFs = true;3116      HonorNaNs = true;3117      // Turning on -ffast-math (with either flag) removes the need for3118      // MathErrno. However, turning *off* -ffast-math merely restores the3119      // toolchain default (which may be false).3120      MathErrno = TC.IsMathErrnoDefault();3121      AssociativeMath = false;3122      ReciprocalMath = false;3123      ApproxFunc = false;3124      SignedZeros = true;3125      restoreFPContractState();3126      if (Range != LangOptions::ComplexRangeKind::CX_Full)3127        setComplexRange(D, A->getSpelling(),3128                        LangOptions::ComplexRangeKind::CX_None,3129                        LastComplexRangeOption, Range);3130      else3131        Range = LangOptions::ComplexRangeKind::CX_None;3132      LastComplexRangeOption = "";3133      LastFpContractOverrideOption = "";3134      break;3135    } // End switch (A->getOption().getID())3136 3137    // The StrictFPModel local variable is needed to report warnings3138    // in the way we intend. If -ffp-model=strict has been used, we3139    // want to report a warning for the next option encountered that3140    // takes us out of the settings described by fp-model=strict, but3141    // we don't want to continue issuing warnings for other conflicting3142    // options after that.3143    if (StrictFPModel) {3144      // If -ffp-model=strict has been specified on command line but3145      // subsequent options conflict then emit warning diagnostic.3146      if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&3147          SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&3148          FPContract == "off")3149        // OK: Current Arg doesn't conflict with -ffp-model=strict3150        ;3151      else {3152        StrictFPModel = false;3153        FPModel = "";3154        // The warning for -ffp-contract would have been reported by the3155        // OPT_ffp_contract_EQ handler above. A special check here is needed3156        // to avoid duplicating the warning.3157        auto RHS = (A->getNumValues() == 0)3158                       ? A->getSpelling()3159                       : Args.MakeArgString(A->getSpelling() + A->getValue());3160        if (A->getSpelling() != "-ffp-contract=") {3161          if (RHS != "-ffp-model=strict")3162            D.Diag(clang::diag::warn_drv_overriding_option)3163                << "-ffp-model=strict" << RHS;3164        }3165      }3166    }3167 3168    // If we handled this option claim it3169    A->claim();3170  }3171 3172  if (!HonorINFs)3173    CmdArgs.push_back("-menable-no-infs");3174 3175  if (!HonorNaNs)3176    CmdArgs.push_back("-menable-no-nans");3177 3178  if (ApproxFunc)3179    CmdArgs.push_back("-fapprox-func");3180 3181  if (MathErrno) {3182    CmdArgs.push_back("-fmath-errno");3183    if (NoMathErrnoWasImpliedByVecLib)3184      D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)3185          << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)3186          << VecLibArg->getAsString(Args);3187  }3188 3189 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&3190     !TrappingMath)3191    CmdArgs.push_back("-funsafe-math-optimizations");3192 3193  if (!SignedZeros)3194    CmdArgs.push_back("-fno-signed-zeros");3195 3196  if (AssociativeMath && !SignedZeros && !TrappingMath)3197    CmdArgs.push_back("-mreassociate");3198 3199  if (ReciprocalMath)3200    CmdArgs.push_back("-freciprocal-math");3201 3202  if (TrappingMath) {3203    // FP Exception Behavior is also set to strict3204    assert(FPExceptionBehavior == "strict");3205  }3206 3207  // The default is IEEE.3208  if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {3209    llvm::SmallString<64> DenormFlag;3210    llvm::raw_svector_ostream ArgStr(DenormFlag);3211    ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;3212    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));3213  }3214 3215  // Add f32 specific denormal mode flag if it's different.3216  if (DenormalFP32Math != DenormalFPMath) {3217    llvm::SmallString<64> DenormFlag;3218    llvm::raw_svector_ostream ArgStr(DenormFlag);3219    ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;3220    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));3221  }3222 3223  if (!FPContract.empty())3224    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));3225 3226  if (RoundingFPMath)3227    CmdArgs.push_back(Args.MakeArgString("-frounding-math"));3228  else3229    CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));3230 3231  if (!FPExceptionBehavior.empty())3232    CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +3233                      FPExceptionBehavior));3234 3235  if (!FPEvalMethod.empty())3236    CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));3237 3238  if (!Float16ExcessPrecision.empty())3239    CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +3240                                         Float16ExcessPrecision));3241  if (!BFloat16ExcessPrecision.empty())3242    CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +3243                                         BFloat16ExcessPrecision));3244 3245  StringRef Recip = parseMRecipOption(D.getDiags(), Args);3246  if (!Recip.empty())3247    CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));3248 3249  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the3250  // individual features enabled by -ffast-math instead of the option itself as3251  // that's consistent with gcc's behaviour.3252  if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&3253      ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)3254    CmdArgs.push_back("-ffast-math");3255 3256  // Handle __FINITE_MATH_ONLY__ similarly.3257  // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.3258  // Otherwise process the Xclang arguments to determine if -menable-no-infs and3259  // -menable-no-nans are set by the user.3260  bool shouldAddFiniteMathOnly = false;3261  if (!HonorINFs && !HonorNaNs) {3262    shouldAddFiniteMathOnly = true;3263  } else {3264    bool InfValues = true;3265    bool NanValues = true;3266    for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {3267      StringRef ArgValue = Arg->getValue();3268      if (ArgValue == "-menable-no-nans")3269        NanValues = false;3270      else if (ArgValue == "-menable-no-infs")3271        InfValues = false;3272    }3273    if (!NanValues && !InfValues)3274      shouldAddFiniteMathOnly = true;3275  }3276  if (shouldAddFiniteMathOnly) {3277    CmdArgs.push_back("-ffinite-math-only");3278  }3279  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {3280    CmdArgs.push_back("-mfpmath");3281    CmdArgs.push_back(A->getValue());3282  }3283 3284  // Disable a codegen optimization for floating-point casts.3285  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,3286                   options::OPT_fstrict_float_cast_overflow, false))3287    CmdArgs.push_back("-fno-strict-float-cast-overflow");3288 3289  if (Range != LangOptions::ComplexRangeKind::CX_None)3290    ComplexRangeStr = renderComplexRangeOption(Range);3291  if (!ComplexRangeStr.empty()) {3292    CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));3293    if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))3294      CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +3295                                           complexRangeKindToStr(Range)));3296  }3297  if (Args.hasArg(options::OPT_fcx_limited_range))3298    CmdArgs.push_back("-fcx-limited-range");3299  if (Args.hasArg(options::OPT_fcx_fortran_rules))3300    CmdArgs.push_back("-fcx-fortran-rules");3301  if (Args.hasArg(options::OPT_fno_cx_limited_range))3302    CmdArgs.push_back("-fno-cx-limited-range");3303  if (Args.hasArg(options::OPT_fno_cx_fortran_rules))3304    CmdArgs.push_back("-fno-cx-fortran-rules");3305}3306 3307static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,3308                                  const llvm::Triple &Triple,3309                                  const InputInfo &Input) {3310  // Add default argument set.3311  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {3312    CmdArgs.push_back("-analyzer-checker=core");3313    CmdArgs.push_back("-analyzer-checker=apiModeling");3314 3315    if (!Triple.isWindowsMSVCEnvironment()) {3316      CmdArgs.push_back("-analyzer-checker=unix");3317    } else {3318      // Enable "unix" checkers that also work on Windows.3319      CmdArgs.push_back("-analyzer-checker=unix.API");3320      CmdArgs.push_back("-analyzer-checker=unix.Malloc");3321      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");3322      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");3323      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");3324      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");3325    }3326 3327    // Disable some unix checkers for PS4/PS5.3328    if (Triple.isPS()) {3329      CmdArgs.push_back("-analyzer-disable-checker=unix.API");3330      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");3331    }3332 3333    if (Triple.isOSDarwin()) {3334      CmdArgs.push_back("-analyzer-checker=osx");3335      CmdArgs.push_back(3336          "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");3337    }3338    else if (Triple.isOSFuchsia())3339      CmdArgs.push_back("-analyzer-checker=fuchsia");3340 3341    CmdArgs.push_back("-analyzer-checker=deadcode");3342 3343    if (types::isCXX(Input.getType()))3344      CmdArgs.push_back("-analyzer-checker=cplusplus");3345 3346    if (!Triple.isPS()) {3347      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");3348      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");3349      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");3350      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");3351      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");3352      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");3353    }3354 3355    // Default nullability checks.3356    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");3357    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");3358  }3359 3360  // Set the output format. The default is plist, for (lame) historical reasons.3361  CmdArgs.push_back("-analyzer-output");3362  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))3363    CmdArgs.push_back(A->getValue());3364  else3365    CmdArgs.push_back("plist");3366 3367  // Disable the presentation of standard compiler warnings when using3368  // --analyze.  We only want to show static analyzer diagnostics or frontend3369  // errors.3370  CmdArgs.push_back("-w");3371 3372  // Add -Xanalyzer arguments when running as analyzer.3373  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);3374}3375 3376static bool isValidSymbolName(StringRef S) {3377  if (S.empty())3378    return false;3379 3380  if (std::isdigit(S[0]))3381    return false;3382 3383  return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });3384}3385 3386static void RenderSSPOptions(const Driver &D, const ToolChain &TC,3387                             const ArgList &Args, ArgStringList &CmdArgs,3388                             bool KernelOrKext) {3389  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();3390 3391  // NVPTX doesn't support stack protectors; from the compiler's perspective, it3392  // doesn't even have a stack!3393  if (EffectiveTriple.isNVPTX())3394    return;3395 3396  // -stack-protector=0 is default.3397  LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;3398  LangOptions::StackProtectorMode DefaultStackProtectorLevel =3399      TC.GetDefaultStackProtectorLevel(KernelOrKext);3400 3401  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,3402                               options::OPT_fstack_protector_all,3403                               options::OPT_fstack_protector_strong,3404                               options::OPT_fstack_protector)) {3405    if (A->getOption().matches(options::OPT_fstack_protector))3406      StackProtectorLevel =3407          std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);3408    else if (A->getOption().matches(options::OPT_fstack_protector_strong))3409      StackProtectorLevel = LangOptions::SSPStrong;3410    else if (A->getOption().matches(options::OPT_fstack_protector_all))3411      StackProtectorLevel = LangOptions::SSPReq;3412 3413    if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {3414      D.Diag(diag::warn_drv_unsupported_option_for_target)3415          << A->getSpelling() << EffectiveTriple.getTriple();3416      StackProtectorLevel = DefaultStackProtectorLevel;3417    }3418  } else {3419    StackProtectorLevel = DefaultStackProtectorLevel;3420  }3421 3422  if (StackProtectorLevel) {3423    CmdArgs.push_back("-stack-protector");3424    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));3425  }3426 3427  // --param ssp-buffer-size=3428  for (const Arg *A : Args.filtered(options::OPT__param)) {3429    StringRef Str(A->getValue());3430    if (Str.consume_front("ssp-buffer-size=")) {3431      if (StackProtectorLevel) {3432        CmdArgs.push_back("-stack-protector-buffer-size");3433        // FIXME: Verify the argument is a valid integer.3434        CmdArgs.push_back(Args.MakeArgString(Str));3435      }3436      A->claim();3437    }3438  }3439 3440  const std::string &TripleStr = EffectiveTriple.getTriple();3441  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {3442    StringRef Value = A->getValue();3443    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&3444        !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&3445        !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())3446      D.Diag(diag::err_drv_unsupported_opt_for_target)3447          << A->getAsString(Args) << TripleStr;3448    if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||3449         EffectiveTriple.isThumb()) &&3450        Value != "tls" && Value != "global") {3451      D.Diag(diag::err_drv_invalid_value_with_suggestion)3452          << A->getOption().getName() << Value << "tls global";3453      return;3454    }3455    if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&3456        Value == "tls") {3457      if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {3458        D.Diag(diag::err_drv_ssp_missing_offset_argument)3459            << A->getAsString(Args);3460        return;3461      }3462      // Check whether the target subarch supports the hardware TLS register3463      if (!arm::isHardTPSupported(EffectiveTriple)) {3464        D.Diag(diag::err_target_unsupported_tp_hard)3465            << EffectiveTriple.getArchName();3466        return;3467      }3468      // Check whether the user asked for something other than -mtp=cp153469      if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {3470        StringRef Value = A->getValue();3471        if (Value != "cp15") {3472          D.Diag(diag::err_drv_argument_not_allowed_with)3473              << A->getAsString(Args) << "-mstack-protector-guard=tls";3474          return;3475        }3476      }3477      CmdArgs.push_back("-target-feature");3478      CmdArgs.push_back("+read-tp-tpidruro");3479    }3480    if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {3481      D.Diag(diag::err_drv_invalid_value_with_suggestion)3482          << A->getOption().getName() << Value << "sysreg global";3483      return;3484    }3485    if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {3486      if (Value != "tls" && Value != "global") {3487        D.Diag(diag::err_drv_invalid_value_with_suggestion)3488            << A->getOption().getName() << Value << "tls global";3489        return;3490      }3491      if (Value == "tls") {3492        if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {3493          D.Diag(diag::err_drv_ssp_missing_offset_argument)3494              << A->getAsString(Args);3495          return;3496        }3497      }3498    }3499    A->render(Args, CmdArgs);3500  }3501 3502  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {3503    StringRef Value = A->getValue();3504    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&3505        !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&3506        !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())3507      D.Diag(diag::err_drv_unsupported_opt_for_target)3508          << A->getAsString(Args) << TripleStr;3509    int Offset;3510    if (Value.getAsInteger(10, Offset)) {3511      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;3512      return;3513    }3514    if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&3515        (Offset < 0 || Offset > 0xfffff)) {3516      D.Diag(diag::err_drv_invalid_int_value)3517          << A->getOption().getName() << Value;3518      return;3519    }3520    A->render(Args, CmdArgs);3521  }3522 3523  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {3524    StringRef Value = A->getValue();3525    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&3526        !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())3527      D.Diag(diag::err_drv_unsupported_opt_for_target)3528          << A->getAsString(Args) << TripleStr;3529    if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {3530      D.Diag(diag::err_drv_invalid_value_with_suggestion)3531          << A->getOption().getName() << Value << "fs gs";3532      return;3533    }3534    if (EffectiveTriple.isAArch64() && Value != "sp_el0") {3535      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;3536      return;3537    }3538    if (EffectiveTriple.isRISCV() && Value != "tp") {3539      D.Diag(diag::err_drv_invalid_value_with_suggestion)3540          << A->getOption().getName() << Value << "tp";3541      return;3542    }3543    if (EffectiveTriple.isPPC64() && Value != "r13") {3544      D.Diag(diag::err_drv_invalid_value_with_suggestion)3545          << A->getOption().getName() << Value << "r13";3546      return;3547    }3548    if (EffectiveTriple.isPPC32() && Value != "r2") {3549      D.Diag(diag::err_drv_invalid_value_with_suggestion)3550          << A->getOption().getName() << Value << "r2";3551      return;3552    }3553    A->render(Args, CmdArgs);3554  }3555 3556  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {3557    StringRef Value = A->getValue();3558    if (!isValidSymbolName(Value)) {3559      D.Diag(diag::err_drv_argument_only_allowed_with)3560          << A->getOption().getName() << "legal symbol name";3561      return;3562    }3563    A->render(Args, CmdArgs);3564  }3565}3566 3567static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,3568                             ArgStringList &CmdArgs) {3569  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();3570 3571  if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&3572      !EffectiveTriple.isOSFuchsia())3573    return;3574 3575  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&3576      !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&3577      !EffectiveTriple.isRISCV())3578    return;3579 3580  Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,3581                    options::OPT_fno_stack_clash_protection);3582}3583 3584static void RenderTrivialAutoVarInitOptions(const Driver &D,3585                                            const ToolChain &TC,3586                                            const ArgList &Args,3587                                            ArgStringList &CmdArgs) {3588  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();3589  StringRef TrivialAutoVarInit = "";3590 3591  for (const Arg *A : Args) {3592    switch (A->getOption().getID()) {3593    default:3594      continue;3595    case options::OPT_ftrivial_auto_var_init: {3596      A->claim();3597      StringRef Val = A->getValue();3598      if (Val == "uninitialized" || Val == "zero" || Val == "pattern")3599        TrivialAutoVarInit = Val;3600      else3601        D.Diag(diag::err_drv_unsupported_option_argument)3602            << A->getSpelling() << Val;3603      break;3604    }3605    }3606  }3607 3608  if (TrivialAutoVarInit.empty())3609    switch (DefaultTrivialAutoVarInit) {3610    case LangOptions::TrivialAutoVarInitKind::Uninitialized:3611      break;3612    case LangOptions::TrivialAutoVarInitKind::Pattern:3613      TrivialAutoVarInit = "pattern";3614      break;3615    case LangOptions::TrivialAutoVarInitKind::Zero:3616      TrivialAutoVarInit = "zero";3617      break;3618    }3619 3620  if (!TrivialAutoVarInit.empty()) {3621    CmdArgs.push_back(3622        Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));3623  }3624 3625  if (Arg *A =3626          Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {3627    if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||3628        StringRef(3629            Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==3630            "uninitialized")3631      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);3632    A->claim();3633    StringRef Val = A->getValue();3634    if (std::stoi(Val.str()) <= 0)3635      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);3636    CmdArgs.push_back(3637        Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));3638  }3639 3640  if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {3641    if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||3642        StringRef(3643            Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==3644            "uninitialized")3645      D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);3646    A->claim();3647    StringRef Val = A->getValue();3648    if (std::stoi(Val.str()) <= 0)3649      D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);3650    CmdArgs.push_back(3651        Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));3652  }3653}3654 3655static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,3656                                types::ID InputType) {3657  // cl-denorms-are-zero is not forwarded. It is translated into a generic flag3658  // for denormal flushing handling based on the target.3659  const unsigned ForwardedArguments[] = {3660      options::OPT_cl_opt_disable,3661      options::OPT_cl_strict_aliasing,3662      options::OPT_cl_single_precision_constant,3663      options::OPT_cl_finite_math_only,3664      options::OPT_cl_kernel_arg_info,3665      options::OPT_cl_unsafe_math_optimizations,3666      options::OPT_cl_fast_relaxed_math,3667      options::OPT_cl_mad_enable,3668      options::OPT_cl_no_signed_zeros,3669      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,3670      options::OPT_cl_uniform_work_group_size3671  };3672 3673  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {3674    std::string CLStdStr = std::string("-cl-std=") + A->getValue();3675    CmdArgs.push_back(Args.MakeArgString(CLStdStr));3676  } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {3677    std::string CLExtStr = std::string("-cl-ext=") + A->getValue();3678    CmdArgs.push_back(Args.MakeArgString(CLExtStr));3679  }3680 3681  if (Args.hasArg(options::OPT_cl_finite_math_only)) {3682    CmdArgs.push_back("-menable-no-infs");3683    CmdArgs.push_back("-menable-no-nans");3684  }3685 3686  for (const auto &Arg : ForwardedArguments)3687    if (const auto *A = Args.getLastArg(Arg))3688      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));3689 3690  // Only add the default headers if we are compiling OpenCL sources.3691  if ((types::isOpenCL(InputType) ||3692       (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&3693      !Args.hasArg(options::OPT_cl_no_stdinc)) {3694    CmdArgs.push_back("-finclude-default-header");3695    CmdArgs.push_back("-fdeclare-opencl-builtins");3696  }3697}3698 3699static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,3700                              types::ID InputType) {3701  const unsigned ForwardedArguments[] = {3702      options::OPT_dxil_validator_version,3703      options::OPT_res_may_alias,3704      options::OPT_D,3705      options::OPT_I,3706      options::OPT_O,3707      options::OPT_emit_llvm,3708      options::OPT_emit_obj,3709      options::OPT_disable_llvm_passes,3710      options::OPT_fnative_half_type,3711      options::OPT_fnative_int16_type,3712      options::OPT_hlsl_entrypoint,3713      options::OPT_fdx_rootsignature_define,3714      options::OPT_fdx_rootsignature_version,3715      options::OPT_fhlsl_spv_use_unknown_image_format,3716      options::OPT_fhlsl_spv_enable_maximal_reconvergence};3717  if (!types::isHLSL(InputType))3718    return;3719  for (const auto &Arg : ForwardedArguments)3720    if (const auto *A = Args.getLastArg(Arg))3721      A->renderAsInput(Args, CmdArgs);3722  // Add the default headers if dxc_no_stdinc is not set.3723  if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&3724      !Args.hasArg(options::OPT_nostdinc))3725    CmdArgs.push_back("-finclude-default-header");3726}3727 3728static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,3729                                 ArgStringList &CmdArgs, types::ID InputType) {3730  if (!Args.hasArg(options::OPT_fopenacc))3731    return;3732 3733  CmdArgs.push_back("-fopenacc");3734}3735 3736static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,3737                                 const ArgList &Args, ArgStringList &CmdArgs) {3738  // -fbuiltin is default unless -mkernel is used.3739  bool UseBuiltins =3740      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,3741                   !Args.hasArg(options::OPT_mkernel));3742  if (!UseBuiltins)3743    CmdArgs.push_back("-fno-builtin");3744 3745  // -ffreestanding implies -fno-builtin.3746  if (Args.hasArg(options::OPT_ffreestanding))3747    UseBuiltins = false;3748 3749  // Process the -fno-builtin-* options.3750  for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {3751    A->claim();3752 3753    // If -fno-builtin is specified, then there's no need to pass the option to3754    // the frontend.3755    if (UseBuiltins)3756      A->render(Args, CmdArgs);3757  }3758}3759 3760bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {3761  if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {3762    Twine Path{Str};3763    Path.toVector(Result);3764    return Path.getSingleStringRef() != "";3765  }3766  if (llvm::sys::path::cache_directory(Result)) {3767    llvm::sys::path::append(Result, "clang");3768    llvm::sys::path::append(Result, "ModuleCache");3769    return true;3770  }3771  return false;3772}3773 3774llvm::SmallString<256>3775clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,3776                                                    const char *BaseInput) {3777  if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))3778    return StringRef(ModuleOutputEQ->getValue());3779 3780  SmallString<256> OutputPath;3781  if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);3782      FinalOutput && Args.hasArg(options::OPT_c))3783    OutputPath = FinalOutput->getValue();3784  else3785    OutputPath = BaseInput;3786 3787  const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);3788  llvm::sys::path::replace_extension(OutputPath, Extension);3789  return OutputPath;3790}3791 3792static bool RenderModulesOptions(Compilation &C, const Driver &D,3793                                 const ArgList &Args, const InputInfo &Input,3794                                 const InputInfo &Output, bool HaveStd20,3795                                 ArgStringList &CmdArgs) {3796  const bool IsCXX = types::isCXX(Input.getType());3797  const bool HaveStdCXXModules = IsCXX && HaveStd20;3798  bool HaveModules = HaveStdCXXModules;3799 3800  // -fmodules enables the use of precompiled modules (off by default).3801  // Users can pass -fno-cxx-modules to turn off modules support for3802  // C++/Objective-C++ programs.3803  const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,3804                                         options::OPT_fno_cxx_modules, true);3805  bool HaveClangModules = false;3806  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {3807    if (AllowedInCXX || !IsCXX) {3808      CmdArgs.push_back("-fmodules");3809      HaveClangModules = true;3810    }3811  }3812 3813  HaveModules |= HaveClangModules;3814 3815  if (HaveModules && !AllowedInCXX)3816    CmdArgs.push_back("-fno-cxx-modules");3817 3818  // -fmodule-maps enables implicit reading of module map files. By default,3819  // this is enabled if we are using Clang's flavor of precompiled modules.3820  if (Args.hasFlag(options::OPT_fimplicit_module_maps,3821                   options::OPT_fno_implicit_module_maps, HaveClangModules))3822    CmdArgs.push_back("-fimplicit-module-maps");3823 3824  // -fmodules-decluse checks that modules used are declared so (off by default)3825  Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,3826                    options::OPT_fno_modules_decluse);3827 3828  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that3829  // all #included headers are part of modules.3830  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,3831                   options::OPT_fno_modules_strict_decluse, false))3832    CmdArgs.push_back("-fmodules-strict-decluse");3833 3834  Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,3835                     options::OPT_fno_modulemap_allow_subdirectory_search);3836 3837  // -fno-implicit-modules turns off implicitly compiling modules on demand.3838  bool ImplicitModules = false;3839  if (!Args.hasFlag(options::OPT_fimplicit_modules,3840                    options::OPT_fno_implicit_modules, HaveClangModules)) {3841    if (HaveModules)3842      CmdArgs.push_back("-fno-implicit-modules");3843  } else if (HaveModules) {3844    ImplicitModules = true;3845    // -fmodule-cache-path specifies where our implicitly-built module files3846    // should be written.3847    SmallString<128> Path;3848    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))3849      Path = A->getValue();3850 3851    bool HasPath = true;3852    if (C.isForDiagnostics()) {3853      // When generating crash reports, we want to emit the modules along with3854      // the reproduction sources, so we ignore any provided module path.3855      Path = Output.getFilename();3856      llvm::sys::path::replace_extension(Path, ".cache");3857      llvm::sys::path::append(Path, "modules");3858    } else if (Path.empty()) {3859      // No module path was provided: use the default.3860      HasPath = Driver::getDefaultModuleCachePath(Path);3861    }3862 3863    // `HasPath` will only be false if getDefaultModuleCachePath() fails.3864    // That being said, that failure is unlikely and not caching is harmless.3865    if (HasPath) {3866      const char Arg[] = "-fmodules-cache-path=";3867      Path.insert(Path.begin(), Arg, Arg + strlen(Arg));3868      CmdArgs.push_back(Args.MakeArgString(Path));3869    }3870  }3871 3872  if (HaveModules) {3873    if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,3874                     options::OPT_fno_prebuilt_implicit_modules, false))3875      CmdArgs.push_back("-fprebuilt-implicit-modules");3876    if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,3877                     options::OPT_fno_modules_validate_input_files_content,3878                     false))3879      CmdArgs.push_back("-fvalidate-ast-input-files-content");3880  }3881 3882  // -fmodule-name specifies the module that is currently being built (or3883  // used for header checking by -fmodule-maps).3884  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);3885 3886  // -fmodule-map-file can be used to specify files containing module3887  // definitions.3888  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);3889 3890  // -fbuiltin-module-map can be used to load the clang3891  // builtin headers modulemap file.3892  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {3893    SmallString<128> BuiltinModuleMap(D.ResourceDir);3894    llvm::sys::path::append(BuiltinModuleMap, "include");3895    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");3896    if (llvm::sys::fs::exists(BuiltinModuleMap))3897      CmdArgs.push_back(3898          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));3899  }3900 3901  // The -fmodule-file=<name>=<file> form specifies the mapping of module3902  // names to precompiled module files (the module is loaded only if used).3903  // The -fmodule-file=<file> form can be used to unconditionally load3904  // precompiled module files (whether used or not).3905  if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {3906    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);3907 3908    // -fprebuilt-module-path specifies where to load the prebuilt module files.3909    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {3910      CmdArgs.push_back(Args.MakeArgString(3911          std::string("-fprebuilt-module-path=") + A->getValue()));3912      A->claim();3913    }3914  } else3915    Args.ClaimAllArgs(options::OPT_fmodule_file);3916 3917  // When building modules and generating crashdumps, we need to dump a module3918  // dependency VFS alongside the output.3919  if (HaveClangModules && C.isForDiagnostics()) {3920    SmallString<128> VFSDir(Output.getFilename());3921    llvm::sys::path::replace_extension(VFSDir, ".cache");3922    // Add the cache directory as a temp so the crash diagnostics pick it up.3923    C.addTempFile(Args.MakeArgString(VFSDir));3924 3925    llvm::sys::path::append(VFSDir, "vfs");3926    CmdArgs.push_back("-module-dependency-dir");3927    CmdArgs.push_back(Args.MakeArgString(VFSDir));3928  }3929 3930  if (HaveClangModules)3931    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);3932 3933  // Pass through all -fmodules-ignore-macro arguments.3934  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);3935  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);3936  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);3937 3938  if (HaveClangModules) {3939    Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);3940 3941    if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {3942      if (Args.hasArg(options::OPT_fbuild_session_timestamp))3943        D.Diag(diag::err_drv_argument_not_allowed_with)3944            << A->getAsString(Args) << "-fbuild-session-timestamp";3945 3946      llvm::sys::fs::file_status Status;3947      if (llvm::sys::fs::status(A->getValue(), Status))3948        D.Diag(diag::err_drv_no_such_file) << A->getValue();3949      CmdArgs.push_back(Args.MakeArgString(3950          "-fbuild-session-timestamp=" +3951          Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(3952                    Status.getLastModificationTime().time_since_epoch())3953                    .count())));3954    }3955 3956    if (Args.getLastArg(3957            options::OPT_fmodules_validate_once_per_build_session)) {3958      if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,3959                           options::OPT_fbuild_session_file))3960        D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);3961 3962      Args.AddLastArg(CmdArgs,3963                      options::OPT_fmodules_validate_once_per_build_session);3964    }3965 3966    if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,3967                     options::OPT_fno_modules_validate_system_headers,3968                     ImplicitModules))3969      CmdArgs.push_back("-fmodules-validate-system-headers");3970 3971    Args.AddLastArg(CmdArgs,3972                    options::OPT_fmodules_disable_diagnostic_validation);3973  } else {3974    Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);3975    Args.ClaimAllArgs(options::OPT_fbuild_session_file);3976    Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);3977    Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);3978    Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);3979    Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);3980  }3981 3982  // FIXME: We provisionally don't check ODR violations for decls in the global3983  // module fragment.3984  CmdArgs.push_back("-fskip-odr-check-in-gmf");3985 3986  if (Input.getType() == driver::types::TY_CXXModule ||3987      Input.getType() == driver::types::TY_PP_CXXModule) {3988    if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))3989      CmdArgs.push_back("-fmodules-reduced-bmi");3990 3991    if (Args.hasArg(options::OPT_fmodule_output_EQ))3992      Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);3993    else if (!Args.hasArg(options::OPT__precompile) ||3994             Args.hasArg(options::OPT_fmodule_output))3995      // If --precompile is specified, we will always generate a module file if3996      // we're compiling an importable module unit. This is fine even if the3997      // compilation process won't reach the point of generating the module file3998      // (e.g., in the preprocessing mode), since the attached flag3999      // '-fmodule-output' is useless.4000      //4001      // But if '--precompile' is specified, it might be annoying to always4002      // generate the module file as '--precompile' will generate the module4003      // file anyway.4004      CmdArgs.push_back(Args.MakeArgString(4005          "-fmodule-output=" +4006          getCXX20NamedModuleOutputPath(Args, Input.getBaseInput())));4007  }4008 4009  if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&4010      Args.hasArg(options::OPT__precompile) &&4011      (!Args.hasArg(options::OPT_o) ||4012       Args.getLastArg(options::OPT_o)->getValue() ==4013           getCXX20NamedModuleOutputPath(Args, Input.getBaseInput()))) {4014    D.Diag(diag::err_drv_reduced_module_output_overrided);4015  }4016 4017  // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with4018  // other translation units than module units. This is more user friendly to4019  // allow end uers to enable this feature without asking for help from build4020  // systems.4021  Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);4022  Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);4023 4024  // We need to include the case the input file is a module file here.4025  // Since the default compilation model for C++ module interface unit will4026  // create temporary module file and compile the temporary module file4027  // to get the object file. Then the `-fmodule-output` flag will be4028  // brought to the second compilation process. So we have to claim it for4029  // the case too.4030  if (Input.getType() == driver::types::TY_CXXModule ||4031      Input.getType() == driver::types::TY_PP_CXXModule ||4032      Input.getType() == driver::types::TY_ModuleFile) {4033    Args.ClaimAllArgs(options::OPT_fmodule_output);4034    Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);4035  }4036 4037  if (Args.hasArg(options::OPT_fmodules_embed_all_files))4038    CmdArgs.push_back("-fmodules-embed-all-files");4039 4040  return HaveModules;4041}4042 4043static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,4044                                   ArgStringList &CmdArgs) {4045  // -fsigned-char is default.4046  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,4047                                     options::OPT_fno_signed_char,4048                                     options::OPT_funsigned_char,4049                                     options::OPT_fno_unsigned_char)) {4050    if (A->getOption().matches(options::OPT_funsigned_char) ||4051        A->getOption().matches(options::OPT_fno_signed_char)) {4052      CmdArgs.push_back("-fno-signed-char");4053    }4054  } else if (!isSignedCharDefault(T)) {4055    CmdArgs.push_back("-fno-signed-char");4056  }4057 4058  // The default depends on the language standard.4059  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);4060 4061  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,4062                                     options::OPT_fno_short_wchar)) {4063    if (A->getOption().matches(options::OPT_fshort_wchar)) {4064      CmdArgs.push_back("-fwchar-type=short");4065      CmdArgs.push_back("-fno-signed-wchar");4066    } else {4067      bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();4068      CmdArgs.push_back("-fwchar-type=int");4069      if (T.isOSzOS() ||4070          (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))4071        CmdArgs.push_back("-fno-signed-wchar");4072      else4073        CmdArgs.push_back("-fsigned-wchar");4074    }4075  } else if (T.isOSzOS())4076    CmdArgs.push_back("-fno-signed-wchar");4077}4078 4079static void RenderObjCOptions(const ToolChain &TC, const Driver &D,4080                              const llvm::Triple &T, const ArgList &Args,4081                              ObjCRuntime &Runtime, bool InferCovariantReturns,4082                              const InputInfo &Input, ArgStringList &CmdArgs) {4083  const llvm::Triple::ArchType Arch = TC.getArch();4084 4085  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy4086  // is the default. Except for deployment target of 10.5, next runtime is4087  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.4088  if (Runtime.isNonFragile()) {4089    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,4090                      options::OPT_fno_objc_legacy_dispatch,4091                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {4092      if (TC.UseObjCMixedDispatch())4093        CmdArgs.push_back("-fobjc-dispatch-method=mixed");4094      else4095        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");4096    }4097  }4098 4099  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option4100  // to do Array/Dictionary subscripting by default.4101  if (Arch == llvm::Triple::x86 && T.isMacOSX() &&4102      Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())4103    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");4104 4105  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.4106  // NOTE: This logic is duplicated in ToolChains.cpp.4107  if (isObjCAutoRefCount(Args)) {4108    TC.CheckObjCARC();4109 4110    CmdArgs.push_back("-fobjc-arc");4111 4112    // FIXME: It seems like this entire block, and several around it should be4113    // wrapped in isObjC, but for now we just use it here as this is where it4114    // was being used previously.4115    if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {4116      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)4117        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");4118      else4119        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");4120    }4121 4122    // Allow the user to enable full exceptions code emission.4123    // We default off for Objective-C, on for Objective-C++.4124    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,4125                     options::OPT_fno_objc_arc_exceptions,4126                     /*Default=*/types::isCXX(Input.getType())))4127      CmdArgs.push_back("-fobjc-arc-exceptions");4128  }4129 4130  // Silence warning for full exception code emission options when explicitly4131  // set to use no ARC.4132  if (Args.hasArg(options::OPT_fno_objc_arc)) {4133    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);4134    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);4135  }4136 4137  // Allow the user to control whether messages can be converted to runtime4138  // functions.4139  if (types::isObjC(Input.getType())) {4140    auto *Arg = Args.getLastArg(4141        options::OPT_fobjc_convert_messages_to_runtime_calls,4142        options::OPT_fno_objc_convert_messages_to_runtime_calls);4143    if (Arg &&4144        Arg->getOption().matches(4145            options::OPT_fno_objc_convert_messages_to_runtime_calls))4146      CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");4147  }4148 4149  // -fobjc-infer-related-result-type is the default, except in the Objective-C4150  // rewriter.4151  if (InferCovariantReturns)4152    CmdArgs.push_back("-fno-objc-infer-related-result-type");4153 4154  // Pass down -fobjc-weak or -fno-objc-weak if present.4155  if (types::isObjC(Input.getType())) {4156    auto WeakArg =4157        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);4158    if (!WeakArg) {4159      // nothing to do4160    } else if (!Runtime.allowsWeak()) {4161      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))4162        D.Diag(diag::err_objc_weak_unsupported);4163    } else {4164      WeakArg->render(Args, CmdArgs);4165    }4166  }4167 4168  if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))4169    CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");4170}4171 4172static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,4173                                     ArgStringList &CmdArgs) {4174  bool CaretDefault = true;4175  bool ColumnDefault = true;4176 4177  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,4178                                     options::OPT__SLASH_diagnostics_column,4179                                     options::OPT__SLASH_diagnostics_caret)) {4180    switch (A->getOption().getID()) {4181    case options::OPT__SLASH_diagnostics_caret:4182      CaretDefault = true;4183      ColumnDefault = true;4184      break;4185    case options::OPT__SLASH_diagnostics_column:4186      CaretDefault = false;4187      ColumnDefault = true;4188      break;4189    case options::OPT__SLASH_diagnostics_classic:4190      CaretDefault = false;4191      ColumnDefault = false;4192      break;4193    }4194  }4195 4196  // -fcaret-diagnostics is default.4197  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,4198                    options::OPT_fno_caret_diagnostics, CaretDefault))4199    CmdArgs.push_back("-fno-caret-diagnostics");4200 4201  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,4202                     options::OPT_fno_diagnostics_fixit_info);4203  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,4204                     options::OPT_fno_diagnostics_show_option);4205 4206  if (const Arg *A =4207          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {4208    CmdArgs.push_back("-fdiagnostics-show-category");4209    CmdArgs.push_back(A->getValue());4210  }4211 4212  Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,4213                    options::OPT_fno_diagnostics_show_hotness);4214 4215  if (const Arg *A =4216          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {4217    std::string Opt =4218        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();4219    CmdArgs.push_back(Args.MakeArgString(Opt));4220  }4221 4222  if (const Arg *A =4223          Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {4224    std::string Opt =4225        std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();4226    CmdArgs.push_back(Args.MakeArgString(Opt));4227  }4228 4229  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {4230    CmdArgs.push_back("-fdiagnostics-format");4231    CmdArgs.push_back(A->getValue());4232    if (StringRef(A->getValue()) == "sarif" ||4233        StringRef(A->getValue()) == "SARIF")4234      D.Diag(diag::warn_drv_sarif_format_unstable);4235  }4236 4237  if (const Arg *A = Args.getLastArg(4238          options::OPT_fdiagnostics_show_note_include_stack,4239          options::OPT_fno_diagnostics_show_note_include_stack)) {4240    const Option &O = A->getOption();4241    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))4242      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");4243    else4244      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");4245  }4246 4247  handleColorDiagnosticsArgs(D, Args, CmdArgs);4248 4249  if (Args.hasArg(options::OPT_fansi_escape_codes))4250    CmdArgs.push_back("-fansi-escape-codes");4251 4252  Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,4253                     options::OPT_fno_show_source_location);4254 4255  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,4256                     options::OPT_fno_diagnostics_show_line_numbers);4257 4258  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))4259    CmdArgs.push_back("-fdiagnostics-absolute-paths");4260 4261  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,4262                    ColumnDefault))4263    CmdArgs.push_back("-fno-show-column");4264 4265  Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,4266                     options::OPT_fno_spell_checking);4267 4268  Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);4269}4270 4271static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,4272                              const ArgList &Args, ArgStringList &CmdArgs,4273                              unsigned DwarfVersion) {4274  auto *DwarfFormatArg =4275      Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);4276  if (!DwarfFormatArg)4277    return;4278 4279  if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {4280    if (DwarfVersion < 3)4281      D.Diag(diag::err_drv_argument_only_allowed_with)4282          << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";4283    else if (!T.isArch64Bit())4284      D.Diag(diag::err_drv_argument_only_allowed_with)4285          << DwarfFormatArg->getAsString(Args) << "64 bit architecture";4286    else if (!T.isOSBinFormatELF())4287      D.Diag(diag::err_drv_argument_only_allowed_with)4288          << DwarfFormatArg->getAsString(Args) << "ELF platforms";4289  }4290 4291  DwarfFormatArg->render(Args, CmdArgs);4292}4293 4294static void4295renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,4296                   const ArgList &Args, types::ID InputType,4297                   ArgStringList &CmdArgs, const InputInfo &Output,4298                   llvm::codegenoptions::DebugInfoKind &DebugInfoKind,4299                   DwarfFissionKind &DwarfFission) {4300  bool IRInput = isLLVMIR(InputType);4301  bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&4302                     !isHIP(InputType) && !isObjC(InputType) &&4303                     !isOpenCL(InputType);4304 4305  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,4306                   options::OPT_fno_debug_info_for_profiling, false) &&4307      checkDebugInfoOption(4308          Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))4309    CmdArgs.push_back("-fdebug-info-for-profiling");4310 4311  // The 'g' groups options involve a somewhat intricate sequence of decisions4312  // about what to pass from the driver to the frontend, but by the time they4313  // reach cc1 they've been factored into three well-defined orthogonal choices:4314  //  * what level of debug info to generate4315  //  * what dwarf version to write4316  //  * what debugger tuning to use4317  // This avoids having to monkey around further in cc1 other than to disable4318  // codeview if not running in a Windows environment. Perhaps even that4319  // decision should be made in the driver as well though.4320  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();4321 4322  bool SplitDWARFInlining =4323      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,4324                   options::OPT_fno_split_dwarf_inlining, false);4325 4326  // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does4327  // object file generation and no IR generation, -gN should not be needed. So4328  // allow -gsplit-dwarf with either -gN or IR input.4329  if (IRInput || Args.hasArg(options::OPT_g_Group)) {4330    // FIXME: -gsplit-dwarf on AIX is currently unimplemented.4331    if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {4332      D.Diag(diag::err_drv_unsupported_opt_for_target)4333          << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()4334          << TC.getTriple().str();4335      return;4336    }4337    Arg *SplitDWARFArg;4338    DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);4339    if (DwarfFission != DwarfFissionKind::None &&4340        !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {4341      DwarfFission = DwarfFissionKind::None;4342      SplitDWARFInlining = false;4343    }4344  }4345  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {4346    DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;4347 4348    // If the last option explicitly specified a debug-info level, use it.4349    if (checkDebugInfoOption(A, Args, D, TC) &&4350        A->getOption().matches(options::OPT_gN_Group)) {4351      DebugInfoKind = debugLevelToInfoKind(*A);4352      // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more4353      // complicated if you've disabled inline info in the skeleton CUs4354      // (SplitDWARFInlining) - then there's value in composing split-dwarf and4355      // line-tables-only, so let those compose naturally in that case.4356      if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||4357          DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||4358          (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&4359           SplitDWARFInlining))4360        DwarfFission = DwarfFissionKind::None;4361    }4362  }4363 4364  // If a debugger tuning argument appeared, remember it.4365  bool HasDebuggerTuning = false;4366  if (const Arg *A =4367          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {4368    HasDebuggerTuning = true;4369    if (checkDebugInfoOption(A, Args, D, TC)) {4370      if (A->getOption().matches(options::OPT_glldb))4371        DebuggerTuning = llvm::DebuggerKind::LLDB;4372      else if (A->getOption().matches(options::OPT_gsce))4373        DebuggerTuning = llvm::DebuggerKind::SCE;4374      else if (A->getOption().matches(options::OPT_gdbx))4375        DebuggerTuning = llvm::DebuggerKind::DBX;4376      else4377        DebuggerTuning = llvm::DebuggerKind::GDB;4378    }4379  }4380 4381  // If a -gdwarf argument appeared, remember it.4382  bool EmitDwarf = false;4383  if (const Arg *A = getDwarfNArg(Args))4384    EmitDwarf = checkDebugInfoOption(A, Args, D, TC);4385 4386  bool EmitCodeView = false;4387  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))4388    EmitCodeView = checkDebugInfoOption(A, Args, D, TC);4389 4390  // If the user asked for debug info but did not explicitly specify -gcodeview4391  // or -gdwarf, ask the toolchain for the default format.4392  if (!EmitCodeView && !EmitDwarf &&4393      DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {4394    switch (TC.getDefaultDebugFormat()) {4395    case llvm::codegenoptions::DIF_CodeView:4396      EmitCodeView = true;4397      break;4398    case llvm::codegenoptions::DIF_DWARF:4399      EmitDwarf = true;4400      break;4401    }4402  }4403 4404  unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user4405  unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may4406                                      // be lower than what the user wanted.4407  if (EmitDwarf) {4408    RequestedDWARFVersion = getDwarfVersion(TC, Args);4409    // Clamp effective DWARF version to the max supported by the toolchain.4410    EffectiveDWARFVersion =4411        std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());4412  } else {4413    Args.ClaimAllArgs(options::OPT_fdebug_default_version);4414  }4415 4416  // -gline-directives-only supported only for the DWARF debug info.4417  if (RequestedDWARFVersion == 0 &&4418      DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)4419    DebugInfoKind = llvm::codegenoptions::NoDebugInfo;4420 4421  // strict DWARF is set to false by default. But for DBX, we need it to be set4422  // as true by default.4423  if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))4424    (void)checkDebugInfoOption(A, Args, D, TC);4425  if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,4426                   DebuggerTuning == llvm::DebuggerKind::DBX))4427    CmdArgs.push_back("-gstrict-dwarf");4428 4429  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.4430  Args.ClaimAllArgs(options::OPT_g_flags_Group);4431 4432  // Column info is included by default for everything except SCE and4433  // CodeView if not use sampling PGO. Clang doesn't track end columns, just4434  // starting columns, which, in theory, is fine for CodeView (and PDB).  In4435  // practice, however, the Microsoft debuggers don't handle missing end columns4436  // well, and the AIX debugger DBX also doesn't handle the columns well, so4437  // it's better not to include any column info.4438  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))4439    (void)checkDebugInfoOption(A, Args, D, TC);4440  if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,4441                    !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&4442                        (DebuggerTuning != llvm::DebuggerKind::SCE &&4443                         DebuggerTuning != llvm::DebuggerKind::DBX)))4444    CmdArgs.push_back("-gno-column-info");4445 4446  if (!Args.hasFlag(options::OPT_gcall_site_info,4447                    options::OPT_gno_call_site_info, true))4448    CmdArgs.push_back("-gno-call-site-info");4449 4450  // FIXME: Move backend command line options to the module.4451  if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {4452    // If -gline-tables-only or -gline-directives-only is the last option it4453    // wins.4454    if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,4455                             TC)) {4456      if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&4457          DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {4458        DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;4459        CmdArgs.push_back("-dwarf-ext-refs");4460        CmdArgs.push_back("-fmodule-format=obj");4461      }4462    }4463  }4464 4465  if (T.isOSBinFormatELF() && SplitDWARFInlining)4466    CmdArgs.push_back("-fsplit-dwarf-inlining");4467 4468  // After we've dealt with all combinations of things that could4469  // make DebugInfoKind be other than None or DebugLineTablesOnly,4470  // figure out if we need to "upgrade" it to standalone debug info.4471  // We parse these two '-f' options whether or not they will be used,4472  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"4473  bool NeedFullDebug = Args.hasFlag(4474      options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,4475      DebuggerTuning == llvm::DebuggerKind::LLDB ||4476          TC.GetDefaultStandaloneDebug());4477  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))4478    (void)checkDebugInfoOption(A, Args, D, TC);4479 4480  if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||4481      DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {4482    if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,4483                     options::OPT_feliminate_unused_debug_types, false))4484      DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;4485    else if (NeedFullDebug)4486      DebugInfoKind = llvm::codegenoptions::FullDebugInfo;4487  }4488 4489  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,4490                   false)) {4491    // Source embedding is a vendor extension to DWARF v5. By now we have4492    // checked if a DWARF version was stated explicitly, and have otherwise4493    // fallen back to the target default, so if this is still not at least 54494    // we emit an error.4495    const Arg *A = Args.getLastArg(options::OPT_gembed_source);4496    if (RequestedDWARFVersion < 5)4497      D.Diag(diag::err_drv_argument_only_allowed_with)4498          << A->getAsString(Args) << "-gdwarf-5";4499    else if (EffectiveDWARFVersion < 5)4500      // The toolchain has reduced allowed dwarf version, so we can't enable4501      // -gembed-source.4502      D.Diag(diag::warn_drv_dwarf_version_limited_by_target)4503          << A->getAsString(Args) << TC.getTripleString() << 54504          << EffectiveDWARFVersion;4505    else if (checkDebugInfoOption(A, Args, D, TC))4506      CmdArgs.push_back("-gembed-source");4507  }4508 4509  // Enable Key Instructions by default if we're emitting DWARF, the language is4510  // plain C or C++, and optimisations are enabled.4511  Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);4512  bool KeyInstructionsOnByDefault =4513      EmitDwarf && PlainCOrCXX && OptLevel &&4514      !OptLevel->getOption().matches(options::OPT_O0);4515  if (Args.hasFlag(options::OPT_gkey_instructions,4516                   options::OPT_gno_key_instructions,4517                   KeyInstructionsOnByDefault))4518    CmdArgs.push_back("-gkey-instructions");4519 4520  if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,4521                    options::OPT_gno_structor_decl_linkage_names, true))4522    CmdArgs.push_back("-gno-structor-decl-linkage-names");4523 4524  if (EmitCodeView) {4525    CmdArgs.push_back("-gcodeview");4526 4527    Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,4528                      options::OPT_gno_codeview_ghash);4529 4530    Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,4531                       options::OPT_gno_codeview_command_line);4532  }4533 4534  Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,4535                     options::OPT_gno_inline_line_tables);4536 4537  // When emitting remarks, we need at least debug lines in the output.4538  if (willEmitRemarks(Args) &&4539      DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)4540    DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;4541 4542  // Adjust the debug info kind for the given toolchain.4543  TC.adjustDebugInfoKind(DebugInfoKind, Args);4544 4545  // On AIX, the debugger tuning option can be omitted if it is not explicitly4546  // set.4547  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,4548                          T.isOSAIX() && !HasDebuggerTuning4549                              ? llvm::DebuggerKind::Default4550                              : DebuggerTuning);4551 4552  // -fdebug-macro turns on macro debug info generation.4553  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,4554                   false))4555    if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,4556                             D, TC))4557      CmdArgs.push_back("-debug-info-macro");4558 4559  // -ggnu-pubnames turns on gnu style pubnames in the backend.4560  const auto *PubnamesArg =4561      Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,4562                      options::OPT_gpubnames, options::OPT_gno_pubnames);4563  if (DwarfFission != DwarfFissionKind::None ||4564      (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {4565    const bool OptionSet =4566        (PubnamesArg &&4567         (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||4568          PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));4569    if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&4570        (!PubnamesArg ||4571         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&4572          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))4573      CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(4574                                           options::OPT_gpubnames)4575                            ? "-gpubnames"4576                            : "-ggnu-pubnames");4577  }4578  const auto *SimpleTemplateNamesArg =4579      Args.getLastArg(options::OPT_gsimple_template_names,4580                      options::OPT_gno_simple_template_names);4581  bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;4582  if (SimpleTemplateNamesArg &&4583      checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {4584    const auto &Opt = SimpleTemplateNamesArg->getOption();4585    if (Opt.matches(options::OPT_gsimple_template_names)) {4586      ForwardTemplateParams = true;4587      CmdArgs.push_back("-gsimple-template-names=simple");4588    }4589  }4590 4591  // Emit DW_TAG_template_alias for template aliases? True by default for SCE.4592  bool UseDebugTemplateAlias =4593      DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;4594  if (const auto *DebugTemplateAlias = Args.getLastArg(4595          options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {4596    // DW_TAG_template_alias is only supported from DWARFv5 but if a user4597    // asks for it we should let them have it (if the target supports it).4598    if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {4599      const auto &Opt = DebugTemplateAlias->getOption();4600      UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);4601    }4602  }4603  if (UseDebugTemplateAlias)4604    CmdArgs.push_back("-gtemplate-alias");4605 4606  if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {4607    StringRef v = A->getValue();4608    CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));4609  }4610 4611  Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,4612                    options::OPT_fno_debug_ranges_base_address);4613 4614  // -gdwarf-aranges turns on the emission of the aranges section in the4615  // backend.4616  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);4617      A && checkDebugInfoOption(A, Args, D, TC)) {4618    CmdArgs.push_back("-mllvm");4619    CmdArgs.push_back("-generate-arange-section");4620  }4621 4622  Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,4623                    options::OPT_fno_force_dwarf_frame);4624 4625  bool EnableTypeUnits = false;4626  if (Args.hasFlag(options::OPT_fdebug_types_section,4627                   options::OPT_fno_debug_types_section, false)) {4628    if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {4629      D.Diag(diag::err_drv_unsupported_opt_for_target)4630          << Args.getLastArg(options::OPT_fdebug_types_section)4631                 ->getAsString(Args)4632          << T.getTriple();4633    } else if (checkDebugInfoOption(4634                   Args.getLastArg(options::OPT_fdebug_types_section), Args, D,4635                   TC)) {4636      EnableTypeUnits = true;4637      CmdArgs.push_back("-mllvm");4638      CmdArgs.push_back("-generate-type-units");4639    }4640  }4641 4642  if (const Arg *A =4643          Args.getLastArg(options::OPT_gomit_unreferenced_methods,4644                          options::OPT_gno_omit_unreferenced_methods))4645    (void)checkDebugInfoOption(A, Args, D, TC);4646  if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,4647                   options::OPT_gno_omit_unreferenced_methods, false) &&4648      (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||4649       DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&4650      !EnableTypeUnits) {4651    CmdArgs.push_back("-gomit-unreferenced-methods");4652  }4653 4654  // To avoid join/split of directory+filename, the integrated assembler prefers4655  // the directory form of .file on all DWARF versions. GNU as doesn't allow the4656  // form before DWARF v5.4657  if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,4658                    options::OPT_fno_dwarf_directory_asm,4659                    TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))4660    CmdArgs.push_back("-fno-dwarf-directory-asm");4661 4662  // Decide how to render forward declarations of template instantiations.4663  // SCE wants full descriptions, others just get them in the name.4664  if (ForwardTemplateParams)4665    CmdArgs.push_back("-debug-forward-template-params");4666 4667  // Do we need to explicitly import anonymous namespaces into the parent4668  // scope?4669  if (DebuggerTuning == llvm::DebuggerKind::SCE)4670    CmdArgs.push_back("-dwarf-explicit-import");4671 4672  renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);4673  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);4674 4675  // This controls whether or not we perform JustMyCode instrumentation.4676  if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {4677    if (TC.getTriple().isOSBinFormatELF() ||4678        TC.getTriple().isWindowsMSVCEnvironment()) {4679      if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)4680        CmdArgs.push_back("-fjmc");4681      else if (D.IsCLMode())4682        D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"4683                                                             << "'/Zi', '/Z7'";4684      else4685        D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"4686                                                             << "-g";4687    } else {4688      D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);4689    }4690  }4691 4692  // Add in -fdebug-compilation-dir if necessary.4693  const char *DebugCompilationDir =4694      addDebugCompDirArg(Args, CmdArgs, D.getVFS());4695 4696  addDebugPrefixMapArg(D, TC, Args, CmdArgs);4697 4698  // Add the output path to the object file for CodeView debug infos.4699  if (EmitCodeView && Output.isFilename())4700    addDebugObjectName(Args, CmdArgs, DebugCompilationDir,4701                       Output.getFilename());4702}4703 4704static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,4705                                    ArgStringList &CmdArgs) {4706  unsigned RTOptionID = options::OPT__SLASH_MT;4707 4708  if (Args.hasArg(options::OPT__SLASH_LDd))4709    // The /LDd option implies /MTd. The dependent lib part can be overridden,4710    // but defining _DEBUG is sticky.4711    RTOptionID = options::OPT__SLASH_MTd;4712 4713  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))4714    RTOptionID = A->getOption().getID();4715 4716  if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {4717    RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())4718                     .Case("static", options::OPT__SLASH_MT)4719                     .Case("static_dbg", options::OPT__SLASH_MTd)4720                     .Case("dll", options::OPT__SLASH_MD)4721                     .Case("dll_dbg", options::OPT__SLASH_MDd)4722                     .Default(options::OPT__SLASH_MT);4723  }4724 4725  StringRef FlagForCRT;4726  switch (RTOptionID) {4727  case options::OPT__SLASH_MD:4728    if (Args.hasArg(options::OPT__SLASH_LDd))4729      CmdArgs.push_back("-D_DEBUG");4730    CmdArgs.push_back("-D_MT");4731    CmdArgs.push_back("-D_DLL");4732    FlagForCRT = "--dependent-lib=msvcrt";4733    break;4734  case options::OPT__SLASH_MDd:4735    CmdArgs.push_back("-D_DEBUG");4736    CmdArgs.push_back("-D_MT");4737    CmdArgs.push_back("-D_DLL");4738    FlagForCRT = "--dependent-lib=msvcrtd";4739    break;4740  case options::OPT__SLASH_MT:4741    if (Args.hasArg(options::OPT__SLASH_LDd))4742      CmdArgs.push_back("-D_DEBUG");4743    CmdArgs.push_back("-D_MT");4744    CmdArgs.push_back("-flto-visibility-public-std");4745    FlagForCRT = "--dependent-lib=libcmt";4746    break;4747  case options::OPT__SLASH_MTd:4748    CmdArgs.push_back("-D_DEBUG");4749    CmdArgs.push_back("-D_MT");4750    CmdArgs.push_back("-flto-visibility-public-std");4751    FlagForCRT = "--dependent-lib=libcmtd";4752    break;4753  default:4754    llvm_unreachable("Unexpected option ID.");4755  }4756 4757  if (Args.hasArg(options::OPT_fms_omit_default_lib)) {4758    CmdArgs.push_back("-D_VC_NODEFAULTLIB");4759  } else {4760    CmdArgs.push_back(FlagForCRT.data());4761 4762    // This provides POSIX compatibility (maps 'open' to '_open'), which most4763    // users want.  The /Za flag to cl.exe turns this off, but it's not4764    // implemented in clang.4765    CmdArgs.push_back("--dependent-lib=oldnames");4766  }4767 4768  // All Arm64EC object files implicitly add softintrin.lib. This is necessary4769  // even if the file doesn't actually refer to any of the routines because4770  // the CRT itself has incomplete dependency markings.4771  if (TC.getTriple().isWindowsArm64EC())4772    CmdArgs.push_back("--dependent-lib=softintrin");4773}4774 4775void Clang::ConstructJob(Compilation &C, const JobAction &JA,4776                         const InputInfo &Output, const InputInfoList &Inputs,4777                         const ArgList &Args, const char *LinkingOutput) const {4778  const auto &TC = getToolChain();4779  const llvm::Triple &RawTriple = TC.getTriple();4780  const llvm::Triple &Triple = TC.getEffectiveTriple();4781  const std::string &TripleStr = Triple.getTriple();4782 4783  bool KernelOrKext =4784      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);4785  const Driver &D = TC.getDriver();4786  ArgStringList CmdArgs;4787 4788  assert(Inputs.size() >= 1 && "Must have at least one input.");4789  // CUDA/HIP compilation may have multiple inputs (source file + results of4790  // device-side compilations). OpenMP device jobs also take the host IR as a4791  // second input. Module precompilation accepts a list of header files to4792  // include as part of the module. API extraction accepts a list of header4793  // files whose API information is emitted in the output. All other jobs are4794  // expected to have exactly one input. SYCL compilation only expects a4795  // single input.4796  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);4797  bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);4798  bool IsHIP = JA.isOffloading(Action::OFK_HIP);4799  bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);4800  bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);4801  bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);4802  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);4803  bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);4804  bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||4805                                 JA.isDeviceOffloading(Action::OFK_Host));4806  bool IsHostOffloadingAction =4807      JA.isHostOffloading(Action::OFK_OpenMP) ||4808      JA.isHostOffloading(Action::OFK_SYCL) ||4809      (JA.isHostOffloading(C.getActiveOffloadKinds()) &&4810       Args.hasFlag(options::OPT_offload_new_driver,4811                    options::OPT_no_offload_new_driver,4812                    C.isOffloadingHostKind(Action::OFK_Cuda)));4813 4814  bool IsRDCMode =4815      Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);4816 4817  auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();4818  bool IsUsingLTO = LTOMode != LTOK_None;4819 4820  // Extract API doesn't have a main input file, so invent a fake one as a4821  // placeholder.4822  InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",4823                                       "extract-api");4824 4825  const InputInfo &Input =4826      IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];4827 4828  InputInfoList ExtractAPIInputs;4829  InputInfoList HostOffloadingInputs;4830  const InputInfo *CudaDeviceInput = nullptr;4831  const InputInfo *OpenMPDeviceInput = nullptr;4832  for (const InputInfo &I : Inputs) {4833    if (&I == &Input || I.getType() == types::TY_Nothing) {4834      // This is the primary input or contains nothing.4835    } else if (IsExtractAPI) {4836      auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();4837      if (I.getType() != ExpectedInputType) {4838        D.Diag(diag::err_drv_extract_api_wrong_kind)4839            << I.getFilename() << types::getTypeName(I.getType())4840            << types::getTypeName(ExpectedInputType);4841      }4842      ExtractAPIInputs.push_back(I);4843    } else if (IsHostOffloadingAction) {4844      HostOffloadingInputs.push_back(I);4845    } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {4846      CudaDeviceInput = &I;4847    } else if (IsOpenMPDevice && !OpenMPDeviceInput) {4848      OpenMPDeviceInput = &I;4849    } else {4850      llvm_unreachable("unexpectedly given multiple inputs");4851    }4852  }4853 4854  const llvm::Triple *AuxTriple =4855      (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;4856  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();4857  bool IsUEFI = RawTriple.isUEFI();4858  bool IsIAMCU = RawTriple.isOSIAMCU();4859 4860  // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations.  Even when compiling in4861  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not4862  // Windows), we need to pass Windows-specific flags to cc1.4863  if (IsCuda || IsHIP || IsSYCL)4864    IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();4865 4866  // C++ is not supported for IAMCU.4867  if (IsIAMCU && types::isCXX(Input.getType()))4868    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";4869 4870  // Invoke ourselves in -cc1 mode.4871  //4872  // FIXME: Implement custom jobs for internal actions.4873  CmdArgs.push_back("-cc1");4874 4875  // Add the "effective" target triple.4876  CmdArgs.push_back("-triple");4877  CmdArgs.push_back(Args.MakeArgString(TripleStr));4878 4879  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {4880    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);4881    Args.ClaimAllArgs(options::OPT_MJ);4882  } else if (const Arg *GenCDBFragment =4883                 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {4884    DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,4885                                         TripleStr, Output, Input, Args);4886    Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);4887  }4888 4889  if (IsCuda || IsHIP) {4890    // We have to pass the triple of the host if compiling for a CUDA/HIP device4891    // and vice-versa.4892    std::string NormalizedTriple;4893    if (JA.isDeviceOffloading(Action::OFK_Cuda) ||4894        JA.isDeviceOffloading(Action::OFK_HIP))4895      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()4896                             ->getTriple()4897                             .normalize();4898    else {4899      // Host-side compilation.4900      NormalizedTriple =4901          (IsCuda ? C.getOffloadToolChains(Action::OFK_Cuda).first->second4902                  : C.getOffloadToolChains(Action::OFK_HIP).first->second)4903              ->getTriple()4904              .normalize();4905      if (IsCuda) {4906        // We need to figure out which CUDA version we're compiling for, as that4907        // determines how we load and launch GPU kernels.4908        auto *CTC = static_cast<const toolchains::CudaToolChain *>(4909            C.getSingleOffloadToolChain<Action::OFK_Cuda>());4910        assert(CTC && "Expected valid CUDA Toolchain.");4911        if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)4912          CmdArgs.push_back(Args.MakeArgString(4913              Twine("-target-sdk-version=") +4914              CudaVersionToString(CTC->CudaInstallation.version())));4915        // Unsized function arguments used for variadics were introduced in4916        // CUDA-9.0. We still do not support generating code that actually uses4917        // variadic arguments yet, but we do need to allow parsing them as4918        // recent CUDA headers rely on that.4919        // https://github.com/llvm/llvm-project/issues/584104920        if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)4921          CmdArgs.push_back("-fcuda-allow-variadic-functions");4922      }4923    }4924    CmdArgs.push_back("-aux-triple");4925    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));4926 4927    if (JA.isDeviceOffloading(Action::OFK_HIP) &&4928        (getToolChain().getTriple().isAMDGPU() ||4929         (getToolChain().getTriple().isSPIRV() &&4930          getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {4931      // Device side compilation printf4932      if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {4933        CmdArgs.push_back(Args.MakeArgString(4934            "-mprintf-kind=" +4935            Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));4936        // Force compiler error on invalid conversion specifiers4937        CmdArgs.push_back(4938            Args.MakeArgString("-Werror=format-invalid-specifier"));4939      }4940    }4941  }4942 4943  // Optimization level for CodeGen.4944  if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {4945    if (A->getOption().matches(options::OPT_O4)) {4946      CmdArgs.push_back("-O3");4947      D.Diag(diag::warn_O4_is_O3);4948    } else {4949      A->render(Args, CmdArgs);4950    }4951  }4952 4953  // Unconditionally claim the printf option now to avoid unused diagnostic.4954  if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))4955    PF->claim();4956 4957  if (IsSYCL) {4958    if (IsSYCLDevice) {4959      // Host triple is needed when doing SYCL device compilations.4960      llvm::Triple AuxT = C.getDefaultToolChain().getTriple();4961      std::string NormalizedTriple = AuxT.normalize();4962      CmdArgs.push_back("-aux-triple");4963      CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));4964 4965      // We want to compile sycl kernels.4966      CmdArgs.push_back("-fsycl-is-device");4967 4968      // Set O2 optimization level by default4969      if (!Args.getLastArg(options::OPT_O_Group))4970        CmdArgs.push_back("-O2");4971    } else {4972      // Add any options that are needed specific to SYCL offload while4973      // performing the host side compilation.4974 4975      // Let the front-end host compilation flow know about SYCL offload4976      // compilation.4977      CmdArgs.push_back("-fsycl-is-host");4978    }4979 4980    // Set options for both host and device.4981    Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);4982    if (SYCLStdArg) {4983      SYCLStdArg->render(Args, CmdArgs);4984    } else {4985      // Ensure the default version in SYCL mode is 2020.4986      CmdArgs.push_back("-sycl-std=2020");4987    }4988  }4989 4990  if (Args.hasArg(options::OPT_fclangir))4991    CmdArgs.push_back("-fclangir");4992 4993  if (IsOpenMPDevice) {4994    // We have to pass the triple of the host if compiling for an OpenMP device.4995    std::string NormalizedTriple =4996        C.getSingleOffloadToolChain<Action::OFK_Host>()4997            ->getTriple()4998            .normalize();4999    CmdArgs.push_back("-aux-triple");5000    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));5001  }5002 5003  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||5004                               Triple.getArch() == llvm::Triple::thumb)) {5005    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;5006    unsigned Version = 0;5007    bool Failure =5008        Triple.getArchName().substr(Offset).consumeInteger(10, Version);5009    if (Failure || Version < 7)5010      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()5011                                                << TripleStr;5012  }5013 5014  // Push all default warning arguments that are specific to5015  // the given target.  These come before user provided warning options5016  // are provided.5017  TC.addClangWarningOptions(CmdArgs);5018 5019  // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.5020  if (Triple.isSPIR() || Triple.isSPIRV())5021    CmdArgs.push_back("-Wspir-compat");5022 5023  // Select the appropriate action.5024  RewriteKind rewriteKind = RK_None;5025 5026  bool UnifiedLTO = false;5027  if (IsUsingLTO) {5028    UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,5029                              options::OPT_fno_unified_lto, Triple.isPS());5030    if (UnifiedLTO)5031      CmdArgs.push_back("-funified-lto");5032  }5033 5034  // If CollectArgsForIntegratedAssembler() isn't called below, claim the args5035  // it claims when not running an assembler. Otherwise, clang would emit5036  // "argument unused" warnings for assembler flags when e.g. adding "-E" to5037  // flags while debugging something. That'd be somewhat inconvenient, and it's5038  // also inconsistent with most other flags -- we don't warn on5039  // -ffunction-sections not being used in -E mode either for example, even5040  // though it's not really used either.5041  if (!isa<AssembleJobAction>(JA)) {5042    // The args claimed here should match the args used in5043    // CollectArgsForIntegratedAssembler().5044    if (TC.useIntegratedAs()) {5045      Args.ClaimAllArgs(options::OPT_mrelax_all);5046      Args.ClaimAllArgs(options::OPT_mno_relax_all);5047      Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);5048      Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);5049      switch (C.getDefaultToolChain().getArch()) {5050      case llvm::Triple::arm:5051      case llvm::Triple::armeb:5052      case llvm::Triple::thumb:5053      case llvm::Triple::thumbeb:5054        Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);5055        break;5056      default:5057        break;5058      }5059    }5060    Args.ClaimAllArgs(options::OPT_Wa_COMMA);5061    Args.ClaimAllArgs(options::OPT_Xassembler);5062    Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);5063  }5064 5065  bool IsAMDSPIRVForHIPDevice =5066      IsHIPDevice && getToolChain().getTriple().isSPIRV() &&5067      getToolChain().getTriple().getVendor() == llvm::Triple::AMD;5068 5069  if (isa<AnalyzeJobAction>(JA)) {5070    assert(JA.getType() == types::TY_Plist && "Invalid output type.");5071    CmdArgs.push_back("-analyze");5072  } else if (isa<PreprocessJobAction>(JA)) {5073    if (Output.getType() == types::TY_Dependencies)5074      CmdArgs.push_back("-Eonly");5075    else {5076      CmdArgs.push_back("-E");5077      if (Args.hasArg(options::OPT_rewrite_objc) &&5078          !Args.hasArg(options::OPT_g_Group))5079        CmdArgs.push_back("-P");5080      else if (JA.getType() == types::TY_PP_CXXHeaderUnit)5081        CmdArgs.push_back("-fdirectives-only");5082    }5083  } else if (isa<AssembleJobAction>(JA)) {5084    CmdArgs.push_back("-emit-obj");5085 5086    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);5087 5088    // Also ignore explicit -force_cpusubtype_ALL option.5089    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);5090  } else if (isa<PrecompileJobAction>(JA)) {5091    if (JA.getType() == types::TY_Nothing)5092      CmdArgs.push_back("-fsyntax-only");5093    else if (JA.getType() == types::TY_ModuleFile)5094      CmdArgs.push_back("-emit-module-interface");5095    else if (JA.getType() == types::TY_HeaderUnit)5096      CmdArgs.push_back("-emit-header-unit");5097    else if (!Args.hasArg(options::OPT_ignore_pch))5098      CmdArgs.push_back("-emit-pch");5099  } else if (isa<VerifyPCHJobAction>(JA)) {5100    CmdArgs.push_back("-verify-pch");5101  } else if (isa<ExtractAPIJobAction>(JA)) {5102    assert(JA.getType() == types::TY_API_INFO &&5103           "Extract API actions must generate a API information.");5104    CmdArgs.push_back("-extract-api");5105 5106    if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))5107      PrettySGFArg->render(Args, CmdArgs);5108 5109    Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);5110 5111    if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))5112      ProductNameArg->render(Args, CmdArgs);5113    if (Arg *ExtractAPIIgnoresFileArg =5114            Args.getLastArg(options::OPT_extract_api_ignores_EQ))5115      ExtractAPIIgnoresFileArg->render(Args, CmdArgs);5116    if (Arg *EmitExtensionSymbolGraphs =5117            Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {5118      if (!SymbolGraphDirArg)5119        D.Diag(diag::err_drv_missing_symbol_graph_dir);5120 5121      EmitExtensionSymbolGraphs->render(Args, CmdArgs);5122    }5123    if (SymbolGraphDirArg)5124      SymbolGraphDirArg->render(Args, CmdArgs);5125  } else {5126    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&5127           "Invalid action for clang tool.");5128    if (JA.getType() == types::TY_Nothing) {5129      CmdArgs.push_back("-fsyntax-only");5130    } else if (JA.getType() == types::TY_LLVM_IR ||5131               JA.getType() == types::TY_LTO_IR) {5132      CmdArgs.push_back("-emit-llvm");5133    } else if (JA.getType() == types::TY_LLVM_BC ||5134               JA.getType() == types::TY_LTO_BC) {5135      // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S5136      if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&5137          Args.hasArg(options::OPT_emit_llvm)) {5138        CmdArgs.push_back("-emit-llvm");5139      } else {5140        CmdArgs.push_back("-emit-llvm-bc");5141      }5142    } else if (JA.getType() == types::TY_IFS ||5143               JA.getType() == types::TY_IFS_CPP) {5144      StringRef ArgStr =5145          Args.hasArg(options::OPT_interface_stub_version_EQ)5146              ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)5147              : "ifs-v1";5148      CmdArgs.push_back("-emit-interface-stubs");5149      CmdArgs.push_back(5150          Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));5151    } else if (JA.getType() == types::TY_PP_Asm) {5152      CmdArgs.push_back("-S");5153    } else if (JA.getType() == types::TY_AST) {5154      if (!Args.hasArg(options::OPT_ignore_pch))5155        CmdArgs.push_back("-emit-pch");5156    } else if (JA.getType() == types::TY_ModuleFile) {5157      CmdArgs.push_back("-module-file-info");5158    } else if (JA.getType() == types::TY_RewrittenObjC) {5159      CmdArgs.push_back("-rewrite-objc");5160      rewriteKind = RK_NonFragile;5161    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {5162      CmdArgs.push_back("-rewrite-objc");5163      rewriteKind = RK_Fragile;5164    } else if (JA.getType() == types::TY_CIR) {5165      CmdArgs.push_back("-emit-cir");5166    } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {5167      CmdArgs.push_back("-emit-obj");5168    } else {5169      assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");5170    }5171 5172    // Preserve use-list order by default when emitting bitcode, so that5173    // loading the bitcode up in 'opt' or 'llc' and running passes gives the5174    // same result as running passes here.  For LTO, we don't need to preserve5175    // the use-list order, since serialization to bitcode is part of the flow.5176    if (JA.getType() == types::TY_LLVM_BC)5177      CmdArgs.push_back("-emit-llvm-uselists");5178 5179    if (IsUsingLTO) {5180      if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&5181          !Args.hasFlag(options::OPT_offload_new_driver,5182                        options::OPT_no_offload_new_driver,5183                        C.isOffloadingHostKind(Action::OFK_Cuda)) &&5184          !Triple.isAMDGPU()) {5185        D.Diag(diag::err_drv_unsupported_opt_for_target)5186            << Args.getLastArg(options::OPT_foffload_lto,5187                               options::OPT_foffload_lto_EQ)5188                   ->getAsString(Args)5189            << Triple.getTriple();5190      } else if (Triple.isNVPTX() && !IsRDCMode &&5191                 JA.isDeviceOffloading(Action::OFK_Cuda)) {5192        D.Diag(diag::err_drv_unsupported_opt_for_language_mode)5193            << Args.getLastArg(options::OPT_foffload_lto,5194                               options::OPT_foffload_lto_EQ)5195                   ->getAsString(Args)5196            << "-fno-gpu-rdc";5197      } else {5198        assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);5199        CmdArgs.push_back(Args.MakeArgString(5200            Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));5201        // PS4 uses the legacy LTO API, which does not support some of the5202        // features enabled by -flto-unit.5203        if (!RawTriple.isPS4() ||5204            (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)5205          CmdArgs.push_back("-flto-unit");5206      }5207    }5208  }5209 5210  Args.AddLastArg(CmdArgs, options::OPT_dumpdir);5211 5212  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {5213    if (!types::isLLVMIR(Input.getType()))5214      D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);5215    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);5216  }5217 5218  if (Triple.isPPC())5219    Args.addOptInFlag(CmdArgs, options::OPT_mregnames,5220                      options::OPT_mno_regnames);5221 5222  if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))5223    Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);5224 5225  if (Args.getLastArg(options::OPT_save_temps_EQ))5226    Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);5227 5228  auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,5229                                     options::OPT_fmemory_profile_EQ,5230                                     options::OPT_fno_memory_profile);5231  if (MemProfArg &&5232      !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))5233    MemProfArg->render(Args, CmdArgs);5234 5235  if (auto *MemProfUseArg =5236          Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {5237    if (MemProfArg)5238      D.Diag(diag::err_drv_argument_not_allowed_with)5239          << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);5240    if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,5241                                            options::OPT_fprofile_generate_EQ))5242      D.Diag(diag::err_drv_argument_not_allowed_with)5243          << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);5244    MemProfUseArg->render(Args, CmdArgs);5245  }5246 5247  // Embed-bitcode option.5248  // Only white-listed flags below are allowed to be embedded.5249  if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&5250      (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {5251    // Add flags implied by -fembed-bitcode.5252    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);5253    // Disable all llvm IR level optimizations.5254    CmdArgs.push_back("-disable-llvm-passes");5255 5256    // Render target options.5257    TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());5258 5259    // reject options that shouldn't be supported in bitcode5260    // also reject kernel/kext5261    static const constexpr unsigned kBitcodeOptionIgnorelist[] = {5262        options::OPT_mkernel,5263        options::OPT_fapple_kext,5264        options::OPT_ffunction_sections,5265        options::OPT_fno_function_sections,5266        options::OPT_fdata_sections,5267        options::OPT_fno_data_sections,5268        options::OPT_fbasic_block_sections_EQ,5269        options::OPT_funique_internal_linkage_names,5270        options::OPT_fno_unique_internal_linkage_names,5271        options::OPT_funique_section_names,5272        options::OPT_fno_unique_section_names,5273        options::OPT_funique_basic_block_section_names,5274        options::OPT_fno_unique_basic_block_section_names,5275        options::OPT_mrestrict_it,5276        options::OPT_mno_restrict_it,5277        options::OPT_mstackrealign,5278        options::OPT_mno_stackrealign,5279        options::OPT_mstack_alignment,5280        options::OPT_mcmodel_EQ,5281        options::OPT_mlong_calls,5282        options::OPT_mno_long_calls,5283        options::OPT_ggnu_pubnames,5284        options::OPT_gdwarf_aranges,5285        options::OPT_fdebug_types_section,5286        options::OPT_fno_debug_types_section,5287        options::OPT_fdwarf_directory_asm,5288        options::OPT_fno_dwarf_directory_asm,5289        options::OPT_mrelax_all,5290        options::OPT_mno_relax_all,5291        options::OPT_ftrap_function_EQ,5292        options::OPT_ffixed_r9,5293        options::OPT_mfix_cortex_a53_835769,5294        options::OPT_mno_fix_cortex_a53_835769,5295        options::OPT_ffixed_x18,5296        options::OPT_mglobal_merge,5297        options::OPT_mno_global_merge,5298        options::OPT_mred_zone,5299        options::OPT_mno_red_zone,5300        options::OPT_Wa_COMMA,5301        options::OPT_Xassembler,5302        options::OPT_mllvm,5303        options::OPT_mmlir,5304    };5305    for (const auto &A : Args)5306      if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))5307        D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();5308 5309    // Render the CodeGen options that need to be passed.5310    Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,5311                       options::OPT_fno_optimize_sibling_calls);5312 5313    RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,5314                               CmdArgs, JA);5315 5316    // Render ABI arguments5317    switch (TC.getArch()) {5318    default: break;5319    case llvm::Triple::arm:5320    case llvm::Triple::armeb:5321    case llvm::Triple::thumbeb:5322      RenderARMABI(D, Triple, Args, CmdArgs);5323      break;5324    case llvm::Triple::aarch64:5325    case llvm::Triple::aarch64_32:5326    case llvm::Triple::aarch64_be:5327      RenderAArch64ABI(Triple, Args, CmdArgs);5328      break;5329    }5330 5331    // Input/Output file.5332    if (Output.getType() == types::TY_Dependencies) {5333      // Handled with other dependency code.5334    } else if (Output.isFilename()) {5335      CmdArgs.push_back("-o");5336      CmdArgs.push_back(Output.getFilename());5337    } else {5338      assert(Output.isNothing() && "Input output.");5339    }5340 5341    for (const auto &II : Inputs) {5342      addDashXForInput(Args, II, CmdArgs);5343      if (II.isFilename())5344        CmdArgs.push_back(II.getFilename());5345      else5346        II.getInputArg().renderAsInput(Args, CmdArgs);5347    }5348 5349    C.addCommand(std::make_unique<Command>(5350        JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),5351        CmdArgs, Inputs, Output, D.getPrependArg()));5352    return;5353  }5354 5355  if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)5356    CmdArgs.push_back("-fembed-bitcode=marker");5357 5358  // We normally speed up the clang process a bit by skipping destructors at5359  // exit, but when we're generating diagnostics we can rely on some of the5360  // cleanup.5361  if (!C.isForDiagnostics())5362    CmdArgs.push_back("-disable-free");5363  CmdArgs.push_back("-clear-ast-before-backend");5364 5365#ifdef NDEBUG5366  const bool IsAssertBuild = false;5367#else5368  const bool IsAssertBuild = true;5369#endif5370 5371  // Disable the verification pass in no-asserts builds unless otherwise5372  // specified.5373  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,5374                   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {5375    CmdArgs.push_back("-disable-llvm-verifier");5376  }5377 5378  // Discard value names in no-asserts builds unless otherwise specified.5379  if (Args.hasFlag(options::OPT_fdiscard_value_names,5380                   options::OPT_fno_discard_value_names, !IsAssertBuild)) {5381    if (Args.hasArg(options::OPT_fdiscard_value_names) &&5382        llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {5383          return types::isLLVMIR(II.getType());5384        })) {5385      D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);5386    }5387    CmdArgs.push_back("-discard-value-names");5388  }5389 5390  // Set the main file name, so that debug info works even with5391  // -save-temps.5392  CmdArgs.push_back("-main-file-name");5393  CmdArgs.push_back(getBaseInputName(Args, Input));5394 5395  // Some flags which affect the language (via preprocessor5396  // defines).5397  if (Args.hasArg(options::OPT_static))5398    CmdArgs.push_back("-static-define");5399 5400  Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);5401 5402  if (Args.hasArg(options::OPT_municode))5403    CmdArgs.push_back("-DUNICODE");5404 5405  if (isa<AnalyzeJobAction>(JA))5406    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);5407 5408  if (isa<AnalyzeJobAction>(JA) ||5409      (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))5410    CmdArgs.push_back("-setup-static-analyzer");5411 5412  // Enable compatilibily mode to avoid analyzer-config related errors.5413  // Since we can't access frontend flags through hasArg, let's manually iterate5414  // through them.5415  bool FoundAnalyzerConfig = false;5416  for (auto *Arg : Args.filtered(options::OPT_Xclang))5417    if (StringRef(Arg->getValue()) == "-analyzer-config") {5418      FoundAnalyzerConfig = true;5419      break;5420    }5421  if (!FoundAnalyzerConfig)5422    for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))5423      if (StringRef(Arg->getValue()) == "-analyzer-config") {5424        FoundAnalyzerConfig = true;5425        break;5426      }5427  if (FoundAnalyzerConfig)5428    CmdArgs.push_back("-analyzer-config-compatibility-mode=true");5429 5430  CheckCodeGenerationOptions(D, Args);5431 5432  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);5433  assert(FunctionAlignment <= 31 && "function alignment will be truncated!");5434  if (FunctionAlignment) {5435    CmdArgs.push_back("-function-alignment");5436    CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));5437  }5438 5439  // We support -falign-loops=N where N is a power of 2. GCC supports more5440  // forms.5441  if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {5442    unsigned Value = 0;5443    if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)5444      TC.getDriver().Diag(diag::err_drv_invalid_int_value)5445          << A->getAsString(Args) << A->getValue();5446    else if (Value & (Value - 1))5447      TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)5448          << A->getAsString(Args) << A->getValue();5449    // Treat =0 as unspecified (use the target preference).5450    if (Value)5451      CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +5452                                           Twine(std::min(Value, 65536u))));5453  }5454 5455  if (Triple.isOSzOS()) {5456    // On z/OS some of the system header feature macros need to5457    // be defined to enable most cross platform projects to build5458    // successfully.  Ths include the libc++ library.  A5459    // complicating factor is that users can define these5460    // macros to the same or different values.  We need to add5461    // the definition for these macros to the compilation command5462    // if the user hasn't already defined them.5463 5464    auto findMacroDefinition = [&](const std::string &Macro) {5465      auto MacroDefs = Args.getAllArgValues(options::OPT_D);5466      return llvm::any_of(MacroDefs, [&](const std::string &M) {5467        return M == Macro || M.find(Macro + '=') != std::string::npos;5468      });5469    };5470 5471    // _UNIX03_WITHDRAWN is required for libcxx & porting.5472    if (!findMacroDefinition("_UNIX03_WITHDRAWN"))5473      CmdArgs.push_back("-D_UNIX03_WITHDRAWN");5474    // _OPEN_DEFAULT is required for XL compat5475    if (!findMacroDefinition("_OPEN_DEFAULT"))5476      CmdArgs.push_back("-D_OPEN_DEFAULT");5477    if (D.CCCIsCXX() || types::isCXX(Input.getType())) {5478      // _XOPEN_SOURCE=600 is required for libcxx.5479      if (!findMacroDefinition("_XOPEN_SOURCE"))5480        CmdArgs.push_back("-D_XOPEN_SOURCE=600");5481    }5482  }5483 5484  llvm::Reloc::Model RelocationModel;5485  unsigned PICLevel;5486  bool IsPIE;5487  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);5488  Arg *LastPICDataRelArg =5489      Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,5490                      options::OPT_mpic_data_is_text_relative);5491  bool NoPICDataIsTextRelative = false;5492  if (LastPICDataRelArg) {5493    if (LastPICDataRelArg->getOption().matches(5494            options::OPT_mno_pic_data_is_text_relative)) {5495      NoPICDataIsTextRelative = true;5496      if (!PICLevel)5497        D.Diag(diag::err_drv_argument_only_allowed_with)5498            << "-mno-pic-data-is-text-relative"5499            << "-fpic/-fpie";5500    }5501    if (!Triple.isSystemZ())5502      D.Diag(diag::err_drv_unsupported_opt_for_target)5503          << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"5504                                      : "-mpic-data-is-text-relative")5505          << RawTriple.str();5506  }5507 5508  bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||5509                RelocationModel == llvm::Reloc::ROPI_RWPI;5510  bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||5511                RelocationModel == llvm::Reloc::ROPI_RWPI;5512 5513  if (Args.hasArg(options::OPT_mcmse) &&5514      !Args.hasArg(options::OPT_fallow_unsupported)) {5515    if (IsROPI)5516      D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;5517    if (IsRWPI)5518      D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;5519  }5520 5521  if (IsROPI && types::isCXX(Input.getType()) &&5522      !Args.hasArg(options::OPT_fallow_unsupported))5523    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);5524 5525  const char *RMName = RelocationModelName(RelocationModel);5526  if (RMName) {5527    CmdArgs.push_back("-mrelocation-model");5528    CmdArgs.push_back(RMName);5529  }5530  if (PICLevel > 0) {5531    CmdArgs.push_back("-pic-level");5532    CmdArgs.push_back(PICLevel == 1 ? "1" : "2");5533    if (IsPIE)5534      CmdArgs.push_back("-pic-is-pie");5535    if (NoPICDataIsTextRelative)5536      CmdArgs.push_back("-mcmodel=medium");5537  }5538 5539  if (RelocationModel == llvm::Reloc::ROPI ||5540      RelocationModel == llvm::Reloc::ROPI_RWPI)5541    CmdArgs.push_back("-fropi");5542  if (RelocationModel == llvm::Reloc::RWPI ||5543      RelocationModel == llvm::Reloc::ROPI_RWPI)5544    CmdArgs.push_back("-frwpi");5545 5546  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {5547    CmdArgs.push_back("-meabi");5548    CmdArgs.push_back(A->getValue());5549  }5550 5551  // -fsemantic-interposition is forwarded to CC1: set the5552  // "SemanticInterposition" metadata to 1 (make some linkages interposable) and5553  // make default visibility external linkage definitions dso_preemptable.5554  //5555  // -fno-semantic-interposition: if the target supports .Lfoo$local local5556  // aliases (make default visibility external linkage definitions dso_local).5557  // This is the CC1 default for ELF to match COFF/Mach-O.5558  //5559  // Otherwise use Clang's traditional behavior: like5560  // -fno-semantic-interposition but local aliases are not used. So references5561  // can be interposed if not optimized out.5562  if (Triple.isOSBinFormatELF()) {5563    Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,5564                             options::OPT_fno_semantic_interposition);5565    if (RelocationModel != llvm::Reloc::Static && !IsPIE) {5566      // The supported targets need to call AsmPrinter::getSymbolPreferLocal.5567      bool SupportsLocalAlias =5568          Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();5569      if (!A)5570        CmdArgs.push_back("-fhalf-no-semantic-interposition");5571      else if (A->getOption().matches(options::OPT_fsemantic_interposition))5572        A->render(Args, CmdArgs);5573      else if (!SupportsLocalAlias)5574        CmdArgs.push_back("-fhalf-no-semantic-interposition");5575    }5576  }5577 5578  {5579    std::string Model;5580    if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {5581      if (!TC.isThreadModelSupported(A->getValue()))5582        D.Diag(diag::err_drv_invalid_thread_model_for_target)5583            << A->getValue() << A->getAsString(Args);5584      Model = A->getValue();5585    } else5586      Model = TC.getThreadModel();5587    if (Model != "posix") {5588      CmdArgs.push_back("-mthread-model");5589      CmdArgs.push_back(Args.MakeArgString(Model));5590    }5591  }5592 5593  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {5594    StringRef Name = A->getValue();5595    if (Name == "SVML") {5596      if (Triple.getArch() != llvm::Triple::x86 &&5597          Triple.getArch() != llvm::Triple::x86_64)5598        D.Diag(diag::err_drv_unsupported_opt_for_target)5599            << Name << Triple.getArchName();5600    } else if (Name == "AMDLIBM") {5601      if (Triple.getArch() != llvm::Triple::x86 &&5602          Triple.getArch() != llvm::Triple::x86_64)5603        D.Diag(diag::err_drv_unsupported_opt_for_target)5604            << Name << Triple.getArchName();5605    } else if (Name == "libmvec") {5606      if (Triple.getArch() != llvm::Triple::x86 &&5607          Triple.getArch() != llvm::Triple::x86_64 &&5608          Triple.getArch() != llvm::Triple::aarch64 &&5609          Triple.getArch() != llvm::Triple::aarch64_be)5610        D.Diag(diag::err_drv_unsupported_opt_for_target)5611            << Name << Triple.getArchName();5612    } else if (Name == "SLEEF" || Name == "ArmPL") {5613      if (Triple.getArch() != llvm::Triple::aarch64 &&5614          Triple.getArch() != llvm::Triple::aarch64_be &&5615          Triple.getArch() != llvm::Triple::riscv64)5616        D.Diag(diag::err_drv_unsupported_opt_for_target)5617            << Name << Triple.getArchName();5618    }5619    A->render(Args, CmdArgs);5620  }5621 5622  if (Args.hasFlag(options::OPT_fmerge_all_constants,5623                   options::OPT_fno_merge_all_constants, false))5624    CmdArgs.push_back("-fmerge-all-constants");5625 5626  Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,5627                     options::OPT_fno_delete_null_pointer_checks);5628 5629  // LLVM Code Generator Options.5630 5631  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {5632    if (!Triple.isOSAIX() || Triple.isPPC32())5633      D.Diag(diag::err_drv_unsupported_opt_for_target)5634        << A->getSpelling() << RawTriple.str();5635    CmdArgs.push_back("-mabi=quadword-atomics");5636  }5637 5638  if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {5639    // Emit the unsupported option error until the Clang's library integration5640    // support for 128-bit long double is available for AIX.5641    if (Triple.isOSAIX())5642      D.Diag(diag::err_drv_unsupported_opt_for_target)5643          << A->getSpelling() << RawTriple.str();5644  }5645 5646  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {5647    StringRef V = A->getValue(), V1 = V;5648    unsigned Size;5649    if (V1.consumeInteger(10, Size) || !V1.empty())5650      D.Diag(diag::err_drv_invalid_argument_to_option)5651          << V << A->getOption().getName();5652    else5653      CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));5654  }5655 5656  Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,5657                     options::OPT_fno_jump_tables);5658  Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,5659                    options::OPT_fno_profile_sample_accurate);5660  Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,5661                     options::OPT_fno_preserve_as_comments);5662 5663  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {5664    CmdArgs.push_back("-mregparm");5665    CmdArgs.push_back(A->getValue());5666  }5667 5668  if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,5669                               options::OPT_msvr4_struct_return)) {5670    if (!TC.getTriple().isPPC32()) {5671      D.Diag(diag::err_drv_unsupported_opt_for_target)5672          << A->getSpelling() << RawTriple.str();5673    } else if (A->getOption().matches(options::OPT_maix_struct_return)) {5674      CmdArgs.push_back("-maix-struct-return");5675    } else {5676      assert(A->getOption().matches(options::OPT_msvr4_struct_return));5677      CmdArgs.push_back("-msvr4-struct-return");5678    }5679  }5680 5681  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,5682                               options::OPT_freg_struct_return)) {5683    if (TC.getArch() != llvm::Triple::x86) {5684      D.Diag(diag::err_drv_unsupported_opt_for_target)5685          << A->getSpelling() << RawTriple.str();5686    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {5687      CmdArgs.push_back("-fpcc-struct-return");5688    } else {5689      assert(A->getOption().matches(options::OPT_freg_struct_return));5690      CmdArgs.push_back("-freg-struct-return");5691    }5692  }5693 5694  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {5695    if (Triple.getArch() == llvm::Triple::m68k)5696      CmdArgs.push_back("-fdefault-calling-conv=rtdcall");5697    else5698      CmdArgs.push_back("-fdefault-calling-conv=stdcall");5699  }5700 5701  if (Args.hasArg(options::OPT_fenable_matrix)) {5702    // enable-matrix is needed by both the LangOpts and by LLVM.5703    CmdArgs.push_back("-fenable-matrix");5704    CmdArgs.push_back("-mllvm");5705    CmdArgs.push_back("-enable-matrix");5706  }5707 5708  CodeGenOptions::FramePointerKind FPKeepKind =5709                  getFramePointerKind(Args, RawTriple);5710  const char *FPKeepKindStr = nullptr;5711  switch (FPKeepKind) {5712  case CodeGenOptions::FramePointerKind::None:5713    FPKeepKindStr = "-mframe-pointer=none";5714    break;5715  case CodeGenOptions::FramePointerKind::Reserved:5716    FPKeepKindStr = "-mframe-pointer=reserved";5717    break;5718  case CodeGenOptions::FramePointerKind::NonLeafNoReserve:5719    FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";5720    break;5721  case CodeGenOptions::FramePointerKind::NonLeaf:5722    FPKeepKindStr = "-mframe-pointer=non-leaf";5723    break;5724  case CodeGenOptions::FramePointerKind::All:5725    FPKeepKindStr = "-mframe-pointer=all";5726    break;5727  }5728  assert(FPKeepKindStr && "unknown FramePointerKind");5729  CmdArgs.push_back(FPKeepKindStr);5730 5731  Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,5732                     options::OPT_fno_zero_initialized_in_bss);5733 5734  bool OFastEnabled = isOptimizationLevelFast(Args);5735  if (OFastEnabled)5736    D.Diag(diag::warn_drv_deprecated_arg_ofast);5737  // If -Ofast is the optimization level, then -fstrict-aliasing should be5738  // enabled.  This alias option is being used to simplify the hasFlag logic.5739  OptSpecifier StrictAliasingAliasOption =5740      OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;5741  // We turn strict aliasing off by default if we're Windows MSVC since MSVC5742  // doesn't do any TBAA.5743  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,5744                    options::OPT_fno_strict_aliasing,5745                    !IsWindowsMSVC && !IsUEFI))5746    CmdArgs.push_back("-relaxed-aliasing");5747  if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,5748                   false))5749    CmdArgs.push_back("-no-pointer-tbaa");5750  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,5751                    options::OPT_fno_struct_path_tbaa, true))5752    CmdArgs.push_back("-no-struct-path-tbaa");5753  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,5754                    options::OPT_fno_strict_enums);5755  Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,5756                     options::OPT_fno_strict_return);5757  Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,5758                    options::OPT_fno_allow_editor_placeholders);5759  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,5760                    options::OPT_fno_strict_vtable_pointers);5761  Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,5762                    options::OPT_fno_force_emit_vtables);5763  Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,5764                     options::OPT_fno_optimize_sibling_calls);5765  Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,5766                     options::OPT_fno_escaping_block_tail_calls);5767 5768  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,5769                  options::OPT_fno_fine_grained_bitfield_accesses);5770 5771  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,5772                  options::OPT_fno_experimental_relative_cxx_abi_vtables);5773 5774  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,5775                  options::OPT_fno_experimental_omit_vtable_rtti);5776 5777  Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,5778                  options::OPT_fno_disable_block_signature_string);5779 5780  // Handle segmented stacks.5781  Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,5782                    options::OPT_fno_split_stack);5783 5784  // -fprotect-parens=0 is default.5785  if (Args.hasFlag(options::OPT_fprotect_parens,5786                   options::OPT_fno_protect_parens, false))5787    CmdArgs.push_back("-fprotect-parens");5788 5789  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);5790 5791  Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,5792                    options::OPT_fno_atomic_remote_memory);5793  Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,5794                    options::OPT_fno_atomic_fine_grained_memory);5795  Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,5796                    options::OPT_fno_atomic_ignore_denormal_mode);5797 5798  if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {5799    const llvm::Triple::ArchType Arch = TC.getArch();5800    if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {5801      StringRef V = A->getValue();5802      if (V == "64")5803        CmdArgs.push_back("-fextend-arguments=64");5804      else if (V != "32")5805        D.Diag(diag::err_drv_invalid_argument_to_option)5806            << A->getValue() << A->getOption().getName();5807    } else5808      D.Diag(diag::err_drv_unsupported_opt_for_target)5809          << A->getOption().getName() << TripleStr;5810  }5811 5812  if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {5813    if (TC.getArch() == llvm::Triple::avr)5814      A->render(Args, CmdArgs);5815    else5816      D.Diag(diag::err_drv_unsupported_opt_for_target)5817          << A->getAsString(Args) << TripleStr;5818  }5819 5820  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {5821    if (TC.getTriple().isX86())5822      A->render(Args, CmdArgs);5823    else if (TC.getTriple().isPPC() &&5824             (A->getOption().getID() != options::OPT_mlong_double_80))5825      A->render(Args, CmdArgs);5826    else5827      D.Diag(diag::err_drv_unsupported_opt_for_target)5828          << A->getAsString(Args) << TripleStr;5829  }5830 5831  // Decide whether to use verbose asm. Verbose assembly is the default on5832  // toolchains which have the integrated assembler on by default.5833  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();5834  if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,5835                    IsIntegratedAssemblerDefault))5836    CmdArgs.push_back("-fno-verbose-asm");5837 5838  // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we5839  // use that to indicate the MC default in the backend.5840  if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {5841    StringRef V = A->getValue();5842    unsigned Num;5843    if (V == "none")5844      A->render(Args, CmdArgs);5845    else if (!V.consumeInteger(10, Num) && Num > 0 &&5846             (V.empty() || (V.consume_front(".") &&5847                            !V.consumeInteger(10, Num) && V.empty())))5848      A->render(Args, CmdArgs);5849    else5850      D.Diag(diag::err_drv_invalid_argument_to_option)5851          << A->getValue() << A->getOption().getName();5852  }5853 5854  // If toolchain choose to use MCAsmParser for inline asm don't pass the5855  // option to disable integrated-as explicitly.5856  if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())5857    CmdArgs.push_back("-no-integrated-as");5858 5859  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {5860    CmdArgs.push_back("-mdebug-pass");5861    CmdArgs.push_back("Structure");5862  }5863  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {5864    CmdArgs.push_back("-mdebug-pass");5865    CmdArgs.push_back("Arguments");5866  }5867 5868  // Enable -mconstructor-aliases except on darwin, where we have to work around5869  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device5870  // code, where aliases aren't supported.5871  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())5872    CmdArgs.push_back("-mconstructor-aliases");5873 5874  // Darwin's kernel doesn't support guard variables; just die if we5875  // try to use them.5876  if (KernelOrKext && RawTriple.isOSDarwin())5877    CmdArgs.push_back("-fforbid-guard-variables");5878 5879  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,5880                   Triple.isWindowsGNUEnvironment())) {5881    CmdArgs.push_back("-mms-bitfields");5882  }5883 5884  if (Triple.isOSCygMing()) {5885    Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,5886                       options::OPT_fno_auto_import);5887  }5888 5889  if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,5890                   Triple.isX86() && IsWindowsMSVC))5891    CmdArgs.push_back("-fms-volatile");5892 5893  // Non-PIC code defaults to -fdirect-access-external-data while PIC code5894  // defaults to -fno-direct-access-external-data. Pass the option if different5895  // from the default.5896  if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,5897                               options::OPT_fno_direct_access_external_data)) {5898    if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=5899        (PICLevel == 0))5900      A->render(Args, CmdArgs);5901  } else if (PICLevel == 0 && Triple.isLoongArch()) {5902    // Some targets default to -fno-direct-access-external-data even for5903    // -fno-pic.5904    CmdArgs.push_back("-fno-direct-access-external-data");5905  }5906 5907  if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))5908    Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);5909 5910  // -fhosted is default.5911  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to5912  // use Freestanding.5913  bool Freestanding =5914      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||5915      KernelOrKext;5916  if (Freestanding)5917    CmdArgs.push_back("-ffreestanding");5918 5919  Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);5920 5921  auto SanitizeArgs = TC.getSanitizerArgs(Args);5922  Args.AddLastArg(CmdArgs,5923                  options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);5924 5925  // This is a coarse approximation of what llvm-gcc actually does, both5926  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more5927  // complicated ways.5928  bool IsAsyncUnwindTablesDefault =5929      TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;5930  bool IsSyncUnwindTablesDefault =5931      TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;5932 5933  bool AsyncUnwindTables = Args.hasFlag(5934      options::OPT_fasynchronous_unwind_tables,5935      options::OPT_fno_asynchronous_unwind_tables,5936      (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&5937          !Freestanding);5938  bool UnwindTables =5939      Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,5940                   IsSyncUnwindTablesDefault && !Freestanding);5941  if (AsyncUnwindTables)5942    CmdArgs.push_back("-funwind-tables=2");5943  else if (UnwindTables)5944     CmdArgs.push_back("-funwind-tables=1");5945 5946  // Prepare `-aux-target-cpu` and `-aux-target-feature` unless5947  // `--gpu-use-aux-triple-only` is specified.5948  if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&5949      (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {5950    const ArgList &HostArgs =5951        C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);5952    std::string HostCPU =5953        getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);5954    if (!HostCPU.empty()) {5955      CmdArgs.push_back("-aux-target-cpu");5956      CmdArgs.push_back(Args.MakeArgString(HostCPU));5957    }5958    getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,5959                      /*ForAS*/ false, /*IsAux*/ true);5960  }5961 5962  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());5963 5964  addMCModel(D, Args, Triple, RelocationModel, CmdArgs);5965 5966  if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {5967    StringRef Value = A->getValue();5968    unsigned TLSSize = 0;5969    Value.getAsInteger(10, TLSSize);5970    if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())5971      D.Diag(diag::err_drv_unsupported_opt_for_target)5972          << A->getOption().getName() << TripleStr;5973    if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)5974      D.Diag(diag::err_drv_invalid_int_value)5975          << A->getOption().getName() << Value;5976    Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);5977  }5978 5979  if (isTLSDESCEnabled(TC, Args))5980    CmdArgs.push_back("-enable-tlsdesc");5981 5982  // Add the target cpu5983  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);5984  if (!CPU.empty()) {5985    CmdArgs.push_back("-target-cpu");5986    CmdArgs.push_back(Args.MakeArgString(CPU));5987  }5988 5989  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);5990 5991  // Add clang-cl arguments.5992  types::ID InputType = Input.getType();5993  if (D.IsCLMode())5994    AddClangCLArgs(Args, InputType, CmdArgs);5995 5996  llvm::codegenoptions::DebugInfoKind DebugInfoKind =5997      llvm::codegenoptions::NoDebugInfo;5998  DwarfFissionKind DwarfFission = DwarfFissionKind::None;5999  renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,6000                     DebugInfoKind, DwarfFission);6001 6002  // Add the split debug info name to the command lines here so we6003  // can propagate it to the backend.6004  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&6005                    (TC.getTriple().isOSBinFormatELF() ||6006                     TC.getTriple().isOSBinFormatWasm() ||6007                     TC.getTriple().isOSBinFormatCOFF()) &&6008                    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||6009                     isa<BackendJobAction>(JA));6010  if (SplitDWARF) {6011    const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);6012    CmdArgs.push_back("-split-dwarf-file");6013    CmdArgs.push_back(SplitDWARFOut);6014    if (DwarfFission == DwarfFissionKind::Split) {6015      CmdArgs.push_back("-split-dwarf-output");6016      CmdArgs.push_back(SplitDWARFOut);6017    }6018  }6019 6020  // Pass the linker version in use.6021  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {6022    CmdArgs.push_back("-target-linker-version");6023    CmdArgs.push_back(A->getValue());6024  }6025 6026  // Explicitly error on some things we know we don't support and can't just6027  // ignore.6028  if (!Args.hasArg(options::OPT_fallow_unsupported)) {6029    Arg *Unsupported;6030    if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&6031        TC.getArch() == llvm::Triple::x86) {6032      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||6033          (Unsupported = Args.getLastArg(options::OPT_mkernel)))6034        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)6035            << Unsupported->getOption().getName();6036    }6037    // The faltivec option has been superseded by the maltivec option.6038    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))6039      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)6040          << Unsupported->getOption().getName()6041          << "please use -maltivec and include altivec.h explicitly";6042    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))6043      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)6044          << Unsupported->getOption().getName() << "please use -mno-altivec";6045  }6046 6047  Args.AddAllArgs(CmdArgs, options::OPT_v);6048 6049  if (Args.getLastArg(options::OPT_H)) {6050    CmdArgs.push_back("-H");6051    CmdArgs.push_back("-sys-header-deps");6052  }6053  Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);6054 6055  if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {6056    CmdArgs.push_back("-header-include-file");6057    CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()6058                          ? D.CCPrintHeadersFilename.c_str()6059                          : "-");6060    CmdArgs.push_back("-sys-header-deps");6061    CmdArgs.push_back(Args.MakeArgString(6062        "-header-include-format=" +6063        std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));6064    CmdArgs.push_back(6065        Args.MakeArgString("-header-include-filtering=" +6066                           std::string(headerIncludeFilteringKindToString(6067                               D.CCPrintHeadersFiltering))));6068  }6069  Args.AddLastArg(CmdArgs, options::OPT_P);6070  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);6071 6072  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {6073    CmdArgs.push_back("-diagnostic-log-file");6074    CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()6075                          ? D.CCLogDiagnosticsFilename.c_str()6076                          : "-");6077  }6078 6079  // Give the gen diagnostics more chances to succeed, by avoiding intentional6080  // crashes.6081  if (D.CCGenDiagnostics)6082    CmdArgs.push_back("-disable-pragma-debug-crash");6083 6084  // Allow backend to put its diagnostic files in the same place as frontend6085  // crash diagnostics files.6086  if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {6087    StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);6088    CmdArgs.push_back("-mllvm");6089    CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));6090  }6091 6092  bool UseSeparateSections = isUseSeparateSections(Triple);6093 6094  if (Args.hasFlag(options::OPT_ffunction_sections,6095                   options::OPT_fno_function_sections, UseSeparateSections)) {6096    CmdArgs.push_back("-ffunction-sections");6097  }6098 6099  if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,6100                               options::OPT_fno_basic_block_address_map)) {6101    if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {6102      if (A->getOption().matches(options::OPT_fbasic_block_address_map))6103        A->render(Args, CmdArgs);6104    } else {6105      D.Diag(diag::err_drv_unsupported_opt_for_target)6106          << A->getAsString(Args) << TripleStr;6107    }6108  }6109 6110  if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {6111    StringRef Val = A->getValue();6112    if (Val == "labels") {6113      D.Diag(diag::warn_drv_deprecated_arg)6114          << A->getAsString(Args) << /*hasReplacement=*/true6115          << "-fbasic-block-address-map";6116      CmdArgs.push_back("-fbasic-block-address-map");6117    } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {6118      if (Val != "all" && Val != "none" && !Val.starts_with("list="))6119        D.Diag(diag::err_drv_invalid_value)6120            << A->getAsString(Args) << A->getValue();6121      else6122        A->render(Args, CmdArgs);6123    } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {6124      // "all" is not supported on AArch64 since branch relaxation creates new6125      // basic blocks for some cross-section branches.6126      if (Val != "labels" && Val != "none" && !Val.starts_with("list="))6127        D.Diag(diag::err_drv_invalid_value)6128            << A->getAsString(Args) << A->getValue();6129      else6130        A->render(Args, CmdArgs);6131    } else if (Triple.isNVPTX()) {6132      // Do not pass the option to the GPU compilation. We still want it enabled6133      // for the host-side compilation, so seeing it here is not an error.6134    } else if (Val != "none") {6135      // =none is allowed everywhere. It's useful for overriding the option6136      // and is the same as not specifying the option.6137      D.Diag(diag::err_drv_unsupported_opt_for_target)6138          << A->getAsString(Args) << TripleStr;6139    }6140  }6141 6142  bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();6143  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,6144                   UseSeparateSections || HasDefaultDataSections)) {6145    CmdArgs.push_back("-fdata-sections");6146  }6147 6148  Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,6149                     options::OPT_fno_unique_section_names);6150  Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,6151                    options::OPT_fno_separate_named_sections);6152  Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,6153                    options::OPT_fno_unique_internal_linkage_names);6154  Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,6155                    options::OPT_fno_unique_basic_block_section_names);6156 6157  if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,6158                               options::OPT_fno_split_machine_functions)) {6159    if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {6160      // This codegen pass is only available on x86 and AArch64 ELF targets.6161      if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())6162        A->render(Args, CmdArgs);6163      else6164        D.Diag(diag::err_drv_unsupported_opt_for_target)6165            << A->getAsString(Args) << TripleStr;6166    }6167  }6168 6169  Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,6170                  options::OPT_finstrument_functions_after_inlining,6171                  options::OPT_finstrument_function_entry_bare);6172  Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,6173                  options::OPT_fno_convergent_functions);6174 6175  // NVPTX doesn't support PGO or coverage6176  if (!Triple.isNVPTX())6177    addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);6178 6179  Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);6180 6181  if (getLastProfileSampleUseArg(Args) &&6182      Args.hasFlag(options::OPT_fsample_profile_use_profi,6183                   options::OPT_fno_sample_profile_use_profi, true)) {6184    CmdArgs.push_back("-mllvm");6185    CmdArgs.push_back("-sample-profile-use-profi");6186  }6187 6188  // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.6189  if (RawTriple.isPS() &&6190      !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {6191    PScpu::addProfileRTArgs(TC, Args, CmdArgs);6192    PScpu::addSanitizerArgs(TC, Args, CmdArgs);6193  }6194 6195  // Pass options for controlling the default header search paths.6196  if (Args.hasArg(options::OPT_nostdinc)) {6197    CmdArgs.push_back("-nostdsysteminc");6198    CmdArgs.push_back("-nobuiltininc");6199  } else {6200    if (Args.hasArg(options::OPT_nostdlibinc))6201      CmdArgs.push_back("-nostdsysteminc");6202    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);6203    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);6204  }6205 6206  // Pass the path to compiler resource files.6207  CmdArgs.push_back("-resource-dir");6208  CmdArgs.push_back(D.ResourceDir.c_str());6209 6210  Args.AddLastArg(CmdArgs, options::OPT_working_directory);6211 6212  // Add preprocessing options like -I, -D, etc. if we are using the6213  // preprocessor.6214  //6215  // FIXME: Support -fpreprocessed6216  if (types::getPreprocessedType(InputType) != types::TY_INVALID)6217    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);6218 6219  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes6220  // that "The compiler can only warn and ignore the option if not recognized".6221  // When building with ccache, it will pass -D options to clang even on6222  // preprocessed inputs and configure concludes that -fPIC is not supported.6223  Args.ClaimAllArgs(options::OPT_D);6224 6225  // Warn about ignored options to clang.6226  for (const Arg *A :6227       Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {6228    D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);6229    A->claim();6230  }6231 6232  for (const Arg *A :6233       Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {6234    D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);6235    A->claim();6236  }6237 6238  claimNoWarnArgs(Args);6239 6240  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);6241 6242  for (const Arg *A :6243       Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {6244    A->claim();6245    if (A->getOption().getID() == options::OPT__SLASH_wd) {6246      unsigned WarningNumber;6247      if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {6248        D.Diag(diag::err_drv_invalid_int_value)6249            << A->getAsString(Args) << A->getValue();6250        continue;6251      }6252 6253      if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {6254        CmdArgs.push_back(Args.MakeArgString(6255            "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));6256      }6257      continue;6258    }6259    A->render(Args, CmdArgs);6260  }6261 6262  Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);6263 6264  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))6265    CmdArgs.push_back("-pedantic");6266  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);6267  Args.AddLastArg(CmdArgs, options::OPT_w);6268 6269  Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,6270                    options::OPT_fno_fixed_point);6271 6272  if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))6273    A->render(Args, CmdArgs);6274 6275  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,6276                  options::OPT_fno_experimental_relative_cxx_abi_vtables);6277 6278  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,6279                  options::OPT_fno_experimental_omit_vtable_rtti);6280 6281  if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))6282    A->render(Args, CmdArgs);6283 6284  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}6285  // (-ansi is equivalent to -std=c89 or -std=c++98).6286  //6287  // If a std is supplied, only add -trigraphs if it follows the6288  // option.6289  bool ImplyVCPPCVer = false;6290  bool ImplyVCPPCXXVer = false;6291  const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);6292  if (Std) {6293    if (Std->getOption().matches(options::OPT_ansi))6294      if (types::isCXX(InputType))6295        CmdArgs.push_back("-std=c++98");6296      else6297        CmdArgs.push_back("-std=c89");6298    else6299      Std->render(Args, CmdArgs);6300 6301    // If -f(no-)trigraphs appears after the language standard flag, honor it.6302    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,6303                                 options::OPT_ftrigraphs,6304                                 options::OPT_fno_trigraphs))6305      if (A != Std)6306        A->render(Args, CmdArgs);6307  } else {6308    // Honor -std-default.6309    //6310    // FIXME: Clang doesn't correctly handle -std= when the input language6311    // doesn't match. For the time being just ignore this for C++ inputs;6312    // eventually we want to do all the standard defaulting here instead of6313    // splitting it between the driver and clang -cc1.6314    if (!types::isCXX(InputType)) {6315      if (!Args.hasArg(options::OPT__SLASH_std)) {6316        Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",6317                                  /*Joined=*/true);6318      } else6319        ImplyVCPPCVer = true;6320    }6321    else if (IsWindowsMSVC)6322      ImplyVCPPCXXVer = true;6323 6324    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,6325                    options::OPT_fno_trigraphs);6326  }6327 6328  // GCC's behavior for -Wwrite-strings is a bit strange:6329  //  * In C, this "warning flag" changes the types of string literals from6330  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning6331  //    for the discarded qualifier.6332  //  * In C++, this is just a normal warning flag.6333  //6334  // Implementing this warning correctly in C is hard, so we follow GCC's6335  // behavior for now. FIXME: Directly diagnose uses of a string literal as6336  // a non-const char* in C, rather than using this crude hack.6337  if (!types::isCXX(InputType)) {6338    // FIXME: This should behave just like a warning flag, and thus should also6339    // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.6340    Arg *WriteStrings =6341        Args.getLastArg(options::OPT_Wwrite_strings,6342                        options::OPT_Wno_write_strings, options::OPT_w);6343    if (WriteStrings &&6344        WriteStrings->getOption().matches(options::OPT_Wwrite_strings))6345      CmdArgs.push_back("-fconst-strings");6346  }6347 6348  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active6349  // during C++ compilation, which it is by default. GCC keeps this define even6350  // in the presence of '-w', match this behavior bug-for-bug.6351  if (types::isCXX(InputType) &&6352      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,6353                   true)) {6354    CmdArgs.push_back("-fdeprecated-macro");6355  }6356 6357  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.6358  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {6359    if (Asm->getOption().matches(options::OPT_fasm))6360      CmdArgs.push_back("-fgnu-keywords");6361    else6362      CmdArgs.push_back("-fno-gnu-keywords");6363  }6364 6365  if (!ShouldEnableAutolink(Args, TC, JA))6366    CmdArgs.push_back("-fno-autolink");6367 6368  Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);6369  Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);6370  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);6371  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);6372 6373  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);6374 6375  if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))6376    CmdArgs.push_back("-fexperimental-new-constant-interpreter");6377 6378  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {6379    CmdArgs.push_back("-fbracket-depth");6380    CmdArgs.push_back(A->getValue());6381  }6382 6383  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,6384                               options::OPT_Wlarge_by_value_copy_def)) {6385    if (A->getNumValues()) {6386      StringRef bytes = A->getValue();6387      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));6388    } else6389      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value6390  }6391 6392  if (Args.hasArg(options::OPT_relocatable_pch))6393    CmdArgs.push_back("-relocatable-pch");6394 6395  if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {6396    static const char *kCFABIs[] = {6397      "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",6398    };6399 6400    if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))6401      D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();6402    else6403      A->render(Args, CmdArgs);6404  }6405 6406  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {6407    CmdArgs.push_back("-fconstant-string-class");6408    CmdArgs.push_back(A->getValue());6409  }6410 6411  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {6412    CmdArgs.push_back("-ftabstop");6413    CmdArgs.push_back(A->getValue());6414  }6415 6416  if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,6417                   options::OPT_fno_experimental_call_graph_section, false))6418    CmdArgs.push_back("-fexperimental-call-graph-section");6419 6420  Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,6421                    options::OPT_fno_stack_size_section);6422 6423  if (Args.hasArg(options::OPT_fstack_usage)) {6424    CmdArgs.push_back("-stack-usage-file");6425 6426    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {6427      SmallString<128> OutputFilename(OutputOpt->getValue());6428      llvm::sys::path::replace_extension(OutputFilename, "su");6429      CmdArgs.push_back(Args.MakeArgString(OutputFilename));6430    } else6431      CmdArgs.push_back(6432          Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));6433  }6434 6435  CmdArgs.push_back("-ferror-limit");6436  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))6437    CmdArgs.push_back(A->getValue());6438  else6439    CmdArgs.push_back("19");6440 6441  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);6442  Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);6443  Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);6444  Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);6445  Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);6446 6447  // Pass -fmessage-length=.6448  unsigned MessageLength = 0;6449  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {6450    StringRef V(A->getValue());6451    if (V.getAsInteger(0, MessageLength))6452      D.Diag(diag::err_drv_invalid_argument_to_option)6453          << V << A->getOption().getName();6454  } else {6455    // If -fmessage-length=N was not specified, determine whether this is a6456    // terminal and, if so, implicitly define -fmessage-length appropriately.6457    MessageLength = llvm::sys::Process::StandardErrColumns();6458  }6459  if (MessageLength != 0)6460    CmdArgs.push_back(6461        Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));6462 6463  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))6464    CmdArgs.push_back(6465        Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));6466 6467  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))6468    CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +6469                                         Twine(A->getValue(0))));6470 6471  // -fvisibility= and -fvisibility-ms-compat are of a piece.6472  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,6473                                     options::OPT_fvisibility_ms_compat)) {6474    if (A->getOption().matches(options::OPT_fvisibility_EQ)) {6475      A->render(Args, CmdArgs);6476    } else {6477      assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));6478      CmdArgs.push_back("-fvisibility=hidden");6479      CmdArgs.push_back("-ftype-visibility=default");6480    }6481  } else if (IsOpenMPDevice) {6482    // When compiling for the OpenMP device we want protected visibility by6483    // default. This prevents the device from accidentally preempting code on6484    // the host, makes the system more robust, and improves performance.6485    CmdArgs.push_back("-fvisibility=protected");6486  }6487 6488  // PS4/PS5 process these options in addClangTargetOptions.6489  if (!RawTriple.isPS()) {6490    if (const Arg *A =6491            Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,6492                            options::OPT_fno_visibility_from_dllstorageclass)) {6493      if (A->getOption().matches(6494              options::OPT_fvisibility_from_dllstorageclass)) {6495        CmdArgs.push_back("-fvisibility-from-dllstorageclass");6496        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);6497        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);6498        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);6499        Args.AddLastArg(CmdArgs,6500                        options::OPT_fvisibility_externs_nodllstorageclass_EQ);6501      }6502    }6503  }6504 6505  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,6506                    options::OPT_fno_visibility_inlines_hidden, false))6507    CmdArgs.push_back("-fvisibility-inlines-hidden");6508 6509  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,6510                           options::OPT_fno_visibility_inlines_hidden_static_local_var);6511 6512  // -fvisibility-global-new-delete-hidden is a deprecated spelling of6513  // -fvisibility-global-new-delete=force-hidden.6514  if (const Arg *A =6515          Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {6516    D.Diag(diag::warn_drv_deprecated_arg)6517        << A->getAsString(Args) << /*hasReplacement=*/true6518        << "-fvisibility-global-new-delete=force-hidden";6519  }6520 6521  if (const Arg *A =6522          Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,6523                          options::OPT_fvisibility_global_new_delete_hidden)) {6524    if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {6525      A->render(Args, CmdArgs);6526    } else {6527      assert(A->getOption().matches(6528          options::OPT_fvisibility_global_new_delete_hidden));6529      CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");6530    }6531  }6532 6533  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);6534 6535  if (Args.hasFlag(options::OPT_fnew_infallible,6536                   options::OPT_fno_new_infallible, false))6537    CmdArgs.push_back("-fnew-infallible");6538 6539  if (Args.hasFlag(options::OPT_fno_operator_names,6540                   options::OPT_foperator_names, false))6541    CmdArgs.push_back("-fno-operator-names");6542 6543  // Forward -f (flag) options which we can pass directly.6544  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);6545  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);6546  Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);6547  Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);6548  Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,6549                  options::OPT_fno_raw_string_literals);6550 6551  if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,6552                   Triple.hasDefaultEmulatedTLS()))6553    CmdArgs.push_back("-femulated-tls");6554 6555  Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,6556                    options::OPT_fno_check_new);6557 6558  if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {6559    // FIXME: There's no reason for this to be restricted to X86. The backend6560    // code needs to be changed to include the appropriate function calls6561    // automatically.6562    if (!Triple.isX86() && !Triple.isAArch64())6563      D.Diag(diag::err_drv_unsupported_opt_for_target)6564          << A->getAsString(Args) << TripleStr;6565  }6566 6567  // AltiVec-like language extensions aren't relevant for assembling.6568  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)6569    Args.AddLastArg(CmdArgs, options::OPT_fzvector);6570 6571  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);6572  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);6573 6574  // Forward flags for OpenMP. We don't do this if the current action is an6575  // device offloading action other than OpenMP.6576  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,6577                   options::OPT_fno_openmp, false) &&6578      !Args.hasFlag(options::OPT_foffload_via_llvm,6579                    options::OPT_fno_offload_via_llvm, false) &&6580      (JA.isDeviceOffloading(Action::OFK_None) ||6581       JA.isDeviceOffloading(Action::OFK_OpenMP))) {6582    switch (D.getOpenMPRuntime(Args)) {6583    case Driver::OMPRT_OMP:6584    case Driver::OMPRT_IOMP5:6585      // Clang can generate useful OpenMP code for these two runtime libraries.6586      CmdArgs.push_back("-fopenmp");6587 6588      // If no option regarding the use of TLS in OpenMP codegeneration is6589      // given, decide a default based on the target. Otherwise rely on the6590      // options and pass the right information to the frontend.6591      if (!Args.hasFlag(options::OPT_fopenmp_use_tls,6592                        options::OPT_fnoopenmp_use_tls, /*Default=*/true))6593        CmdArgs.push_back("-fnoopenmp-use-tls");6594      Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,6595                      options::OPT_fno_openmp_simd);6596      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);6597      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);6598      if (!Args.hasFlag(options::OPT_fopenmp_extensions,6599                        options::OPT_fno_openmp_extensions, /*Default=*/true))6600        CmdArgs.push_back("-fno-openmp-extensions");6601      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);6602      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);6603      Args.AddAllArgs(CmdArgs,6604                      options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);6605      if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,6606                       options::OPT_fno_openmp_optimistic_collapse,6607                       /*Default=*/false))6608        CmdArgs.push_back("-fopenmp-optimistic-collapse");6609 6610      // When in OpenMP offloading mode with NVPTX target, forward6611      // cuda-mode flag6612      if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,6613                       options::OPT_fno_openmp_cuda_mode, /*Default=*/false))6614        CmdArgs.push_back("-fopenmp-cuda-mode");6615 6616      // When in OpenMP offloading mode, enable debugging on the device.6617      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);6618      if (Args.hasFlag(options::OPT_fopenmp_target_debug,6619                       options::OPT_fno_openmp_target_debug, /*Default=*/false))6620        CmdArgs.push_back("-fopenmp-target-debug");6621 6622      // When in OpenMP offloading mode, forward assumptions information about6623      // thread and team counts in the device.6624      if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,6625                       options::OPT_fno_openmp_assume_teams_oversubscription,6626                       /*Default=*/false))6627        CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");6628      if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,6629                       options::OPT_fno_openmp_assume_threads_oversubscription,6630                       /*Default=*/false))6631        CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");6632      if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))6633        CmdArgs.push_back("-fopenmp-assume-no-thread-state");6634      if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))6635        CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");6636      if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))6637        CmdArgs.push_back("-fopenmp-offload-mandatory");6638      if (Args.hasArg(options::OPT_fopenmp_force_usm))6639        CmdArgs.push_back("-fopenmp-force-usm");6640      break;6641    default:6642      // By default, if Clang doesn't know how to generate useful OpenMP code6643      // for a specific runtime library, we just don't pass the '-fopenmp' flag6644      // down to the actual compilation.6645      // FIXME: It would be better to have a mode which *only* omits IR6646      // generation based on the OpenMP support so that we get consistent6647      // semantic analysis, etc.6648      break;6649    }6650  } else {6651    Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,6652                    options::OPT_fno_openmp_simd);6653    Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);6654    Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,6655                       options::OPT_fno_openmp_extensions);6656  }6657  // Forward the offload runtime change to code generation, liboffload implies6658  // new driver. Otherwise, check if we should forward the new driver to change6659  // offloading code generation.6660  if (Args.hasFlag(options::OPT_foffload_via_llvm,6661                   options::OPT_fno_offload_via_llvm, false)) {6662    CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});6663  } else if (Args.hasFlag(options::OPT_offload_new_driver,6664                          options::OPT_no_offload_new_driver,6665                          C.isOffloadingHostKind(Action::OFK_Cuda))) {6666    CmdArgs.push_back("--offload-new-driver");6667  }6668 6669  const XRayArgs &XRay = TC.getXRayArgs(Args);6670  XRay.addArgs(TC, Args, CmdArgs, InputType);6671 6672  for (const auto &Filename :6673       Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {6674    if (D.getVFS().exists(Filename))6675      CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));6676    else6677      D.Diag(clang::diag::err_drv_no_such_file) << Filename;6678  }6679 6680  if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {6681    StringRef S0 = A->getValue(), S = S0;6682    unsigned Size, Offset = 0;6683    if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&6684        !Triple.isX86() &&6685        !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||6686                                Triple.getArch() == llvm::Triple::ppc64 ||6687                                Triple.getArch() == llvm::Triple::ppc64le)))6688      D.Diag(diag::err_drv_unsupported_opt_for_target)6689          << A->getAsString(Args) << TripleStr;6690    else if (S.consumeInteger(10, Size) ||6691             (!S.empty() &&6692              (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||6693             (!S.empty() && (!S.consume_front(",") || S.empty())))6694      D.Diag(diag::err_drv_invalid_argument_to_option)6695          << S0 << A->getOption().getName();6696    else if (Size < Offset)6697      D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);6698    else {6699      CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));6700      CmdArgs.push_back(Args.MakeArgString(6701          "-fpatchable-function-entry-offset=" + Twine(Offset)));6702      if (!S.empty())6703        CmdArgs.push_back(6704            Args.MakeArgString("-fpatchable-function-entry-section=" + S));6705    }6706  }6707 6708  Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);6709 6710  if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))6711    Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);6712 6713  for (const auto &A :6714       Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))6715    CmdArgs.push_back(6716        Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));6717 6718  if (TC.SupportsProfiling()) {6719    Args.AddLastArg(CmdArgs, options::OPT_pg);6720 6721    llvm::Triple::ArchType Arch = TC.getArch();6722    if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {6723      if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())6724        A->render(Args, CmdArgs);6725      else6726        D.Diag(diag::err_drv_unsupported_opt_for_target)6727            << A->getAsString(Args) << TripleStr;6728    }6729    if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {6730      if (Arch == llvm::Triple::systemz)6731        A->render(Args, CmdArgs);6732      else6733        D.Diag(diag::err_drv_unsupported_opt_for_target)6734            << A->getAsString(Args) << TripleStr;6735    }6736    if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {6737      if (Arch == llvm::Triple::systemz)6738        A->render(Args, CmdArgs);6739      else6740        D.Diag(diag::err_drv_unsupported_opt_for_target)6741            << A->getAsString(Args) << TripleStr;6742    }6743  }6744 6745  if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {6746    if (TC.getTriple().isOSzOS()) {6747      D.Diag(diag::err_drv_unsupported_opt_for_target)6748          << A->getAsString(Args) << TripleStr;6749    }6750  }6751  if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {6752    if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {6753      D.Diag(diag::err_drv_unsupported_opt_for_target)6754          << A->getAsString(Args) << TripleStr;6755    }6756  }6757  if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {6758    if (A->getOption().matches(options::OPT_p)) {6759      A->claim();6760      if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))6761        CmdArgs.push_back("-pg");6762    }6763  }6764 6765  // Reject AIX-specific link options on other targets.6766  if (!TC.getTriple().isOSAIX()) {6767    for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,6768                                      options::OPT_mxcoff_build_id_EQ)) {6769      D.Diag(diag::err_drv_unsupported_opt_for_target)6770          << A->getSpelling() << TripleStr;6771    }6772  }6773 6774  if (Args.getLastArg(options::OPT_fapple_kext) ||6775      (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))6776    CmdArgs.push_back("-fapple-kext");6777 6778  Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);6779  Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);6780  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);6781  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);6782  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);6783  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);6784  Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);6785  Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);6786  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);6787  Args.AddLastArg(CmdArgs, options::OPT_malign_double);6788  Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);6789 6790  if (const char *Name = C.getTimeTraceFile(&JA)) {6791    CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));6792    Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);6793    Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);6794  }6795 6796  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {6797    CmdArgs.push_back("-ftrapv-handler");6798    CmdArgs.push_back(A->getValue());6799  }6800 6801  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);6802 6803  // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both6804  // clang and flang.6805  renderCommonIntegerOverflowOptions(Args, CmdArgs);6806 6807  Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,6808                  options::OPT_fno_finite_loops);6809 6810  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);6811  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,6812                  options::OPT_fno_unroll_loops);6813  Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,6814                  options::OPT_fno_loop_interchange);6815  Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,6816                    options::OPT_fno_experimental_loop_fusion);6817 6818  Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);6819 6820  Args.AddLastArg(CmdArgs, options::OPT_pthread);6821 6822  Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,6823                    options::OPT_mno_speculative_load_hardening);6824 6825  RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);6826  RenderSCPOptions(TC, Args, CmdArgs);6827  RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);6828 6829  Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);6830 6831  Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,6832                    options::OPT_mno_stackrealign);6833 6834  if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {6835    StringRef Value = A->getValue();6836    int64_t Alignment = 0;6837    if (Value.getAsInteger(10, Alignment) || Alignment < 0)6838      D.Diag(diag::err_drv_invalid_argument_to_option)6839          << Value << A->getOption().getName();6840    else if (Alignment & (Alignment - 1))6841      D.Diag(diag::err_drv_alignment_not_power_of_two)6842          << A->getAsString(Args) << Value;6843    else6844      CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));6845  }6846 6847  if (Args.hasArg(options::OPT_mstack_probe_size)) {6848    StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);6849 6850    if (!Size.empty())6851      CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));6852    else6853      CmdArgs.push_back("-mstack-probe-size=0");6854  }6855 6856  Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,6857                     options::OPT_mno_stack_arg_probe);6858 6859  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,6860                               options::OPT_mno_restrict_it)) {6861    if (A->getOption().matches(options::OPT_mrestrict_it)) {6862      CmdArgs.push_back("-mllvm");6863      CmdArgs.push_back("-arm-restrict-it");6864    } else {6865      CmdArgs.push_back("-mllvm");6866      CmdArgs.push_back("-arm-default-it");6867    }6868  }6869 6870  // Forward -cl options to -cc16871  RenderOpenCLOptions(Args, CmdArgs, InputType);6872 6873  // Forward hlsl options to -cc16874  RenderHLSLOptions(Args, CmdArgs, InputType);6875 6876  // Forward OpenACC options to -cc16877  RenderOpenACCOptions(D, Args, CmdArgs, InputType);6878 6879  if (IsHIP) {6880    if (Args.hasFlag(options::OPT_fhip_new_launch_api,6881                     options::OPT_fno_hip_new_launch_api, true))6882      CmdArgs.push_back("-fhip-new-launch-api");6883    Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,6884                      options::OPT_fno_gpu_allow_device_init);6885    Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);6886    Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);6887    Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,6888                      options::OPT_fno_hip_kernel_arg_name);6889  }6890 6891  if (IsCuda || IsHIP) {6892    if (IsRDCMode)6893      CmdArgs.push_back("-fgpu-rdc");6894    Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,6895                      options::OPT_fno_gpu_defer_diag);6896    if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,6897                     options::OPT_fno_gpu_exclude_wrong_side_overloads,6898                     false)) {6899      CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");6900      CmdArgs.push_back("-fgpu-defer-diag");6901    }6902  }6903 6904  // Forward --no-offloadlib to -cc1.6905  if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))6906    CmdArgs.push_back("--no-offloadlib");6907 6908  if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {6909    CmdArgs.push_back(6910        Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));6911 6912    if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))6913      CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +6914                                           SA->getValue()));6915  } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {6916    // Emit IBT endbr64 instructions by default6917    CmdArgs.push_back("-fcf-protection=branch");6918    // jump-table can generate indirect jumps, which are not permitted6919    CmdArgs.push_back("-fno-jump-tables");6920  }6921 6922  if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))6923    CmdArgs.push_back(6924        Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));6925 6926  Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);6927 6928  // Forward -f options with positive and negative forms; we translate these by6929  // hand.  Do not propagate PGO options to the GPU-side compilations as the6930  // profile info is for the host-side compilation only.6931  if (!(IsCudaDevice || IsHIPDevice)) {6932    if (Arg *A = getLastProfileSampleUseArg(Args)) {6933      auto *PGOArg = Args.getLastArg(6934          options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,6935          options::OPT_fcs_profile_generate,6936          options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,6937          options::OPT_fprofile_use_EQ);6938      if (PGOArg)6939        D.Diag(diag::err_drv_argument_not_allowed_with)6940            << "SampleUse with PGO options";6941 6942      StringRef fname = A->getValue();6943      if (!llvm::sys::fs::exists(fname))6944        D.Diag(diag::err_drv_no_such_file) << fname;6945      else6946        A->render(Args, CmdArgs);6947    }6948    Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);6949 6950    if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,6951                     options::OPT_fno_pseudo_probe_for_profiling, false)) {6952      CmdArgs.push_back("-fpseudo-probe-for-profiling");6953      // Enforce -funique-internal-linkage-names if it's not explicitly turned6954      // off.6955      if (Args.hasFlag(options::OPT_funique_internal_linkage_names,6956                       options::OPT_fno_unique_internal_linkage_names, true))6957        CmdArgs.push_back("-funique-internal-linkage-names");6958    }6959  }6960  RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);6961 6962  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,6963                     options::OPT_fno_assume_sane_operator_new);6964 6965  if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))6966    CmdArgs.push_back("-fapinotes");6967  if (Args.hasFlag(options::OPT_fapinotes_modules,6968                   options::OPT_fno_apinotes_modules, false))6969    CmdArgs.push_back("-fapinotes-modules");6970  Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);6971 6972  if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,6973                   options::OPT_fno_swift_version_independent_apinotes, false))6974    CmdArgs.push_back("-fswift-version-independent-apinotes");6975 6976  // -fblocks=0 is default.6977  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,6978                   TC.IsBlocksDefault()) ||6979      (Args.hasArg(options::OPT_fgnu_runtime) &&6980       Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&6981       !Args.hasArg(options::OPT_fno_blocks))) {6982    CmdArgs.push_back("-fblocks");6983 6984    if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())6985      CmdArgs.push_back("-fblocks-runtime-optional");6986  }6987 6988  // -fencode-extended-block-signature=1 is default.6989  if (TC.IsEncodeExtendedBlockSignatureDefault())6990    CmdArgs.push_back("-fencode-extended-block-signature");6991 6992  if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,6993                   options::OPT_fno_coro_aligned_allocation, false) &&6994      types::isCXX(InputType))6995    CmdArgs.push_back("-fcoro-aligned-allocation");6996 6997  Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,6998                  options::OPT_fno_double_square_bracket_attributes);6999 7000  Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,7001                     options::OPT_fno_access_control);7002  Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,7003                     options::OPT_fno_elide_constructors);7004 7005  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();7006 7007  if (KernelOrKext || (types::isCXX(InputType) &&7008                       (RTTIMode == ToolChain::RM_Disabled)))7009    CmdArgs.push_back("-fno-rtti");7010 7011  // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.7012  if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,7013                   TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))7014    CmdArgs.push_back("-fshort-enums");7015 7016  RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);7017 7018  // -fuse-cxa-atexit is default.7019  if (!Args.hasFlag(7020          options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,7021          !RawTriple.isOSAIX() &&7022              (!RawTriple.isOSWindows() ||7023               RawTriple.isWindowsCygwinEnvironment()) &&7024              ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||7025               RawTriple.hasEnvironment())) ||7026      KernelOrKext)7027    CmdArgs.push_back("-fno-use-cxa-atexit");7028 7029  if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,7030                   options::OPT_fno_register_global_dtors_with_atexit,7031                   RawTriple.isOSDarwin() && !KernelOrKext))7032    CmdArgs.push_back("-fregister-global-dtors-with-atexit");7033 7034  Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,7035                    options::OPT_fno_use_line_directives);7036 7037  // -fno-minimize-whitespace is default.7038  if (Args.hasFlag(options::OPT_fminimize_whitespace,7039                   options::OPT_fno_minimize_whitespace, false)) {7040    types::ID InputType = Inputs[0].getType();7041    if (!isDerivedFromC(InputType))7042      D.Diag(diag::err_drv_opt_unsupported_input_type)7043          << "-fminimize-whitespace" << types::getTypeName(InputType);7044    CmdArgs.push_back("-fminimize-whitespace");7045  }7046 7047  // -fno-keep-system-includes is default.7048  if (Args.hasFlag(options::OPT_fkeep_system_includes,7049                   options::OPT_fno_keep_system_includes, false)) {7050    types::ID InputType = Inputs[0].getType();7051    if (!isDerivedFromC(InputType))7052      D.Diag(diag::err_drv_opt_unsupported_input_type)7053          << "-fkeep-system-includes" << types::getTypeName(InputType);7054    CmdArgs.push_back("-fkeep-system-includes");7055  }7056 7057  // -fms-extensions=0 is default.7058  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,7059                   IsWindowsMSVC || IsUEFI))7060    CmdArgs.push_back("-fms-extensions");7061 7062  // -fms-compatibility=0 is default.7063  bool IsMSVCCompat = Args.hasFlag(7064      options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,7065      (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,7066                                     options::OPT_fno_ms_extensions, true)));7067  if (IsMSVCCompat) {7068    CmdArgs.push_back("-fms-compatibility");7069    if (!types::isCXX(Input.getType()) &&7070        Args.hasArg(options::OPT_fms_define_stdc))7071      CmdArgs.push_back("-fms-define-stdc");7072  }7073 7074  if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&7075      Args.hasArg(options::OPT_fms_runtime_lib_EQ))7076    ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);7077 7078  // Handle -fgcc-version, if present.7079  VersionTuple GNUCVer;7080  if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {7081    // Check that the version has 1 to 3 components and the minor and patch7082    // versions fit in two decimal digits.7083    StringRef Val = A->getValue();7084    Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.7085    bool Invalid = GNUCVer.tryParse(Val);7086    unsigned Minor = GNUCVer.getMinor().value_or(0);7087    unsigned Patch = GNUCVer.getSubminor().value_or(0);7088    if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {7089      D.Diag(diag::err_drv_invalid_value)7090          << A->getAsString(Args) << A->getValue();7091    }7092  } else if (!IsMSVCCompat) {7093    // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.7094    GNUCVer = VersionTuple(4, 2, 1);7095  }7096  if (!GNUCVer.empty()) {7097    CmdArgs.push_back(7098        Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));7099  }7100 7101  VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);7102  if (!MSVT.empty())7103    CmdArgs.push_back(7104        Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));7105 7106  bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;7107  if (ImplyVCPPCVer) {7108    StringRef LanguageStandard;7109    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {7110      Std = StdArg;7111      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())7112                             .Case("c11", "-std=c11")7113                             .Case("c17", "-std=c17")7114                             // TODO: add c23 when MSVC supports it.7115                             .Case("clatest", "-std=c23")7116                             .Default("");7117      if (LanguageStandard.empty())7118        D.Diag(clang::diag::warn_drv_unused_argument)7119            << StdArg->getAsString(Args);7120    }7121    CmdArgs.push_back(LanguageStandard.data());7122  }7123  if (ImplyVCPPCXXVer) {7124    StringRef LanguageStandard;7125    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {7126      Std = StdArg;7127      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())7128                             .Case("c++14", "-std=c++14")7129                             .Case("c++17", "-std=c++17")7130                             .Case("c++20", "-std=c++20")7131                             // TODO add c++23 and c++26 when MSVC supports it.7132                             .Case("c++23preview", "-std=c++23")7133                             .Case("c++latest", "-std=c++26")7134                             .Default("");7135      if (LanguageStandard.empty())7136        D.Diag(clang::diag::warn_drv_unused_argument)7137            << StdArg->getAsString(Args);7138    }7139 7140    if (LanguageStandard.empty()) {7141      if (IsMSVC2015Compatible)7142        LanguageStandard = "-std=c++14";7143      else7144        LanguageStandard = "-std=c++11";7145    }7146 7147    CmdArgs.push_back(LanguageStandard.data());7148  }7149 7150  Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,7151                    options::OPT_fno_borland_extensions);7152 7153  // -fno-declspec is default, except for PS4/PS5.7154  if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,7155                   RawTriple.isPS()))7156    CmdArgs.push_back("-fdeclspec");7157  else if (Args.hasArg(options::OPT_fno_declspec))7158    CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.7159 7160  // -fthreadsafe-static is default, except for MSVC compatibility versions less7161  // than 19.7162  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,7163                    options::OPT_fno_threadsafe_statics,7164                    !types::isOpenCL(InputType) &&7165                        (!IsWindowsMSVC || IsMSVC2015Compatible)))7166    CmdArgs.push_back("-fno-threadsafe-statics");7167 7168  if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,7169                    true))7170    CmdArgs.push_back("-fno-ms-tls-guards");7171 7172  // Add -fno-assumptions, if it was specified.7173  if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,7174                    true))7175    CmdArgs.push_back("-fno-assumptions");7176 7177  // -fgnu-keywords default varies depending on language; only pass if7178  // specified.7179  Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,7180                  options::OPT_fno_gnu_keywords);7181 7182  Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,7183                    options::OPT_fno_gnu89_inline);7184 7185  const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,7186                                         options::OPT_finline_hint_functions,7187                                         options::OPT_fno_inline_functions);7188  if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {7189    if (A->getOption().matches(options::OPT_fno_inline))7190      A->render(Args, CmdArgs);7191  } else if (InlineArg) {7192    InlineArg->render(Args, CmdArgs);7193  }7194 7195  Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);7196 7197  // FIXME: Find a better way to determine whether we are in C++20.7198  bool HaveCxx20 =7199      Std &&7200      (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||7201       Std->containsValue("c++20") || Std->containsValue("gnu++20") ||7202       Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||7203       Std->containsValue("c++23") || Std->containsValue("gnu++23") ||7204       Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||7205       Std->containsValue("c++26") || Std->containsValue("gnu++26") ||7206       Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));7207  bool HaveModules =7208      RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);7209 7210  // -fdelayed-template-parsing is default when targeting MSVC.7211  // Many old Windows SDK versions require this to parse.7212  //7213  // According to7214  // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,7215  // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-7216  // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to7217  // not enable -fdelayed-template-parsing by default after C++20.7218  //7219  // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be7220  // able to disable this by default at some point.7221  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,7222                   options::OPT_fno_delayed_template_parsing,7223                   IsWindowsMSVC && !HaveCxx20)) {7224    if (HaveCxx20)7225      D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);7226 7227    CmdArgs.push_back("-fdelayed-template-parsing");7228  }7229 7230  if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,7231                   options::OPT_fno_pch_validate_input_files_content, false))7232    CmdArgs.push_back("-fvalidate-ast-input-files-content");7233  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,7234                   options::OPT_fno_pch_instantiate_templates, false))7235    CmdArgs.push_back("-fpch-instantiate-templates");7236  if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,7237                   false))7238    CmdArgs.push_back("-fmodules-codegen");7239  if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,7240                   false))7241    CmdArgs.push_back("-fmodules-debuginfo");7242 7243  ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);7244  RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,7245                    Input, CmdArgs);7246 7247  if (types::isObjC(Input.getType()) &&7248      Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,7249                   options::OPT_fno_objc_encode_cxx_class_template_spec,7250                   !Runtime.isNeXTFamily()))7251    CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");7252 7253  if (Args.hasFlag(options::OPT_fapplication_extension,7254                   options::OPT_fno_application_extension, false))7255    CmdArgs.push_back("-fapplication-extension");7256 7257  // Handle GCC-style exception args.7258  bool EH = false;7259  if (!C.getDriver().IsCLMode())7260    EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);7261 7262  // Handle exception personalities7263  Arg *A = Args.getLastArg(7264      options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,7265      options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);7266  if (A) {7267    const Option &Opt = A->getOption();7268    if (Opt.matches(options::OPT_fsjlj_exceptions))7269      CmdArgs.push_back("-exception-model=sjlj");7270    if (Opt.matches(options::OPT_fseh_exceptions))7271      CmdArgs.push_back("-exception-model=seh");7272    if (Opt.matches(options::OPT_fdwarf_exceptions))7273      CmdArgs.push_back("-exception-model=dwarf");7274    if (Opt.matches(options::OPT_fwasm_exceptions))7275      CmdArgs.push_back("-exception-model=wasm");7276  } else {7277    switch (TC.GetExceptionModel(Args)) {7278    default:7279      break;7280    case llvm::ExceptionHandling::DwarfCFI:7281      CmdArgs.push_back("-exception-model=dwarf");7282      break;7283    case llvm::ExceptionHandling::SjLj:7284      CmdArgs.push_back("-exception-model=sjlj");7285      break;7286    case llvm::ExceptionHandling::WinEH:7287      CmdArgs.push_back("-exception-model=seh");7288      break;7289    }7290  }7291 7292  // Unwind v2 (epilog) information for x64 Windows.7293  Args.AddLastArg(CmdArgs, options::OPT_winx64_eh_unwindv2);7294 7295  // C++ "sane" operator new.7296  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,7297                     options::OPT_fno_assume_sane_operator_new);7298 7299  // -fassume-unique-vtables is on by default.7300  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,7301                     options::OPT_fno_assume_unique_vtables);7302 7303  // -fsized-deallocation is on by default in C++14 onwards and otherwise off7304  // by default.7305  Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,7306                  options::OPT_fno_sized_deallocation);7307 7308  // -faligned-allocation is on by default in C++17 onwards and otherwise off7309  // by default.7310  if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,7311                               options::OPT_fno_aligned_allocation,7312                               options::OPT_faligned_new_EQ)) {7313    if (A->getOption().matches(options::OPT_fno_aligned_allocation))7314      CmdArgs.push_back("-fno-aligned-allocation");7315    else7316      CmdArgs.push_back("-faligned-allocation");7317  }7318 7319  // The default new alignment can be specified using a dedicated option or via7320  // a GCC-compatible option that also turns on aligned allocation.7321  if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,7322                               options::OPT_faligned_new_EQ))7323    CmdArgs.push_back(7324        Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));7325 7326  // -fconstant-cfstrings is default, and may be subject to argument translation7327  // on Darwin.7328  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,7329                    options::OPT_fno_constant_cfstrings, true) ||7330      !Args.hasFlag(options::OPT_mconstant_cfstrings,7331                    options::OPT_mno_constant_cfstrings, true))7332    CmdArgs.push_back("-fno-constant-cfstrings");7333 7334  Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,7335                    options::OPT_fno_pascal_strings);7336 7337  // Honor -fpack-struct= and -fpack-struct, if given. Note that7338  // -fno-pack-struct doesn't apply to -fpack-struct=.7339  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {7340    std::string PackStructStr = "-fpack-struct=";7341    PackStructStr += A->getValue();7342    CmdArgs.push_back(Args.MakeArgString(PackStructStr));7343  } else if (Args.hasFlag(options::OPT_fpack_struct,7344                          options::OPT_fno_pack_struct, false)) {7345    CmdArgs.push_back("-fpack-struct=1");7346  }7347 7348  // Handle -fmax-type-align=N and -fno-type-align7349  bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);7350  if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {7351    if (!SkipMaxTypeAlign) {7352      std::string MaxTypeAlignStr = "-fmax-type-align=";7353      MaxTypeAlignStr += A->getValue();7354      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));7355    }7356  } else if (RawTriple.isOSDarwin()) {7357    if (!SkipMaxTypeAlign) {7358      std::string MaxTypeAlignStr = "-fmax-type-align=16";7359      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));7360    }7361  }7362 7363  if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))7364    CmdArgs.push_back("-Qn");7365 7366  // -fno-common is the default, set -fcommon only when that flag is set.7367  Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);7368 7369  // -fsigned-bitfields is default, and clang doesn't yet support7370  // -funsigned-bitfields.7371  if (!Args.hasFlag(options::OPT_fsigned_bitfields,7372                    options::OPT_funsigned_bitfields, true))7373    D.Diag(diag::warn_drv_clang_unsupported)7374        << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);7375 7376  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.7377  if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))7378    D.Diag(diag::err_drv_clang_unsupported)7379        << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);7380 7381  // -finput_charset=UTF-8 is default. Reject others7382  if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {7383    StringRef value = inputCharset->getValue();7384    if (!value.equals_insensitive("utf-8"))7385      D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)7386                                          << value;7387  }7388 7389  // -fexec_charset=UTF-8 is default. Reject others7390  if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {7391    StringRef value = execCharset->getValue();7392    if (!value.equals_insensitive("utf-8"))7393      D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)7394                                          << value;7395  }7396 7397  RenderDiagnosticsOptions(D, Args, CmdArgs);7398 7399  Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,7400                    options::OPT_fno_asm_blocks);7401 7402  Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,7403                     options::OPT_fno_gnu_inline_asm);7404 7405  handleVectorizeLoopsArgs(Args, CmdArgs);7406  handleVectorizeSLPArgs(Args, CmdArgs);7407 7408  StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);7409  if (!VecWidth.empty())7410    CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));7411 7412  Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);7413  Args.AddLastArg(CmdArgs,7414                  options::OPT_fsanitize_undefined_strip_path_components_EQ);7415 7416  // -fdollars-in-identifiers default varies depending on platform and7417  // language; only pass if specified.7418  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,7419                               options::OPT_fno_dollars_in_identifiers)) {7420    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))7421      CmdArgs.push_back("-fdollars-in-identifiers");7422    else7423      CmdArgs.push_back("-fno-dollars-in-identifiers");7424  }7425 7426  Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,7427                    options::OPT_fno_apple_pragma_pack);7428 7429  // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.7430  if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))7431    renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);7432 7433  bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,7434                                     options::OPT_fno_rewrite_imports, false);7435  if (RewriteImports)7436    CmdArgs.push_back("-frewrite-imports");7437 7438  Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,7439                    options::OPT_fno_directives_only);7440 7441  // Enable rewrite includes if the user's asked for it or if we're generating7442  // diagnostics.7443  // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be7444  // nice to enable this when doing a crashdump for modules as well.7445  if (Args.hasFlag(options::OPT_frewrite_includes,7446                   options::OPT_fno_rewrite_includes, false) ||7447      (C.isForDiagnostics() && !HaveModules))7448    CmdArgs.push_back("-frewrite-includes");7449 7450  if (Args.hasFlag(options::OPT_fzos_extensions,7451                   options::OPT_fno_zos_extensions, false))7452    CmdArgs.push_back("-fzos-extensions");7453  else if (Args.hasArg(options::OPT_fno_zos_extensions))7454    CmdArgs.push_back("-fno-zos-extensions");7455 7456  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.7457  if (Arg *A = Args.getLastArg(options::OPT_traditional,7458                               options::OPT_traditional_cpp)) {7459    if (isa<PreprocessJobAction>(JA))7460      CmdArgs.push_back("-traditional-cpp");7461    else7462      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);7463  }7464 7465  Args.AddLastArg(CmdArgs, options::OPT_dM);7466  Args.AddLastArg(CmdArgs, options::OPT_dD);7467  Args.AddLastArg(CmdArgs, options::OPT_dI);7468 7469  Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);7470 7471  // Handle serialized diagnostics.7472  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {7473    CmdArgs.push_back("-serialize-diagnostic-file");7474    CmdArgs.push_back(Args.MakeArgString(A->getValue()));7475  }7476 7477  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))7478    CmdArgs.push_back("-fretain-comments-from-system-headers");7479 7480  if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {7481    A->render(Args, CmdArgs);7482  } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);7483             A && A->containsValue("g")) {7484    // Set -fextend-variable-liveness=all by default at -Og.7485    CmdArgs.push_back("-fextend-variable-liveness=all");7486  }7487 7488  // Forward -fcomment-block-commands to -cc1.7489  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);7490  // Forward -fparse-all-comments to -cc1.7491  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);7492 7493  // Turn -fplugin=name.so into -load name.so7494  for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {7495    CmdArgs.push_back("-load");7496    CmdArgs.push_back(A->getValue());7497    A->claim();7498  }7499 7500  // Turn -fplugin-arg-pluginname-key=value into7501  // -plugin-arg-pluginname key=value7502  // GCC has an actual plugin_argument struct with key/value pairs that it7503  // passes to its plugins, but we don't, so just pass it on as-is.7504  //7505  // The syntax for -fplugin-arg- is ambiguous if both plugin name and7506  // argument key are allowed to contain dashes. GCC therefore only7507  // allows dashes in the key. We do the same.7508  for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {7509    auto ArgValue = StringRef(A->getValue());7510    auto FirstDashIndex = ArgValue.find('-');7511    StringRef PluginName = ArgValue.substr(0, FirstDashIndex);7512    StringRef Arg = ArgValue.substr(FirstDashIndex + 1);7513 7514    A->claim();7515    if (FirstDashIndex == StringRef::npos || Arg.empty()) {7516      if (PluginName.empty()) {7517        D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);7518      } else {7519        D.Diag(diag::warn_drv_missing_plugin_arg)7520            << PluginName << A->getAsString(Args);7521      }7522      continue;7523    }7524 7525    CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));7526    CmdArgs.push_back(Args.MakeArgString(Arg));7527  }7528 7529  // Forward -fpass-plugin=name.so to -cc1.7530  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {7531    CmdArgs.push_back(7532        Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));7533    A->claim();7534  }7535 7536  // Forward --vfsoverlay to -cc1.7537  for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {7538    CmdArgs.push_back("--vfsoverlay");7539    CmdArgs.push_back(A->getValue());7540    A->claim();7541  }7542 7543  Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,7544                    options::OPT_fno_safe_buffer_usage_suggestions);7545 7546  Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,7547                    options::OPT_fno_experimental_late_parse_attributes);7548 7549  if (Args.hasFlag(options::OPT_funique_source_file_names,7550                   options::OPT_fno_unique_source_file_names, false)) {7551    if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))7552      A->render(Args, CmdArgs);7553    else7554      CmdArgs.push_back(Args.MakeArgString(7555          Twine("-funique-source-file-identifier=") + Input.getBaseInput()));7556  }7557 7558  // Setup statistics file output.7559  SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);7560  if (!StatsFile.empty()) {7561    CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));7562    if (D.CCPrintInternalStats)7563      CmdArgs.push_back("-stats-file-append");7564  }7565 7566  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option7567  // parser.7568  for (auto Arg : Args.filtered(options::OPT_Xclang)) {7569    Arg->claim();7570    // -finclude-default-header flag is for preprocessor,7571    // do not pass it to other cc1 commands when save-temps is enabled7572    if (C.getDriver().isSaveTempsEnabled() &&7573        !isa<PreprocessJobAction>(JA)) {7574      if (StringRef(Arg->getValue()) == "-finclude-default-header")7575        continue;7576    }7577    CmdArgs.push_back(Arg->getValue());7578  }7579  for (const Arg *A : Args.filtered(options::OPT_mllvm)) {7580    A->claim();7581 7582    // We translate this by hand to the -cc1 argument, since nightly test uses7583    // it and developers have been trained to spell it with -mllvm. Both7584    // spellings are now deprecated and should be removed.7585    if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {7586      CmdArgs.push_back("-disable-llvm-optzns");7587    } else {7588      A->render(Args, CmdArgs);7589    }7590  }7591 7592  // This needs to run after -Xclang argument forwarding to pick up the target7593  // features enabled through -Xclang -target-feature flags.7594  SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);7595 7596  Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);7597 7598#if CLANG_ENABLE_CIR7599  // Forward -mmlir arguments to to the MLIR option parser.7600  for (const Arg *A : Args.filtered(options::OPT_mmlir)) {7601    A->claim();7602    A->render(Args, CmdArgs);7603  }7604#endif // CLANG_ENABLE_CIR7605 7606  // With -save-temps, we want to save the unoptimized bitcode output from the7607  // CompileJobAction, use -disable-llvm-passes to get pristine IR generated7608  // by the frontend.7609  // When -fembed-bitcode is enabled, optimized bitcode is emitted because it7610  // has slightly different breakdown between stages.7611  // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of7612  // pristine IR generated by the frontend. Ideally, a new compile action should7613  // be added so both IR can be captured.7614  if ((C.getDriver().isSaveTempsEnabled() ||7615       JA.isHostOffloading(Action::OFK_OpenMP)) &&7616      !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&7617      isa<CompileJobAction>(JA))7618    CmdArgs.push_back("-disable-llvm-passes");7619 7620  Args.AddAllArgs(CmdArgs, options::OPT_undef);7621 7622  const char *Exec = D.getClangProgramPath();7623 7624  // Optionally embed the -cc1 level arguments into the debug info or a7625  // section, for build analysis.7626  // Also record command line arguments into the debug info if7627  // -grecord-gcc-switches options is set on.7628  // By default, -gno-record-gcc-switches is set on and no recording.7629  auto GRecordSwitches = false;7630  auto FRecordSwitches = false;7631  if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches)) {7632    auto FlagsArgString = renderEscapedCommandLine(TC, Args);7633    if (TC.UseDwarfDebugFlags() || GRecordSwitches) {7634      CmdArgs.push_back("-dwarf-debug-flags");7635      CmdArgs.push_back(FlagsArgString);7636    }7637    if (FRecordSwitches) {7638      CmdArgs.push_back("-record-command-line");7639      CmdArgs.push_back(FlagsArgString);7640    }7641  }7642 7643  // Host-side offloading compilation receives all device-side outputs. Include7644  // them in the host compilation depending on the target. If the host inputs7645  // are not empty we use the new-driver scheme, otherwise use the old scheme.7646  if ((IsCuda || IsHIP) && CudaDeviceInput) {7647    CmdArgs.push_back("-fcuda-include-gpubinary");7648    CmdArgs.push_back(CudaDeviceInput->getFilename());7649  } else if (!HostOffloadingInputs.empty()) {7650    if ((IsCuda || IsHIP) && !IsRDCMode) {7651      assert(HostOffloadingInputs.size() == 1 && "Only one input expected");7652      CmdArgs.push_back("-fcuda-include-gpubinary");7653      CmdArgs.push_back(HostOffloadingInputs.front().getFilename());7654    } else {7655      for (const InputInfo Input : HostOffloadingInputs)7656        CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +7657                                             TC.getInputFilename(Input)));7658    }7659  }7660 7661  if (IsCuda) {7662    if (Args.hasFlag(options::OPT_fcuda_short_ptr,7663                     options::OPT_fno_cuda_short_ptr, false))7664      CmdArgs.push_back("-fcuda-short-ptr");7665  }7666 7667  if (IsCuda || IsHIP) {7668    // Determine the original source input.7669    const Action *SourceAction = &JA;7670    while (SourceAction->getKind() != Action::InputClass) {7671      assert(!SourceAction->getInputs().empty() && "unexpected root action!");7672      SourceAction = SourceAction->getInputs()[0];7673    }7674    auto CUID = cast<InputAction>(SourceAction)->getId();7675    if (!CUID.empty())7676      CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));7677 7678    // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will7679    // be overriden by -fno-gpu-approx-transcendentals.7680    bool UseApproxTranscendentals = Args.hasFlag(7681        options::OPT_ffast_math, options::OPT_fno_fast_math, false);7682    if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,7683                     options::OPT_fno_gpu_approx_transcendentals,7684                     UseApproxTranscendentals))7685      CmdArgs.push_back("-fgpu-approx-transcendentals");7686  } else {7687    Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,7688                      options::OPT_fno_gpu_approx_transcendentals);7689  }7690 7691  if (IsHIP) {7692    CmdArgs.push_back("-fcuda-allow-variadic-functions");7693    Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);7694  }7695 7696  Args.AddAllArgs(CmdArgs,7697                  options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);7698 7699  Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,7700                  options::OPT_fno_offload_uniform_block);7701 7702  Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,7703                  options::OPT_fno_offload_implicit_host_device_templates);7704 7705  if (IsCudaDevice || IsHIPDevice) {7706    StringRef InlineThresh =7707        Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);7708    if (!InlineThresh.empty()) {7709      std::string ArgStr =7710          std::string("-inline-threshold=") + InlineThresh.str();7711      CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});7712    }7713  }7714 7715  if (IsHIPDevice)7716    Args.addOptOutFlag(CmdArgs,7717                       options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,7718                       options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);7719 7720  // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path7721  // to specify the result of the compile phase on the host, so the meaningful7722  // device declarations can be identified. Also, -fopenmp-is-target-device is7723  // passed along to tell the frontend that it is generating code for a device,7724  // so that only the relevant declarations are emitted.7725  if (IsOpenMPDevice) {7726    CmdArgs.push_back("-fopenmp-is-target-device");7727    // If we are offloading cuda/hip via llvm, it's also "cuda device code".7728    if (Args.hasArg(options::OPT_foffload_via_llvm))7729      CmdArgs.push_back("-fcuda-is-device");7730 7731    if (OpenMPDeviceInput) {7732      CmdArgs.push_back("-fopenmp-host-ir-file-path");7733      CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));7734    }7735  }7736 7737  if (Triple.isAMDGPU()) {7738    handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);7739 7740    Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,7741                      options::OPT_mno_unsafe_fp_atomics);7742    Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,7743                       options::OPT_mno_amdgpu_ieee);7744  }7745 7746  addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);7747 7748  bool VirtualFunctionElimination =7749      Args.hasFlag(options::OPT_fvirtual_function_elimination,7750                   options::OPT_fno_virtual_function_elimination, false);7751  if (VirtualFunctionElimination) {7752    // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO7753    // in the future).7754    if (LTOMode != LTOK_Full)7755      D.Diag(diag::err_drv_argument_only_allowed_with)7756          << "-fvirtual-function-elimination"7757          << "-flto=full";7758 7759    CmdArgs.push_back("-fvirtual-function-elimination");7760  }7761 7762  // VFE requires whole-program-vtables, and enables it by default.7763  bool WholeProgramVTables = Args.hasFlag(7764      options::OPT_fwhole_program_vtables,7765      options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);7766  if (VirtualFunctionElimination && !WholeProgramVTables) {7767    D.Diag(diag::err_drv_argument_not_allowed_with)7768        << "-fno-whole-program-vtables"7769        << "-fvirtual-function-elimination";7770  }7771 7772  if (WholeProgramVTables) {7773    // PS4 uses the legacy LTO API, which does not support this feature in7774    // ThinLTO mode.7775    bool IsPS4 = getToolChain().getTriple().isPS4();7776 7777    // Check if we passed LTO options but they were suppressed because this is a7778    // device offloading action, or we passed device offload LTO options which7779    // were suppressed because this is not the device offload action.7780    // Check if we are using PS4 in regular LTO mode.7781    // Otherwise, issue an error.7782 7783    auto OtherLTOMode =7784        IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();7785    auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;7786 7787    if ((!IsUsingLTO && !OtherIsUsingLTO) ||7788        (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))7789      D.Diag(diag::err_drv_argument_only_allowed_with)7790          << "-fwhole-program-vtables"7791          << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");7792 7793    // Propagate -fwhole-program-vtables if this is an LTO compile.7794    if (IsUsingLTO)7795      CmdArgs.push_back("-fwhole-program-vtables");7796  }7797 7798  bool DefaultsSplitLTOUnit =7799      ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&7800          (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||7801      (!Triple.isPS4() && UnifiedLTO);7802  bool SplitLTOUnit =7803      Args.hasFlag(options::OPT_fsplit_lto_unit,7804                   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);7805  if (SanitizeArgs.needsLTO() && !SplitLTOUnit)7806    D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"7807                                                    << "-fsanitize=cfi";7808  if (SplitLTOUnit)7809    CmdArgs.push_back("-fsplit-lto-unit");7810 7811  if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,7812                               options::OPT_fno_fat_lto_objects)) {7813    if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {7814      assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);7815      if (!Triple.isOSBinFormatELF()) {7816        D.Diag(diag::err_drv_unsupported_opt_for_target)7817            << A->getAsString(Args) << TC.getTripleString();7818      }7819      CmdArgs.push_back(Args.MakeArgString(7820          Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));7821      CmdArgs.push_back("-flto-unit");7822      CmdArgs.push_back("-ffat-lto-objects");7823      A->render(Args, CmdArgs);7824    }7825  }7826 7827  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,7828                               options::OPT_fno_global_isel)) {7829    CmdArgs.push_back("-mllvm");7830    if (A->getOption().matches(options::OPT_fglobal_isel)) {7831      CmdArgs.push_back("-global-isel=1");7832 7833      // GISel is on by default on AArch64 -O0, so don't bother adding7834      // the fallback remarks for it. Other combinations will add a warning of7835      // some kind.7836      bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;7837      bool IsOptLevelSupported = false;7838 7839      Arg *A = Args.getLastArg(options::OPT_O_Group);7840      if (Triple.getArch() == llvm::Triple::aarch64) {7841        if (!A || A->getOption().matches(options::OPT_O0))7842          IsOptLevelSupported = true;7843      }7844      if (!IsArchSupported || !IsOptLevelSupported) {7845        CmdArgs.push_back("-mllvm");7846        CmdArgs.push_back("-global-isel-abort=2");7847 7848        if (!IsArchSupported)7849          D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();7850        else7851          D.Diag(diag::warn_drv_global_isel_incomplete_opt);7852      }7853    } else {7854      CmdArgs.push_back("-global-isel=0");7855    }7856  }7857 7858  if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,7859                               options::OPT_fno_force_enable_int128)) {7860    if (A->getOption().matches(options::OPT_fforce_enable_int128))7861      CmdArgs.push_back("-fforce-enable-int128");7862  }7863 7864  Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,7865                    options::OPT_fno_keep_static_consts);7866  Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,7867                    options::OPT_fno_keep_persistent_storage_variables);7868  Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,7869                    options::OPT_fno_complete_member_pointers);7870  if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))7871    A->render(Args, CmdArgs);7872 7873  addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);7874 7875  addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);7876 7877  if (Triple.isAArch64() &&7878      (Args.hasArg(options::OPT_mno_fmv) ||7879       (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||7880       getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {7881    // Disable Function Multiversioning on AArch64 target.7882    CmdArgs.push_back("-target-feature");7883    CmdArgs.push_back("-fmv");7884  }7885 7886  if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,7887                   (TC.getTriple().isOSBinFormatELF() ||7888                    TC.getTriple().isOSBinFormatCOFF()) &&7889                       !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&7890                       !TC.getTriple().isOSNetBSD() &&7891                       !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&7892                       !TC.getTriple().isAndroid() && TC.useIntegratedAs()))7893    CmdArgs.push_back("-faddrsig");7894 7895  const bool HasDefaultDwarf2CFIASM =7896      (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&7897      (EH || UnwindTables || AsyncUnwindTables ||7898       DebugInfoKind != llvm::codegenoptions::NoDebugInfo);7899  if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,7900                   options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))7901    CmdArgs.push_back("-fdwarf2-cfi-asm");7902 7903  if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {7904    std::string Str = A->getAsString(Args);7905    if (!TC.getTriple().isOSBinFormatELF())7906      D.Diag(diag::err_drv_unsupported_opt_for_target)7907          << Str << TC.getTripleString();7908    CmdArgs.push_back(Args.MakeArgString(Str));7909  }7910 7911  // Add the "-o out -x type src.c" flags last. This is done primarily to make7912  // the -cc1 command easier to edit when reproducing compiler crashes.7913  if (Output.getType() == types::TY_Dependencies) {7914    // Handled with other dependency code.7915  } else if (Output.isFilename()) {7916    if (Output.getType() == clang::driver::types::TY_IFS_CPP ||7917        Output.getType() == clang::driver::types::TY_IFS) {7918      SmallString<128> OutputFilename(Output.getFilename());7919      llvm::sys::path::replace_extension(OutputFilename, "ifs");7920      CmdArgs.push_back("-o");7921      CmdArgs.push_back(Args.MakeArgString(OutputFilename));7922    } else {7923      CmdArgs.push_back("-o");7924      CmdArgs.push_back(Output.getFilename());7925    }7926  } else {7927    assert(Output.isNothing() && "Invalid output.");7928  }7929 7930  addDashXForInput(Args, Input, CmdArgs);7931 7932  ArrayRef<InputInfo> FrontendInputs = Input;7933  if (IsExtractAPI)7934    FrontendInputs = ExtractAPIInputs;7935  else if (Input.isNothing())7936    FrontendInputs = {};7937 7938  for (const InputInfo &Input : FrontendInputs) {7939    if (Input.isFilename())7940      CmdArgs.push_back(Input.getFilename());7941    else7942      Input.getInputArg().renderAsInput(Args, CmdArgs);7943  }7944 7945  if (D.CC1Main && !D.CCGenDiagnostics) {7946    // Invoke the CC1 directly in this process7947    C.addCommand(std::make_unique<CC1Command>(7948        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,7949        Output, D.getPrependArg()));7950  } else {7951    C.addCommand(std::make_unique<Command>(7952        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,7953        Output, D.getPrependArg()));7954  }7955 7956  // Make the compile command echo its inputs for /showFilenames.7957  if (Output.getType() == types::TY_Object &&7958      Args.hasFlag(options::OPT__SLASH_showFilenames,7959                   options::OPT__SLASH_showFilenames_, false)) {7960    C.getJobs().getJobs().back()->PrintInputFilenames = true;7961  }7962 7963  if (Arg *A = Args.getLastArg(options::OPT_pg))7964    if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&7965        !Args.hasArg(options::OPT_mfentry))7966      D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"7967                                                      << A->getAsString(Args);7968 7969  // Claim some arguments which clang supports automatically.7970 7971  // -fpch-preprocess is used with gcc to add a special marker in the output to7972  // include the PCH file.7973  Args.ClaimAllArgs(options::OPT_fpch_preprocess);7974 7975  // Claim some arguments which clang doesn't support, but we don't7976  // care to warn the user about.7977  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);7978  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);7979 7980  // Disable warnings for clang -E -emit-llvm foo.c7981  Args.ClaimAllArgs(options::OPT_emit_llvm);7982}7983 7984Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)7985    // CAUTION! The first constructor argument ("clang") is not arbitrary,7986    // as it is for other tools. Some operations on a Tool actually test7987    // whether that tool is Clang based on the Tool's Name as a string.7988    : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}7989 7990Clang::~Clang() {}7991 7992/// Add options related to the Objective-C runtime/ABI.7993///7994/// Returns true if the runtime is non-fragile.7995ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,7996                                      const InputInfoList &inputs,7997                                      ArgStringList &cmdArgs,7998                                      RewriteKind rewriteKind) const {7999  // Look for the controlling runtime option.8000  Arg *runtimeArg =8001      args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,8002                      options::OPT_fobjc_runtime_EQ);8003 8004  // Just forward -fobjc-runtime= to the frontend.  This supercedes8005  // options about fragility.8006  if (runtimeArg &&8007      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {8008    ObjCRuntime runtime;8009    StringRef value = runtimeArg->getValue();8010    if (runtime.tryParse(value)) {8011      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)8012          << value;8013    }8014    if ((runtime.getKind() == ObjCRuntime::GNUstep) &&8015        (runtime.getVersion() >= VersionTuple(2, 0)))8016      if (!getToolChain().getTriple().isOSBinFormatELF() &&8017          !getToolChain().getTriple().isOSBinFormatCOFF()) {8018        getToolChain().getDriver().Diag(8019            diag::err_drv_gnustep_objc_runtime_incompatible_binary)8020          << runtime.getVersion().getMajor();8021      }8022 8023    runtimeArg->render(args, cmdArgs);8024    return runtime;8025  }8026 8027  // Otherwise, we'll need the ABI "version".  Version numbers are8028  // slightly confusing for historical reasons:8029  //   1 - Traditional "fragile" ABI8030  //   2 - Non-fragile ABI, version 18031  //   3 - Non-fragile ABI, version 28032  unsigned objcABIVersion = 1;8033  // If -fobjc-abi-version= is present, use that to set the version.8034  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {8035    StringRef value = abiArg->getValue();8036    if (value == "1")8037      objcABIVersion = 1;8038    else if (value == "2")8039      objcABIVersion = 2;8040    else if (value == "3")8041      objcABIVersion = 3;8042    else8043      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;8044  } else {8045    // Otherwise, determine if we are using the non-fragile ABI.8046    bool nonFragileABIIsDefault =8047        (rewriteKind == RK_NonFragile ||8048         (rewriteKind == RK_None &&8049          getToolChain().IsObjCNonFragileABIDefault()));8050    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,8051                     options::OPT_fno_objc_nonfragile_abi,8052                     nonFragileABIIsDefault)) {8053// Determine the non-fragile ABI version to use.8054#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO8055      unsigned nonFragileABIVersion = 1;8056#else8057      unsigned nonFragileABIVersion = 2;8058#endif8059 8060      if (Arg *abiArg =8061              args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {8062        StringRef value = abiArg->getValue();8063        if (value == "1")8064          nonFragileABIVersion = 1;8065        else if (value == "2")8066          nonFragileABIVersion = 2;8067        else8068          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)8069              << value;8070      }8071 8072      objcABIVersion = 1 + nonFragileABIVersion;8073    } else {8074      objcABIVersion = 1;8075    }8076  }8077 8078  // We don't actually care about the ABI version other than whether8079  // it's non-fragile.8080  bool isNonFragile = objcABIVersion != 1;8081 8082  // If we have no runtime argument, ask the toolchain for its default runtime.8083  // However, the rewriter only really supports the Mac runtime, so assume that.8084  ObjCRuntime runtime;8085  if (!runtimeArg) {8086    switch (rewriteKind) {8087    case RK_None:8088      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);8089      break;8090    case RK_Fragile:8091      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());8092      break;8093    case RK_NonFragile:8094      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());8095      break;8096    }8097 8098    // -fnext-runtime8099  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {8100    // On Darwin, make this use the default behavior for the toolchain.8101    if (getToolChain().getTriple().isOSDarwin()) {8102      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);8103 8104      // Otherwise, build for a generic macosx port.8105    } else {8106      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());8107    }8108 8109    // -fgnu-runtime8110  } else {8111    assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));8112    // Legacy behaviour is to target the gnustep runtime if we are in8113    // non-fragile mode or the GCC runtime in fragile mode.8114    if (isNonFragile)8115      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));8116    else8117      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());8118  }8119 8120  if (llvm::any_of(inputs, [](const InputInfo &input) {8121        return types::isObjC(input.getType());8122      }))8123    cmdArgs.push_back(8124        args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));8125  return runtime;8126}8127 8128static bool maybeConsumeDash(const std::string &EH, size_t &I) {8129  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');8130  I += HaveDash;8131  return !HaveDash;8132}8133 8134namespace {8135struct EHFlags {8136  bool Synch = false;8137  bool Asynch = false;8138  bool NoUnwindC = false;8139};8140} // end anonymous namespace8141 8142/// /EH controls whether to run destructor cleanups when exceptions are8143/// thrown.  There are three modifiers:8144/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.8145/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.8146///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.8147/// - c: Assume that extern "C" functions are implicitly nounwind.8148/// The default is /EHs-c-, meaning cleanups are disabled.8149static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,8150                                   bool isWindowsMSVC) {8151  EHFlags EH;8152 8153  std::vector<std::string> EHArgs =8154      Args.getAllArgValues(options::OPT__SLASH_EH);8155  for (const auto &EHVal : EHArgs) {8156    for (size_t I = 0, E = EHVal.size(); I != E; ++I) {8157      switch (EHVal[I]) {8158      case 'a':8159        EH.Asynch = maybeConsumeDash(EHVal, I);8160        if (EH.Asynch) {8161          // Async exceptions are Windows MSVC only.8162          if (!isWindowsMSVC) {8163            EH.Asynch = false;8164            D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;8165            continue;8166          }8167          EH.Synch = false;8168        }8169        continue;8170      case 'c':8171        EH.NoUnwindC = maybeConsumeDash(EHVal, I);8172        continue;8173      case 's':8174        EH.Synch = maybeConsumeDash(EHVal, I);8175        if (EH.Synch)8176          EH.Asynch = false;8177        continue;8178      default:8179        break;8180      }8181      D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;8182      break;8183    }8184  }8185  // The /GX, /GX- flags are only processed if there are not /EH flags.8186  // The default is that /GX is not specified.8187  if (EHArgs.empty() &&8188      Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,8189                   /*Default=*/false)) {8190    EH.Synch = true;8191    EH.NoUnwindC = true;8192  }8193 8194  if (Args.hasArg(options::OPT__SLASH_kernel)) {8195    EH.Synch = false;8196    EH.NoUnwindC = false;8197    EH.Asynch = false;8198  }8199 8200  return EH;8201}8202 8203void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,8204                           ArgStringList &CmdArgs) const {8205  bool isNVPTX = getToolChain().getTriple().isNVPTX();8206 8207  ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);8208 8209  if (Arg *ShowIncludes =8210          Args.getLastArg(options::OPT__SLASH_showIncludes,8211                          options::OPT__SLASH_showIncludes_user)) {8212    CmdArgs.push_back("--show-includes");8213    if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))8214      CmdArgs.push_back("-sys-header-deps");8215  }8216 8217  // This controls whether or not we emit RTTI data for polymorphic types.8218  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,8219                   /*Default=*/false))8220    CmdArgs.push_back("-fno-rtti-data");8221 8222  // This controls whether or not we emit stack-protector instrumentation.8223  // In MSVC, Buffer Security Check (/GS) is on by default.8224  if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,8225                               /*Default=*/true)) {8226    CmdArgs.push_back("-stack-protector");8227    CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));8228  }8229 8230  const Driver &D = getToolChain().getDriver();8231 8232  bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();8233  EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);8234  if (!isNVPTX && (EH.Synch || EH.Asynch)) {8235    if (types::isCXX(InputType))8236      CmdArgs.push_back("-fcxx-exceptions");8237    CmdArgs.push_back("-fexceptions");8238    if (EH.Asynch)8239      CmdArgs.push_back("-fasync-exceptions");8240  }8241  if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)8242    CmdArgs.push_back("-fexternc-nounwind");8243 8244  // /EP should expand to -E -P.8245  if (Args.hasArg(options::OPT__SLASH_EP)) {8246    CmdArgs.push_back("-E");8247    CmdArgs.push_back("-P");8248  }8249 8250 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,8251                  options::OPT__SLASH_Zc_dllexportInlines,8252                  false)) {8253  CmdArgs.push_back("-fno-dllexport-inlines");8254 }8255 8256 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,8257                  options::OPT__SLASH_Zc_wchar_t, false)) {8258   CmdArgs.push_back("-fno-wchar");8259 }8260 8261 if (Args.hasArg(options::OPT__SLASH_kernel)) {8262   llvm::Triple::ArchType Arch = getToolChain().getArch();8263   std::vector<std::string> Values =8264       Args.getAllArgValues(options::OPT__SLASH_arch);8265   if (!Values.empty()) {8266     llvm::SmallSet<std::string, 4> SupportedArches;8267     if (Arch == llvm::Triple::x86)8268       SupportedArches.insert("IA32");8269 8270     for (auto &V : Values)8271       if (!SupportedArches.contains(V))8272         D.Diag(diag::err_drv_argument_not_allowed_with)8273             << std::string("/arch:").append(V) << "/kernel";8274   }8275 8276   CmdArgs.push_back("-fno-rtti");8277   if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))8278     D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"8279                                                     << "/kernel";8280 }8281 8282  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,8283                                     options::OPT__SLASH_vlen_EQ_256,8284                                     options::OPT__SLASH_vlen_EQ_512)) {8285    llvm::Triple::ArchType AT = getToolChain().getArch();8286    StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";8287    StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);8288    llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",8289                                            "AVX10.2"};8290 8291    if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {8292      if (Arch512.contains(Arch))8293        CmdArgs.push_back("-mprefer-vector-width=512");8294      else8295        D.Diag(diag::warn_drv_argument_not_allowed_with)8296            << "/vlen=512" << std::string("/arch:").append(Arch);8297    } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {8298      if (Arch512.contains(Arch))8299        CmdArgs.push_back("-mprefer-vector-width=256");8300      else if (Arch != "AVX" && Arch != "AVX2")8301        D.Diag(diag::warn_drv_argument_not_allowed_with)8302            << "/vlen=256" << std::string("/arch:").append(Arch);8303    } else {8304      if (Arch == "AVX10.1" || Arch == "AVX10.2")8305        CmdArgs.push_back("-mprefer-vector-width=256");8306    }8307  } else {8308    StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);8309    if (Arch == "AVX10.1" || Arch == "AVX10.2")8310      CmdArgs.push_back("-mprefer-vector-width=256");8311  }8312 8313  Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);8314  Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);8315  if (MostGeneralArg && BestCaseArg)8316    D.Diag(clang::diag::err_drv_argument_not_allowed_with)8317        << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);8318 8319  if (MostGeneralArg) {8320    Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);8321    Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);8322    Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);8323 8324    Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;8325    Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;8326    if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)8327      D.Diag(clang::diag::err_drv_argument_not_allowed_with)8328          << FirstConflict->getAsString(Args)8329          << SecondConflict->getAsString(Args);8330 8331    if (SingleArg)8332      CmdArgs.push_back("-fms-memptr-rep=single");8333    else if (MultipleArg)8334      CmdArgs.push_back("-fms-memptr-rep=multiple");8335    else8336      CmdArgs.push_back("-fms-memptr-rep=virtual");8337  }8338 8339  if (Args.hasArg(options::OPT_regcall4))8340    CmdArgs.push_back("-regcall4");8341 8342  // Parse the default calling convention options.8343  if (Arg *CCArg =8344          Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,8345                          options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,8346                          options::OPT__SLASH_Gregcall)) {8347    unsigned DCCOptId = CCArg->getOption().getID();8348    const char *DCCFlag = nullptr;8349    bool ArchSupported = !isNVPTX;8350    llvm::Triple::ArchType Arch = getToolChain().getArch();8351    switch (DCCOptId) {8352    case options::OPT__SLASH_Gd:8353      DCCFlag = "-fdefault-calling-conv=cdecl";8354      break;8355    case options::OPT__SLASH_Gr:8356      ArchSupported = Arch == llvm::Triple::x86;8357      DCCFlag = "-fdefault-calling-conv=fastcall";8358      break;8359    case options::OPT__SLASH_Gz:8360      ArchSupported = Arch == llvm::Triple::x86;8361      DCCFlag = "-fdefault-calling-conv=stdcall";8362      break;8363    case options::OPT__SLASH_Gv:8364      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;8365      DCCFlag = "-fdefault-calling-conv=vectorcall";8366      break;8367    case options::OPT__SLASH_Gregcall:8368      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;8369      DCCFlag = "-fdefault-calling-conv=regcall";8370      break;8371    }8372 8373    // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.8374    if (ArchSupported && DCCFlag)8375      CmdArgs.push_back(DCCFlag);8376  }8377 8378  if (Args.hasArg(options::OPT__SLASH_Gregcall4))8379    CmdArgs.push_back("-regcall4");8380 8381  Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);8382 8383  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {8384    CmdArgs.push_back("-fdiagnostics-format");8385    CmdArgs.push_back("msvc");8386  }8387 8388  if (Args.hasArg(options::OPT__SLASH_kernel))8389    CmdArgs.push_back("-fms-kernel");8390 8391  // Unwind v2 (epilog) information for x64 Windows.8392  if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))8393    CmdArgs.push_back("-fwinx64-eh-unwindv2=required");8394  else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))8395    CmdArgs.push_back("-fwinx64-eh-unwindv2=best-effort");8396 8397  for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {8398    StringRef GuardArgs = A->getValue();8399    // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and8400    // "ehcont-".8401    if (GuardArgs.equals_insensitive("cf")) {8402      // Emit CFG instrumentation and the table of address-taken functions.8403      CmdArgs.push_back("-cfguard");8404    } else if (GuardArgs.equals_insensitive("cf,nochecks")) {8405      // Emit only the table of address-taken functions.8406      CmdArgs.push_back("-cfguard-no-checks");8407    } else if (GuardArgs.equals_insensitive("ehcont")) {8408      // Emit EH continuation table.8409      CmdArgs.push_back("-ehcontguard");8410    } else if (GuardArgs.equals_insensitive("cf-") ||8411               GuardArgs.equals_insensitive("ehcont-")) {8412      // Do nothing, but we might want to emit a security warning in future.8413    } else {8414      D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;8415    }8416    A->claim();8417  }8418 8419  for (const auto &FuncOverride :8420       Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {8421    CmdArgs.push_back(Args.MakeArgString(8422        Twine("-loader-replaceable-function=") + FuncOverride));8423  }8424}8425 8426const char *Clang::getBaseInputName(const ArgList &Args,8427                                    const InputInfo &Input) {8428  return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));8429}8430 8431const char *Clang::getBaseInputStem(const ArgList &Args,8432                                    const InputInfoList &Inputs) {8433  const char *Str = getBaseInputName(Args, Inputs[0]);8434 8435  if (const char *End = strrchr(Str, '.'))8436    return Args.MakeArgString(std::string(Str, End));8437 8438  return Str;8439}8440 8441const char *Clang::getDependencyFileName(const ArgList &Args,8442                                         const InputInfoList &Inputs) {8443  // FIXME: Think about this more.8444 8445  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {8446    SmallString<128> OutputFilename(OutputOpt->getValue());8447    llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));8448    return Args.MakeArgString(OutputFilename);8449  }8450 8451  return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");8452}8453 8454// Begin ClangAs8455 8456void ClangAs::AddMIPSTargetArgs(const ArgList &Args,8457                                ArgStringList &CmdArgs) const {8458  StringRef CPUName;8459  StringRef ABIName;8460  const llvm::Triple &Triple = getToolChain().getTriple();8461  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);8462 8463  CmdArgs.push_back("-target-abi");8464  CmdArgs.push_back(ABIName.data());8465}8466 8467void ClangAs::AddX86TargetArgs(const ArgList &Args,8468                               ArgStringList &CmdArgs) const {8469  addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,8470                        /*IsLTO=*/false);8471 8472  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {8473    StringRef Value = A->getValue();8474    if (Value == "intel" || Value == "att") {8475      CmdArgs.push_back("-mllvm");8476      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));8477    } else {8478      getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)8479          << A->getSpelling() << Value;8480    }8481  }8482}8483 8484void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,8485                                     ArgStringList &CmdArgs) const {8486  CmdArgs.push_back("-target-abi");8487  CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,8488                                               getToolChain().getTriple())8489                        .data());8490}8491 8492void ClangAs::AddRISCVTargetArgs(const ArgList &Args,8493                               ArgStringList &CmdArgs) const {8494  const llvm::Triple &Triple = getToolChain().getTriple();8495  StringRef ABIName = riscv::getRISCVABI(Args, Triple);8496 8497  CmdArgs.push_back("-target-abi");8498  CmdArgs.push_back(ABIName.data());8499 8500  if (Args.hasFlag(options::OPT_mdefault_build_attributes,8501                   options::OPT_mno_default_build_attributes, true)) {8502      CmdArgs.push_back("-mllvm");8503      CmdArgs.push_back("-riscv-add-build-attributes");8504  }8505}8506 8507void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,8508                           const InputInfo &Output, const InputInfoList &Inputs,8509                           const ArgList &Args,8510                           const char *LinkingOutput) const {8511  ArgStringList CmdArgs;8512 8513  assert(Inputs.size() == 1 && "Unexpected number of inputs.");8514  const InputInfo &Input = Inputs[0];8515 8516  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();8517  const std::string &TripleStr = Triple.getTriple();8518  const auto &D = getToolChain().getDriver();8519 8520  // Don't warn about "clang -w -c foo.s"8521  Args.ClaimAllArgs(options::OPT_w);8522  // and "clang -emit-llvm -c foo.s"8523  Args.ClaimAllArgs(options::OPT_emit_llvm);8524 8525  claimNoWarnArgs(Args);8526 8527  // Invoke ourselves in -cc1as mode.8528  //8529  // FIXME: Implement custom jobs for internal actions.8530  CmdArgs.push_back("-cc1as");8531 8532  // Add the "effective" target triple.8533  CmdArgs.push_back("-triple");8534  CmdArgs.push_back(Args.MakeArgString(TripleStr));8535 8536  getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);8537 8538  // Set the output mode, we currently only expect to be used as a real8539  // assembler.8540  CmdArgs.push_back("-filetype");8541  CmdArgs.push_back("obj");8542 8543  // Set the main file name, so that debug info works even with8544  // -save-temps or preprocessed assembly.8545  CmdArgs.push_back("-main-file-name");8546  CmdArgs.push_back(Clang::getBaseInputName(Args, Input));8547 8548  // Add the target cpu8549  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);8550  if (!CPU.empty()) {8551    CmdArgs.push_back("-target-cpu");8552    CmdArgs.push_back(Args.MakeArgString(CPU));8553  }8554 8555  // Add the target features8556  getTargetFeatures(D, Triple, Args, CmdArgs, true);8557 8558  // Ignore explicit -force_cpusubtype_ALL option.8559  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);8560 8561  // Pass along any -I options so we get proper .include search paths.8562  Args.AddAllArgs(CmdArgs, options::OPT_I_Group);8563 8564  // Pass along any --embed-dir or similar options so we get proper embed paths.8565  Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);8566 8567  // Determine the original source input.8568  auto FindSource = [](const Action *S) -> const Action * {8569    while (S->getKind() != Action::InputClass) {8570      assert(!S->getInputs().empty() && "unexpected root action!");8571      S = S->getInputs()[0];8572    }8573    return S;8574  };8575  const Action *SourceAction = FindSource(&JA);8576 8577  // Forward -g and handle debug info related flags, assuming we are dealing8578  // with an actual assembly file.8579  bool WantDebug = false;8580  Args.ClaimAllArgs(options::OPT_g_Group);8581  if (Arg *A = Args.getLastArg(options::OPT_g_Group))8582    WantDebug = !A->getOption().matches(options::OPT_g0) &&8583                !A->getOption().matches(options::OPT_ggdb0);8584 8585  // If a -gdwarf argument appeared, remember it.8586  bool EmitDwarf = false;8587  if (const Arg *A = getDwarfNArg(Args))8588    EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());8589 8590  bool EmitCodeView = false;8591  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))8592    EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());8593 8594  // If the user asked for debug info but did not explicitly specify -gcodeview8595  // or -gdwarf, ask the toolchain for the default format.8596  if (!EmitCodeView && !EmitDwarf && WantDebug) {8597    switch (getToolChain().getDefaultDebugFormat()) {8598    case llvm::codegenoptions::DIF_CodeView:8599      EmitCodeView = true;8600      break;8601    case llvm::codegenoptions::DIF_DWARF:8602      EmitDwarf = true;8603      break;8604    }8605  }8606 8607  // If the arguments don't imply DWARF, don't emit any debug info here.8608  if (!EmitDwarf)8609    WantDebug = false;8610 8611  llvm::codegenoptions::DebugInfoKind DebugInfoKind =8612      llvm::codegenoptions::NoDebugInfo;8613 8614  // Add the -fdebug-compilation-dir flag if needed.8615  const char *DebugCompilationDir =8616      addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());8617 8618  if (SourceAction->getType() == types::TY_Asm ||8619      SourceAction->getType() == types::TY_PP_Asm) {8620    // You might think that it would be ok to set DebugInfoKind outside of8621    // the guard for source type, however there is a test which asserts8622    // that some assembler invocation receives no -debug-info-kind,8623    // and it's not clear whether that test is just overly restrictive.8624    DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor8625                               : llvm::codegenoptions::NoDebugInfo);8626 8627    addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,8628                         CmdArgs);8629 8630    // Set the AT_producer to the clang version when using the integrated8631    // assembler on assembly source files.8632    CmdArgs.push_back("-dwarf-debug-producer");8633    CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));8634 8635    // And pass along -I options8636    Args.AddAllArgs(CmdArgs, options::OPT_I);8637  }8638  const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);8639  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,8640                          llvm::DebuggerKind::Default);8641  renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);8642  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());8643 8644  // Handle -fPIC et al -- the relocation-model affects the assembler8645  // for some targets.8646  llvm::Reloc::Model RelocationModel;8647  unsigned PICLevel;8648  bool IsPIE;8649  std::tie(RelocationModel, PICLevel, IsPIE) =8650      ParsePICArgs(getToolChain(), Args);8651 8652  const char *RMName = RelocationModelName(RelocationModel);8653  if (RMName) {8654    CmdArgs.push_back("-mrelocation-model");8655    CmdArgs.push_back(RMName);8656  }8657 8658  // Optionally embed the -cc1as level arguments into the debug info, for build8659  // analysis.8660  if (getToolChain().UseDwarfDebugFlags()) {8661    ArgStringList OriginalArgs;8662    for (const auto &Arg : Args)8663      Arg->render(Args, OriginalArgs);8664 8665    SmallString<256> Flags;8666    const char *Exec = getToolChain().getDriver().getClangProgramPath();8667    escapeSpacesAndBackslashes(Exec, Flags);8668    for (const char *OriginalArg : OriginalArgs) {8669      SmallString<128> EscapedArg;8670      escapeSpacesAndBackslashes(OriginalArg, EscapedArg);8671      Flags += " ";8672      Flags += EscapedArg;8673    }8674    CmdArgs.push_back("-dwarf-debug-flags");8675    CmdArgs.push_back(Args.MakeArgString(Flags));8676  }8677 8678  // FIXME: Add -static support, once we have it.8679 8680  // Add target specific flags.8681  switch (getToolChain().getArch()) {8682  default:8683    break;8684 8685  case llvm::Triple::mips:8686  case llvm::Triple::mipsel:8687  case llvm::Triple::mips64:8688  case llvm::Triple::mips64el:8689    AddMIPSTargetArgs(Args, CmdArgs);8690    break;8691 8692  case llvm::Triple::x86:8693  case llvm::Triple::x86_64:8694    AddX86TargetArgs(Args, CmdArgs);8695    break;8696 8697  case llvm::Triple::arm:8698  case llvm::Triple::armeb:8699  case llvm::Triple::thumb:8700  case llvm::Triple::thumbeb:8701    // This isn't in AddARMTargetArgs because we want to do this for assembly8702    // only, not C/C++.8703    if (Args.hasFlag(options::OPT_mdefault_build_attributes,8704                     options::OPT_mno_default_build_attributes, true)) {8705        CmdArgs.push_back("-mllvm");8706        CmdArgs.push_back("-arm-add-build-attributes");8707    }8708    break;8709 8710  case llvm::Triple::aarch64:8711  case llvm::Triple::aarch64_32:8712  case llvm::Triple::aarch64_be:8713    if (Args.hasArg(options::OPT_mmark_bti_property)) {8714      CmdArgs.push_back("-mllvm");8715      CmdArgs.push_back("-aarch64-mark-bti-property");8716    }8717    break;8718 8719  case llvm::Triple::loongarch32:8720  case llvm::Triple::loongarch64:8721    AddLoongArchTargetArgs(Args, CmdArgs);8722    break;8723 8724  case llvm::Triple::riscv32:8725  case llvm::Triple::riscv64:8726    AddRISCVTargetArgs(Args, CmdArgs);8727    break;8728 8729  case llvm::Triple::hexagon:8730    if (Args.hasFlag(options::OPT_mdefault_build_attributes,8731                     options::OPT_mno_default_build_attributes, true)) {8732      CmdArgs.push_back("-mllvm");8733      CmdArgs.push_back("-hexagon-add-build-attributes");8734    }8735    break;8736  }8737 8738  // Consume all the warning flags. Usually this would be handled more8739  // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as8740  // doesn't handle that so rather than warning about unused flags that are8741  // actually used, we'll lie by omission instead.8742  // FIXME: Stop lying and consume only the appropriate driver flags8743  Args.ClaimAllArgs(options::OPT_W_Group);8744 8745  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,8746                                    getToolChain().getDriver());8747 8748  // Forward -Xclangas arguments to -cc1as8749  for (auto Arg : Args.filtered(options::OPT_Xclangas)) {8750    Arg->claim();8751    CmdArgs.push_back(Arg->getValue());8752  }8753 8754  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);8755 8756  if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())8757    addDebugObjectName(Args, CmdArgs, DebugCompilationDir,8758                       Output.getFilename());8759 8760  // Fixup any previous commands that use -object-file-name because when we8761  // generated them, the final .obj name wasn't yet known.8762  for (Command &J : C.getJobs()) {8763    if (SourceAction != FindSource(&J.getSource()))8764      continue;8765    auto &JArgs = J.getArguments();8766    for (unsigned I = 0; I < JArgs.size(); ++I) {8767      if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&8768          Output.isFilename()) {8769       ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);8770       addDebugObjectName(Args, NewArgs, DebugCompilationDir,8771                          Output.getFilename());8772       NewArgs.append(JArgs.begin() + I + 1, JArgs.end());8773       J.replaceArguments(NewArgs);8774       break;8775      }8776    }8777  }8778 8779  assert(Output.isFilename() && "Unexpected lipo output.");8780  CmdArgs.push_back("-o");8781  CmdArgs.push_back(Output.getFilename());8782 8783  const llvm::Triple &T = getToolChain().getTriple();8784  Arg *A;8785  if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&8786      T.isOSBinFormatELF()) {8787    CmdArgs.push_back("-split-dwarf-output");8788    CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));8789  }8790 8791  if (Triple.isAMDGPU())8792    handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);8793 8794  assert(Input.isFilename() && "Invalid input.");8795  CmdArgs.push_back(Input.getFilename());8796 8797  const char *Exec = getToolChain().getDriver().getClangProgramPath();8798  if (D.CC1Main && !D.CCGenDiagnostics) {8799    // Invoke cc1as directly in this process.8800    C.addCommand(std::make_unique<CC1Command>(8801        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,8802        Output, D.getPrependArg()));8803  } else {8804    C.addCommand(std::make_unique<Command>(8805        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,8806        Output, D.getPrependArg()));8807  }8808}8809 8810// Begin OffloadBundler8811void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,8812                                  const InputInfo &Output,8813                                  const InputInfoList &Inputs,8814                                  const llvm::opt::ArgList &TCArgs,8815                                  const char *LinkingOutput) const {8816  // The version with only one output is expected to refer to a bundling job.8817  assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");8818 8819  // The bundling command looks like this:8820  // clang-offload-bundler -type=bc8821  //   -targets=host-triple,openmp-triple1,openmp-triple28822  //   -output=output_file8823  //   -input=unbundle_file_host8824  //   -input=unbundle_file_tgt18825  //   -input=unbundle_file_tgt28826 8827  ArgStringList CmdArgs;8828 8829  // Get the type.8830  CmdArgs.push_back(TCArgs.MakeArgString(8831      Twine("-type=") + types::getTypeTempSuffix(Output.getType())));8832 8833  assert(JA.getInputs().size() == Inputs.size() &&8834         "Not have inputs for all dependence actions??");8835 8836  // Get the targets.8837  SmallString<128> Triples;8838  Triples += "-targets=";8839  for (unsigned I = 0; I < Inputs.size(); ++I) {8840    if (I)8841      Triples += ',';8842 8843    // Find ToolChain for this input.8844    Action::OffloadKind CurKind = Action::OFK_Host;8845    const ToolChain *CurTC = &getToolChain();8846    const Action *CurDep = JA.getInputs()[I];8847 8848    if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {8849      CurTC = nullptr;8850      OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {8851        assert(CurTC == nullptr && "Expected one dependence!");8852        CurKind = A->getOffloadingDeviceKind();8853        CurTC = TC;8854      });8855    }8856    Triples += Action::GetOffloadKindName(CurKind);8857    Triples += '-';8858    Triples +=8859        CurTC->getTriple().normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);8860    if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&8861        !StringRef(CurDep->getOffloadingArch()).empty()) {8862      Triples += '-';8863      Triples += CurDep->getOffloadingArch();8864    }8865 8866    // TODO: Replace parsing of -march flag. Can be done by storing GPUArch8867    //       with each toolchain.8868    StringRef GPUArchName;8869    if (CurKind == Action::OFK_OpenMP) {8870      // Extract GPUArch from -march argument in TC argument list.8871      for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {8872        auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));8873        auto Arch = ArchStr.starts_with_insensitive("-march=");8874        if (Arch) {8875          GPUArchName = ArchStr.substr(7);8876          Triples += "-";8877          break;8878        }8879      }8880      Triples += GPUArchName.str();8881    }8882  }8883  CmdArgs.push_back(TCArgs.MakeArgString(Triples));8884 8885  // Get bundled file command.8886  CmdArgs.push_back(8887      TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));8888 8889  // Get unbundled files command.8890  for (unsigned I = 0; I < Inputs.size(); ++I) {8891    SmallString<128> UB;8892    UB += "-input=";8893 8894    // Find ToolChain for this input.8895    const ToolChain *CurTC = &getToolChain();8896    if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {8897      CurTC = nullptr;8898      OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {8899        assert(CurTC == nullptr && "Expected one dependence!");8900        CurTC = TC;8901      });8902      UB += C.addTempFile(8903          C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));8904    } else {8905      UB += CurTC->getInputFilename(Inputs[I]);8906    }8907    CmdArgs.push_back(TCArgs.MakeArgString(UB));8908  }8909  addOffloadCompressArgs(TCArgs, CmdArgs);8910  // All the inputs are encoded as commands.8911  C.addCommand(std::make_unique<Command>(8912      JA, *this, ResponseFileSupport::None(),8913      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),8914      CmdArgs, ArrayRef<InputInfo>(), Output));8915}8916 8917void OffloadBundler::ConstructJobMultipleOutputs(8918    Compilation &C, const JobAction &JA, const InputInfoList &Outputs,8919    const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,8920    const char *LinkingOutput) const {8921  // The version with multiple outputs is expected to refer to a unbundling job.8922  auto &UA = cast<OffloadUnbundlingJobAction>(JA);8923 8924  // The unbundling command looks like this:8925  // clang-offload-bundler -type=bc8926  //   -targets=host-triple,openmp-triple1,openmp-triple28927  //   -input=input_file8928  //   -output=unbundle_file_host8929  //   -output=unbundle_file_tgt18930  //   -output=unbundle_file_tgt28931  //   -unbundle8932 8933  ArgStringList CmdArgs;8934 8935  assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");8936  InputInfo Input = Inputs.front();8937 8938  // Get the type.8939  CmdArgs.push_back(TCArgs.MakeArgString(8940      Twine("-type=") + types::getTypeTempSuffix(Input.getType())));8941 8942  // Get the targets.8943  SmallString<128> Triples;8944  Triples += "-targets=";8945  auto DepInfo = UA.getDependentActionsInfo();8946  for (unsigned I = 0; I < DepInfo.size(); ++I) {8947    if (I)8948      Triples += ',';8949 8950    auto &Dep = DepInfo[I];8951    Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);8952    Triples += '-';8953    Triples += Dep.DependentToolChain->getTriple().normalize(8954        llvm::Triple::CanonicalForm::FOUR_IDENT);8955    if ((Dep.DependentOffloadKind == Action::OFK_HIP ||8956         Dep.DependentOffloadKind == Action::OFK_Cuda) &&8957        !Dep.DependentBoundArch.empty()) {8958      Triples += '-';8959      Triples += Dep.DependentBoundArch;8960    }8961    // TODO: Replace parsing of -march flag. Can be done by storing GPUArch8962    //       with each toolchain.8963    StringRef GPUArchName;8964    if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {8965      // Extract GPUArch from -march argument in TC argument list.8966      for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {8967        StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));8968        auto Arch = ArchStr.starts_with_insensitive("-march=");8969        if (Arch) {8970          GPUArchName = ArchStr.substr(7);8971          Triples += "-";8972          break;8973        }8974      }8975      Triples += GPUArchName.str();8976    }8977  }8978 8979  CmdArgs.push_back(TCArgs.MakeArgString(Triples));8980 8981  // Get bundled file command.8982  CmdArgs.push_back(8983      TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));8984 8985  // Get unbundled files command.8986  for (unsigned I = 0; I < Outputs.size(); ++I) {8987    SmallString<128> UB;8988    UB += "-output=";8989    UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);8990    CmdArgs.push_back(TCArgs.MakeArgString(UB));8991  }8992  CmdArgs.push_back("-unbundle");8993  CmdArgs.push_back("-allow-missing-bundles");8994  if (TCArgs.hasArg(options::OPT_v))8995    CmdArgs.push_back("-verbose");8996 8997  // All the inputs are encoded as commands.8998  C.addCommand(std::make_unique<Command>(8999      JA, *this, ResponseFileSupport::None(),9000      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),9001      CmdArgs, ArrayRef<InputInfo>(), Outputs));9002}9003 9004void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,9005                                   const InputInfo &Output,9006                                   const InputInfoList &Inputs,9007                                   const llvm::opt::ArgList &Args,9008                                   const char *LinkingOutput) const {9009  ArgStringList CmdArgs;9010 9011  // Add the output file name.9012  assert(Output.isFilename() && "Invalid output.");9013  CmdArgs.push_back("-o");9014  CmdArgs.push_back(Output.getFilename());9015 9016  // Create the inputs to bundle the needed metadata.9017  for (const InputInfo &Input : Inputs) {9018    const Action *OffloadAction = Input.getAction();9019    const ToolChain *TC = OffloadAction->getOffloadingToolChain();9020    const ArgList &TCArgs =9021        C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),9022                              OffloadAction->getOffloadingDeviceKind());9023    StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));9024    StringRef Arch = OffloadAction->getOffloadingArch()9025                         ? OffloadAction->getOffloadingArch()9026                         : TCArgs.getLastArgValue(options::OPT_march_EQ);9027    StringRef Kind =9028      Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());9029 9030    ArgStringList Features;9031    SmallVector<StringRef> FeatureArgs;9032    getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,9033                      false);9034    llvm::copy_if(Features, std::back_inserter(FeatureArgs),9035                  [](StringRef Arg) { return !Arg.starts_with("-target"); });9036 9037    // TODO: We need to pass in the full target-id and handle it properly in the9038    // linker wrapper.9039    SmallVector<std::string> Parts{9040        "file=" + File.str(),9041        "triple=" + TC->getTripleString(),9042        "arch=" + (Arch.empty() ? "generic" : Arch.str()),9043        "kind=" + Kind.str(),9044    };9045 9046    if (TC->getDriver().isUsingOffloadLTO())9047      for (StringRef Feature : FeatureArgs)9048        Parts.emplace_back("feature=" + Feature.str());9049 9050    CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));9051  }9052 9053  C.addCommand(std::make_unique<Command>(9054      JA, *this, ResponseFileSupport::None(),9055      Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),9056      CmdArgs, Inputs, Output));9057}9058 9059void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,9060                                 const InputInfo &Output,9061                                 const InputInfoList &Inputs,9062                                 const ArgList &Args,9063                                 const char *LinkingOutput) const {9064  using namespace options;9065 9066  // A list of permitted options that will be forwarded to the embedded device9067  // compilation job.9068  const llvm::DenseSet<unsigned> CompilerOptions{9069      OPT_v,9070      OPT_cuda_path_EQ,9071      OPT_rocm_path_EQ,9072      OPT_O_Group,9073      OPT_g_Group,9074      OPT_g_flags_Group,9075      OPT_R_value_Group,9076      OPT_R_Group,9077      OPT_Xcuda_ptxas,9078      OPT_ftime_report,9079      OPT_ftime_trace,9080      OPT_ftime_trace_EQ,9081      OPT_ftime_trace_granularity_EQ,9082      OPT_ftime_trace_verbose,9083      OPT_opt_record_file,9084      OPT_opt_record_format,9085      OPT_opt_record_passes,9086      OPT_fsave_optimization_record,9087      OPT_fsave_optimization_record_EQ,9088      OPT_fno_save_optimization_record,9089      OPT_foptimization_record_file_EQ,9090      OPT_foptimization_record_passes_EQ,9091      OPT_save_temps,9092      OPT_save_temps_EQ,9093      OPT_mcode_object_version_EQ,9094      OPT_load,9095      OPT_fno_lto,9096      OPT_flto,9097      OPT_flto_partitions_EQ,9098      OPT_flto_EQ,9099      OPT_use_spirv_backend};9100 9101  const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};9102  auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {9103    // Don't forward -mllvm to toolchains that don't support LLVM.9104    return TC.HasNativeLLVMSupport() || A->getOption().getID() != OPT_mllvm;9105  };9106  auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,9107                           const ToolChain &TC) {9108    // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.9109    if (A->getOption().matches(OPT_v) && JA.getType() == types::TY_HIP_FATBIN)9110      return false;9111    return (Set.contains(A->getOption().getID()) ||9112            (A->getOption().getGroup().isValid() &&9113             Set.contains(A->getOption().getGroup().getID()))) &&9114           ShouldForwardForToolChain(A, TC);9115  };9116 9117  ArgStringList CmdArgs;9118  for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,9119                                   Action::OFK_HIP, Action::OFK_SYCL}) {9120    auto TCRange = C.getOffloadToolChains(Kind);9121    for (auto &I : llvm::make_range(TCRange)) {9122      const ToolChain *TC = I.second;9123 9124      // We do not use a bound architecture here so options passed only to a9125      // specific architecture via -Xarch_<cpu> will not be forwarded.9126      ArgStringList CompilerArgs;9127      ArgStringList LinkerArgs;9128      const DerivedArgList &ToolChainArgs =9129          C.getArgsForToolChain(TC, /*BoundArch=*/"", Kind);9130      for (Arg *A : ToolChainArgs) {9131        if (A->getOption().matches(OPT_Zlinker_input))9132          LinkerArgs.emplace_back(A->getValue());9133        else if (ShouldForward(CompilerOptions, A, *TC))9134          A->render(Args, CompilerArgs);9135        else if (ShouldForward(LinkerOptions, A, *TC))9136          A->render(Args, LinkerArgs);9137      }9138 9139      // If the user explicitly requested it via `--offload-arch` we should9140      // extract it from any static libraries if present.9141      for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))9142        CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));9143 9144      // If this is OpenMP the device linker will need `-lompdevice`.9145      if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&9146          (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))9147        LinkerArgs.emplace_back("-lompdevice");9148 9149      // Forward all of these to the appropriate toolchain.9150      for (StringRef Arg : CompilerArgs)9151        CmdArgs.push_back(Args.MakeArgString(9152            "--device-compiler=" + TC->getTripleString() + "=" + Arg));9153      for (StringRef Arg : LinkerArgs)9154        CmdArgs.push_back(Args.MakeArgString(9155            "--device-linker=" + TC->getTripleString() + "=" + Arg));9156 9157      // Forward the LTO mode relying on the Driver's parsing.9158      if (C.getDriver().getOffloadLTOMode() == LTOK_Full)9159        CmdArgs.push_back(Args.MakeArgString(9160            "--device-compiler=" + TC->getTripleString() + "=-flto=full"));9161      else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {9162        CmdArgs.push_back(Args.MakeArgString(9163            "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));9164        if (TC->getTriple().isAMDGPU()) {9165          CmdArgs.push_back(9166              Args.MakeArgString("--device-linker=" + TC->getTripleString() +9167                                 "=-plugin-opt=-force-import-all"));9168          CmdArgs.push_back(9169              Args.MakeArgString("--device-linker=" + TC->getTripleString() +9170                                 "=-plugin-opt=-avail-extern-to-local"));9171          CmdArgs.push_back(Args.MakeArgString(9172              "--device-linker=" + TC->getTripleString() +9173              "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));9174          if (Kind == Action::OFK_OpenMP) {9175            CmdArgs.push_back(9176                Args.MakeArgString("--device-linker=" + TC->getTripleString() +9177                                   "=-plugin-opt=-amdgpu-internalize-symbols"));9178          }9179        }9180      }9181    }9182  }9183 9184  CmdArgs.push_back(9185      Args.MakeArgString("--host-triple=" + getToolChain().getTripleString()));9186 9187  // CMake hack, suppress passing verbose arguments for the special-case HIP9188  // non-RDC mode compilation. This confuses default CMake implicit linker9189  // argument parsing when the language is set to HIP and the system linker is9190  // also `ld.lld`.9191  if (Args.hasArg(options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)9192    CmdArgs.push_back("--wrapper-verbose");9193  if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ))9194    CmdArgs.push_back(9195        Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));9196 9197  // Construct the link job so we can wrap around it.9198  Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);9199  const auto &LinkCommand = C.getJobs().getJobs().back();9200 9201  // Forward -Xoffload-linker<-triple> arguments to the device link job.9202  for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {9203    StringRef Val = A->getValue(0);9204    if (Val.empty())9205      CmdArgs.push_back(9206          Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));9207    else9208      CmdArgs.push_back(Args.MakeArgString(9209          "--device-linker=" +9210          ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +9211          A->getValue(1)));9212  }9213  Args.ClaimAllArgs(options::OPT_Xoffload_linker);9214 9215  // Embed bitcode instead of an object in JIT mode.9216  if (Args.hasFlag(options::OPT_fopenmp_target_jit,9217                   options::OPT_fno_openmp_target_jit, false))9218    CmdArgs.push_back("--embed-bitcode");9219 9220  // Save temporary files created by the linker wrapper.9221  if (Args.hasArg(options::OPT_save_temps_EQ) ||9222      Args.hasArg(options::OPT_save_temps))9223    CmdArgs.push_back("--save-temps");9224 9225  // Pass in the C library for GPUs if present and not disabled.9226  if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&9227      !Args.hasArg(options::OPT_nostdlib, options::OPT_r,9228                   options::OPT_nodefaultlibs, options::OPT_nolibc,9229                   options::OPT_nogpulibc)) {9230    forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {9231      // The device C library is only available for NVPTX and AMDGPU targets9232      // and we only link it by default for OpenMP currently.9233      if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||9234          !JA.isHostOffloading(Action::OFK_OpenMP))9235        return;9236      bool HasLibC = TC.getStdlibIncludePath().has_value();9237      if (HasLibC) {9238        CmdArgs.push_back(Args.MakeArgString(9239            "--device-linker=" + TC.getTripleString() + "=" + "-lc"));9240        CmdArgs.push_back(Args.MakeArgString(9241            "--device-linker=" + TC.getTripleString() + "=" + "-lm"));9242      }9243      auto HasCompilerRT = getToolChain().getVFS().exists(9244          TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static));9245      if (HasCompilerRT)9246        CmdArgs.push_back(9247            Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +9248                               "-lclang_rt.builtins"));9249      bool HasFlangRT = HasCompilerRT && C.getDriver().IsFlangMode();9250      if (HasFlangRT)9251        CmdArgs.push_back(9252            Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +9253                               "-lflang_rt.runtime"));9254    });9255  }9256 9257  // Add the linker arguments to be forwarded by the wrapper.9258  CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +9259                                       LinkCommand->getExecutable()));9260 9261  // We use action type to differentiate two use cases of the linker wrapper.9262  // TY_Image for normal linker wrapper work.9263  // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.9264  assert(JA.getType() == types::TY_HIP_FATBIN ||9265         JA.getType() == types::TY_Image);9266  if (JA.getType() == types::TY_HIP_FATBIN) {9267    CmdArgs.push_back("--emit-fatbin-only");9268    CmdArgs.append({"-o", Output.getFilename()});9269    for (auto Input : Inputs)9270      CmdArgs.push_back(Input.getFilename());9271  } else9272    for (const char *LinkArg : LinkCommand->getArguments())9273      CmdArgs.push_back(LinkArg);9274 9275  addOffloadCompressArgs(Args, CmdArgs);9276 9277  if (Arg *A = Args.getLastArg(options::OPT_offload_jobs_EQ)) {9278    StringRef Val = A->getValue();9279 9280    if (Val.equals_insensitive("jobserver"))9281      CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));9282    else {9283      int NumThreads;9284      if (Val.getAsInteger(10, NumThreads) || NumThreads <= 0) {9285        C.getDriver().Diag(diag::err_drv_invalid_int_value)9286            << A->getAsString(Args) << Val;9287      } else {9288        CmdArgs.push_back(9289            Args.MakeArgString("--wrapper-jobs=" + Twine(NumThreads)));9290      }9291    }9292  }9293 9294  const char *Exec =9295      Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));9296 9297  // Replace the executable and arguments of the link job with the9298  // wrapper.9299  LinkCommand->replaceExecutable(Exec);9300  LinkCommand->replaceArguments(CmdArgs);9301}9302