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