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