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