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