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