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