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