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