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