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