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