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 Driver &D, const llvm::Triple &Triple, 1592 const ArgList &Args, 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(D, 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(getToolChain().getDriver(), 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 const llvm::DenormalMode DefaultDenormalFPMath = 2636 TC.getDefaultDenormalModeForType(Args, JA); 2637 const llvm::DenormalMode DefaultDenormalFP32Math = 2638 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle()); 2639 2640 llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath; 2641 llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math; 2642 StringRef FPContract = ""; 2643 bool StrictFPModel = false; 2644 2645 2646 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) { 2647 CmdArgs.push_back("-mlimit-float-precision"); 2648 CmdArgs.push_back(A->getValue()); 2649 } 2650 2651 for (const Arg *A : Args) { 2652 auto optID = A->getOption().getID(); 2653 bool PreciseFPModel = false; 2654 switch (optID) { 2655 default: 2656 break; 2657 case options::OPT_ffp_model_EQ: { 2658 // If -ffp-model= is seen, reset to fno-fast-math 2659 HonorINFs = true; 2660 HonorNaNs = true; 2661 // Turning *off* -ffast-math restores the toolchain default. 2662 MathErrno = TC.IsMathErrnoDefault(); 2663 AssociativeMath = false; 2664 ReciprocalMath = false; 2665 SignedZeros = true; 2666 // -fno_fast_math restores default denormal and fpcontract handling 2667 FPContract = ""; 2668 DenormalFPMath = llvm::DenormalMode::getIEEE(); 2669 2670 // FIXME: The target may have picked a non-IEEE default mode here based on 2671 // -cl-denorms-are-zero. Should the target consider -fp-model interaction? 2672 DenormalFP32Math = llvm::DenormalMode::getIEEE(); 2673 2674 StringRef Val = A->getValue(); 2675 if (OFastEnabled && !Val.equals("fast")) { 2676 // Only -ffp-model=fast is compatible with OFast, ignore. 2677 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2678 << Args.MakeArgString("-ffp-model=" + Val) 2679 << "-Ofast"; 2680 break; 2681 } 2682 StrictFPModel = false; 2683 PreciseFPModel = true; 2684 // ffp-model= is a Driver option, it is entirely rewritten into more 2685 // granular options before being passed into cc1. 2686 // Use the gcc option in the switch below. 2687 if (!FPModel.empty() && !FPModel.equals(Val)) { 2688 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2689 << Args.MakeArgString("-ffp-model=" + FPModel) 2690 << Args.MakeArgString("-ffp-model=" + Val); 2691 FPContract = ""; 2692 } 2693 if (Val.equals("fast")) { 2694 optID = options::OPT_ffast_math; 2695 FPModel = Val; 2696 FPContract = "fast"; 2697 } else if (Val.equals("precise")) { 2698 optID = options::OPT_ffp_contract; 2699 FPModel = Val; 2700 FPContract = "fast"; 2701 PreciseFPModel = true; 2702 } else if (Val.equals("strict")) { 2703 StrictFPModel = true; 2704 optID = options::OPT_frounding_math; 2705 FPExceptionBehavior = "strict"; 2706 FPModel = Val; 2707 FPContract = "off"; 2708 TrappingMath = true; 2709 } else 2710 D.Diag(diag::err_drv_unsupported_option_argument) 2711 << A->getOption().getName() << Val; 2712 break; 2713 } 2714 } 2715 2716 switch (optID) { 2717 // If this isn't an FP option skip the claim below 2718 default: continue; 2719 2720 // Options controlling individual features 2721 case options::OPT_fhonor_infinities: HonorINFs = true; break; 2722 case options::OPT_fno_honor_infinities: HonorINFs = false; break; 2723 case options::OPT_fhonor_nans: HonorNaNs = true; break; 2724 case options::OPT_fno_honor_nans: HonorNaNs = false; break; 2725 case options::OPT_fmath_errno: MathErrno = true; break; 2726 case options::OPT_fno_math_errno: MathErrno = false; break; 2727 case options::OPT_fassociative_math: AssociativeMath = true; break; 2728 case options::OPT_fno_associative_math: AssociativeMath = false; break; 2729 case options::OPT_freciprocal_math: ReciprocalMath = true; break; 2730 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break; 2731 case options::OPT_fsigned_zeros: SignedZeros = true; break; 2732 case options::OPT_fno_signed_zeros: SignedZeros = false; break; 2733 case options::OPT_ftrapping_math: 2734 if (!TrappingMathPresent && !FPExceptionBehavior.empty() && 2735 !FPExceptionBehavior.equals("strict")) 2736 // Warn that previous value of option is overridden. 2737 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2738 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior) 2739 << "-ftrapping-math"; 2740 TrappingMath = true; 2741 TrappingMathPresent = true; 2742 FPExceptionBehavior = "strict"; 2743 break; 2744 case options::OPT_fno_trapping_math: 2745 if (!TrappingMathPresent && !FPExceptionBehavior.empty() && 2746 !FPExceptionBehavior.equals("ignore")) 2747 // Warn that previous value of option is overridden. 2748 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2749 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior) 2750 << "-fno-trapping-math"; 2751 TrappingMath = false; 2752 TrappingMathPresent = true; 2753 FPExceptionBehavior = "ignore"; 2754 break; 2755 2756 case options::OPT_frounding_math: 2757 RoundingFPMath = true; 2758 RoundingMathPresent = true; 2759 break; 2760 2761 case options::OPT_fno_rounding_math: 2762 RoundingFPMath = false; 2763 RoundingMathPresent = false; 2764 break; 2765 2766 case options::OPT_fdenormal_fp_math_EQ: 2767 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue()); 2768 if (!DenormalFPMath.isValid()) { 2769 D.Diag(diag::err_drv_invalid_value) 2770 << A->getAsString(Args) << A->getValue(); 2771 } 2772 break; 2773 2774 case options::OPT_fdenormal_fp_math_f32_EQ: 2775 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue()); 2776 if (!DenormalFP32Math.isValid()) { 2777 D.Diag(diag::err_drv_invalid_value) 2778 << A->getAsString(Args) << A->getValue(); 2779 } 2780 break; 2781 2782 // Validate and pass through -ffp-contract option. 2783 case options::OPT_ffp_contract: { 2784 StringRef Val = A->getValue(); 2785 if (PreciseFPModel) { 2786 // -ffp-model=precise enables ffp-contract=fast as a side effect 2787 // the FPContract value has already been set to a string literal 2788 // and the Val string isn't a pertinent value. 2789 ; 2790 } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) 2791 FPContract = Val; 2792 else 2793 D.Diag(diag::err_drv_unsupported_option_argument) 2794 << A->getOption().getName() << Val; 2795 break; 2796 } 2797 2798 // Validate and pass through -ffp-model option. 2799 case options::OPT_ffp_model_EQ: 2800 // This should only occur in the error case 2801 // since the optID has been replaced by a more granular 2802 // floating point option. 2803 break; 2804 2805 // Validate and pass through -ffp-exception-behavior option. 2806 case options::OPT_ffp_exception_behavior_EQ: { 2807 StringRef Val = A->getValue(); 2808 if (!TrappingMathPresent && !FPExceptionBehavior.empty() && 2809 !FPExceptionBehavior.equals(Val)) 2810 // Warn that previous value of option is overridden. 2811 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2812 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior) 2813 << Args.MakeArgString("-ffp-exception-behavior=" + Val); 2814 TrappingMath = TrappingMathPresent = false; 2815 if (Val.equals("ignore") || Val.equals("maytrap")) 2816 FPExceptionBehavior = Val; 2817 else if (Val.equals("strict")) { 2818 FPExceptionBehavior = Val; 2819 TrappingMath = TrappingMathPresent = true; 2820 } else 2821 D.Diag(diag::err_drv_unsupported_option_argument) 2822 << A->getOption().getName() << Val; 2823 break; 2824 } 2825 2826 case options::OPT_ffinite_math_only: 2827 HonorINFs = false; 2828 HonorNaNs = false; 2829 break; 2830 case options::OPT_fno_finite_math_only: 2831 HonorINFs = true; 2832 HonorNaNs = true; 2833 break; 2834 2835 case options::OPT_funsafe_math_optimizations: 2836 AssociativeMath = true; 2837 ReciprocalMath = true; 2838 SignedZeros = false; 2839 TrappingMath = false; 2840 FPExceptionBehavior = ""; 2841 break; 2842 case options::OPT_fno_unsafe_math_optimizations: 2843 AssociativeMath = false; 2844 ReciprocalMath = false; 2845 SignedZeros = true; 2846 TrappingMath = true; 2847 FPExceptionBehavior = "strict"; 2848 2849 // The target may have opted to flush by default, so force IEEE. 2850 DenormalFPMath = llvm::DenormalMode::getIEEE(); 2851 DenormalFP32Math = llvm::DenormalMode::getIEEE(); 2852 break; 2853 2854 case options::OPT_Ofast: 2855 // If -Ofast is the optimization level, then -ffast-math should be enabled 2856 if (!OFastEnabled) 2857 continue; 2858 LLVM_FALLTHROUGH; 2859 case options::OPT_ffast_math: 2860 HonorINFs = false; 2861 HonorNaNs = false; 2862 MathErrno = false; 2863 AssociativeMath = true; 2864 ReciprocalMath = true; 2865 SignedZeros = false; 2866 TrappingMath = false; 2867 RoundingFPMath = false; 2868 // If fast-math is set then set the fp-contract mode to fast. 2869 FPContract = "fast"; 2870 break; 2871 case options::OPT_fno_fast_math: 2872 HonorINFs = true; 2873 HonorNaNs = true; 2874 // Turning on -ffast-math (with either flag) removes the need for 2875 // MathErrno. However, turning *off* -ffast-math merely restores the 2876 // toolchain default (which may be false). 2877 MathErrno = TC.IsMathErrnoDefault(); 2878 AssociativeMath = false; 2879 ReciprocalMath = false; 2880 SignedZeros = true; 2881 TrappingMath = false; 2882 RoundingFPMath = false; 2883 // -fno_fast_math restores default denormal and fpcontract handling 2884 DenormalFPMath = DefaultDenormalFPMath; 2885 DenormalFP32Math = llvm::DenormalMode::getIEEE(); 2886 FPContract = ""; 2887 break; 2888 } 2889 if (StrictFPModel) { 2890 // If -ffp-model=strict has been specified on command line but 2891 // subsequent options conflict then emit warning diagnostic. 2892 if (HonorINFs && HonorNaNs && 2893 !AssociativeMath && !ReciprocalMath && 2894 SignedZeros && TrappingMath && RoundingFPMath && 2895 (FPContract.equals("off") || FPContract.empty()) && 2896 DenormalFPMath == llvm::DenormalMode::getIEEE() && 2897 DenormalFP32Math == llvm::DenormalMode::getIEEE()) 2898 // OK: Current Arg doesn't conflict with -ffp-model=strict 2899 ; 2900 else { 2901 StrictFPModel = false; 2902 FPModel = ""; 2903 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2904 << "-ffp-model=strict" << 2905 ((A->getNumValues() == 0) ? A->getSpelling() 2906 : Args.MakeArgString(A->getSpelling() + A->getValue())); 2907 } 2908 } 2909 2910 // If we handled this option claim it 2911 A->claim(); 2912 } 2913 2914 if (!HonorINFs) 2915 CmdArgs.push_back("-menable-no-infs"); 2916 2917 if (!HonorNaNs) 2918 CmdArgs.push_back("-menable-no-nans"); 2919 2920 if (MathErrno) 2921 CmdArgs.push_back("-fmath-errno"); 2922 2923 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros && 2924 !TrappingMath) 2925 CmdArgs.push_back("-menable-unsafe-fp-math"); 2926 2927 if (!SignedZeros) 2928 CmdArgs.push_back("-fno-signed-zeros"); 2929 2930 if (AssociativeMath && !SignedZeros && !TrappingMath) 2931 CmdArgs.push_back("-mreassociate"); 2932 2933 if (ReciprocalMath) 2934 CmdArgs.push_back("-freciprocal-math"); 2935 2936 if (TrappingMath) { 2937 // FP Exception Behavior is also set to strict 2938 assert(FPExceptionBehavior.equals("strict")); 2939 } 2940 2941 // The default is IEEE. 2942 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) { 2943 llvm::SmallString<64> DenormFlag; 2944 llvm::raw_svector_ostream ArgStr(DenormFlag); 2945 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath; 2946 CmdArgs.push_back(Args.MakeArgString(ArgStr.str())); 2947 } 2948 2949 // Add f32 specific denormal mode flag if it's different. 2950 if (DenormalFP32Math != DenormalFPMath) { 2951 llvm::SmallString<64> DenormFlag; 2952 llvm::raw_svector_ostream ArgStr(DenormFlag); 2953 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math; 2954 CmdArgs.push_back(Args.MakeArgString(ArgStr.str())); 2955 } 2956 2957 if (!FPContract.empty()) 2958 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract)); 2959 2960 if (!RoundingFPMath) 2961 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math")); 2962 2963 if (RoundingFPMath && RoundingMathPresent) 2964 CmdArgs.push_back(Args.MakeArgString("-frounding-math")); 2965 2966 if (!FPExceptionBehavior.empty()) 2967 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" + 2968 FPExceptionBehavior)); 2969 2970 ParseMRecip(D, Args, CmdArgs); 2971 2972 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the 2973 // individual features enabled by -ffast-math instead of the option itself as 2974 // that's consistent with gcc's behaviour. 2975 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && 2976 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) { 2977 CmdArgs.push_back("-ffast-math"); 2978 if (FPModel.equals("fast")) { 2979 if (FPContract.equals("fast")) 2980 // All set, do nothing. 2981 ; 2982 else if (FPContract.empty()) 2983 // Enable -ffp-contract=fast 2984 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast")); 2985 else 2986 D.Diag(clang::diag::warn_drv_overriding_flag_option) 2987 << "-ffp-model=fast" 2988 << Args.MakeArgString("-ffp-contract=" + FPContract); 2989 } 2990 } 2991 2992 // Handle __FINITE_MATH_ONLY__ similarly. 2993 if (!HonorINFs && !HonorNaNs) 2994 CmdArgs.push_back("-ffinite-math-only"); 2995 2996 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) { 2997 CmdArgs.push_back("-mfpmath"); 2998 CmdArgs.push_back(A->getValue()); 2999 } 3000 3001 // Disable a codegen optimization for floating-point casts. 3002 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow, 3003 options::OPT_fstrict_float_cast_overflow, false)) 3004 CmdArgs.push_back("-fno-strict-float-cast-overflow"); 3005 } 3006 3007 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, 3008 const llvm::Triple &Triple, 3009 const InputInfo &Input) { 3010 // Enable region store model by default. 3011 CmdArgs.push_back("-analyzer-store=region"); 3012 3013 // Treat blocks as analysis entry points. 3014 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks"); 3015 3016 // Add default argument set. 3017 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) { 3018 CmdArgs.push_back("-analyzer-checker=core"); 3019 CmdArgs.push_back("-analyzer-checker=apiModeling"); 3020 3021 if (!Triple.isWindowsMSVCEnvironment()) { 3022 CmdArgs.push_back("-analyzer-checker=unix"); 3023 } else { 3024 // Enable "unix" checkers that also work on Windows. 3025 CmdArgs.push_back("-analyzer-checker=unix.API"); 3026 CmdArgs.push_back("-analyzer-checker=unix.Malloc"); 3027 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof"); 3028 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator"); 3029 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg"); 3030 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg"); 3031 } 3032 3033 // Disable some unix checkers for PS4. 3034 if (Triple.isPS4CPU()) { 3035 CmdArgs.push_back("-analyzer-disable-checker=unix.API"); 3036 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork"); 3037 } 3038 3039 if (Triple.isOSDarwin()) { 3040 CmdArgs.push_back("-analyzer-checker=osx"); 3041 CmdArgs.push_back( 3042 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType"); 3043 } 3044 else if (Triple.isOSFuchsia()) 3045 CmdArgs.push_back("-analyzer-checker=fuchsia"); 3046 3047 CmdArgs.push_back("-analyzer-checker=deadcode"); 3048 3049 if (types::isCXX(Input.getType())) 3050 CmdArgs.push_back("-analyzer-checker=cplusplus"); 3051 3052 if (!Triple.isPS4CPU()) { 3053 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn"); 3054 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw"); 3055 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets"); 3056 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp"); 3057 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp"); 3058 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork"); 3059 } 3060 3061 // Default nullability checks. 3062 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull"); 3063 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull"); 3064 } 3065 3066 // Set the output format. The default is plist, for (lame) historical reasons. 3067 CmdArgs.push_back("-analyzer-output"); 3068 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output)) 3069 CmdArgs.push_back(A->getValue()); 3070 else 3071 CmdArgs.push_back("plist"); 3072 3073 // Disable the presentation of standard compiler warnings when using 3074 // --analyze. We only want to show static analyzer diagnostics or frontend 3075 // errors. 3076 CmdArgs.push_back("-w"); 3077 3078 // Add -Xanalyzer arguments when running as analyzer. 3079 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); 3080 } 3081 3082 static void RenderSSPOptions(const Driver &D, const ToolChain &TC, 3083 const ArgList &Args, ArgStringList &CmdArgs, 3084 bool KernelOrKext) { 3085 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple(); 3086 3087 // NVPTX doesn't support stack protectors; from the compiler's perspective, it 3088 // doesn't even have a stack! 3089 if (EffectiveTriple.isNVPTX()) 3090 return; 3091 3092 // -stack-protector=0 is default. 3093 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff; 3094 LangOptions::StackProtectorMode DefaultStackProtectorLevel = 3095 TC.GetDefaultStackProtectorLevel(KernelOrKext); 3096 3097 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector, 3098 options::OPT_fstack_protector_all, 3099 options::OPT_fstack_protector_strong, 3100 options::OPT_fstack_protector)) { 3101 if (A->getOption().matches(options::OPT_fstack_protector)) 3102 StackProtectorLevel = 3103 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel); 3104 else if (A->getOption().matches(options::OPT_fstack_protector_strong)) 3105 StackProtectorLevel = LangOptions::SSPStrong; 3106 else if (A->getOption().matches(options::OPT_fstack_protector_all)) 3107 StackProtectorLevel = LangOptions::SSPReq; 3108 } else { 3109 StackProtectorLevel = DefaultStackProtectorLevel; 3110 } 3111 3112 if (StackProtectorLevel) { 3113 CmdArgs.push_back("-stack-protector"); 3114 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel))); 3115 } 3116 3117 // --param ssp-buffer-size= 3118 for (const Arg *A : Args.filtered(options::OPT__param)) { 3119 StringRef Str(A->getValue()); 3120 if (Str.startswith("ssp-buffer-size=")) { 3121 if (StackProtectorLevel) { 3122 CmdArgs.push_back("-stack-protector-buffer-size"); 3123 // FIXME: Verify the argument is a valid integer. 3124 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16))); 3125 } 3126 A->claim(); 3127 } 3128 } 3129 3130 const std::string &TripleStr = EffectiveTriple.getTriple(); 3131 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) { 3132 StringRef Value = A->getValue(); 3133 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64()) 3134 D.Diag(diag::err_drv_unsupported_opt_for_target) 3135 << A->getAsString(Args) << TripleStr; 3136 if (EffectiveTriple.isX86() && Value != "tls" && Value != "global") { 3137 D.Diag(diag::err_drv_invalid_value_with_suggestion) 3138 << A->getOption().getName() << Value << "tls global"; 3139 return; 3140 } 3141 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") { 3142 D.Diag(diag::err_drv_invalid_value_with_suggestion) 3143 << A->getOption().getName() << Value << "sysreg global"; 3144 return; 3145 } 3146 A->render(Args, CmdArgs); 3147 } 3148 3149 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) { 3150 StringRef Value = A->getValue(); 3151 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64()) 3152 D.Diag(diag::err_drv_unsupported_opt_for_target) 3153 << A->getAsString(Args) << TripleStr; 3154 int Offset; 3155 if (Value.getAsInteger(10, Offset)) { 3156 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value; 3157 return; 3158 } 3159 A->render(Args, CmdArgs); 3160 } 3161 3162 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) { 3163 StringRef Value = A->getValue(); 3164 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64()) 3165 D.Diag(diag::err_drv_unsupported_opt_for_target) 3166 << A->getAsString(Args) << TripleStr; 3167 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) { 3168 D.Diag(diag::err_drv_invalid_value_with_suggestion) 3169 << A->getOption().getName() << Value << "fs gs"; 3170 return; 3171 } 3172 if (EffectiveTriple.isAArch64() && Value != "sp_el0") { 3173 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value; 3174 return; 3175 } 3176 A->render(Args, CmdArgs); 3177 } 3178 } 3179 3180 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, 3181 ArgStringList &CmdArgs) { 3182 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple(); 3183 3184 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux()) 3185 return; 3186 3187 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() && 3188 !EffectiveTriple.isPPC64()) 3189 return; 3190 3191 if (Args.hasFlag(options::OPT_fstack_clash_protection, 3192 options::OPT_fno_stack_clash_protection, false)) 3193 CmdArgs.push_back("-fstack-clash-protection"); 3194 } 3195 3196 static void RenderTrivialAutoVarInitOptions(const Driver &D, 3197 const ToolChain &TC, 3198 const ArgList &Args, 3199 ArgStringList &CmdArgs) { 3200 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit(); 3201 StringRef TrivialAutoVarInit = ""; 3202 3203 for (const Arg *A : Args) { 3204 switch (A->getOption().getID()) { 3205 default: 3206 continue; 3207 case options::OPT_ftrivial_auto_var_init: { 3208 A->claim(); 3209 StringRef Val = A->getValue(); 3210 if (Val == "uninitialized" || Val == "zero" || Val == "pattern") 3211 TrivialAutoVarInit = Val; 3212 else 3213 D.Diag(diag::err_drv_unsupported_option_argument) 3214 << A->getOption().getName() << Val; 3215 break; 3216 } 3217 } 3218 } 3219 3220 if (TrivialAutoVarInit.empty()) 3221 switch (DefaultTrivialAutoVarInit) { 3222 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 3223 break; 3224 case LangOptions::TrivialAutoVarInitKind::Pattern: 3225 TrivialAutoVarInit = "pattern"; 3226 break; 3227 case LangOptions::TrivialAutoVarInitKind::Zero: 3228 TrivialAutoVarInit = "zero"; 3229 break; 3230 } 3231 3232 if (!TrivialAutoVarInit.empty()) { 3233 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero)) 3234 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled); 3235 CmdArgs.push_back( 3236 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit)); 3237 } 3238 3239 if (Arg *A = 3240 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) { 3241 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) || 3242 StringRef( 3243 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) == 3244 "uninitialized") 3245 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency); 3246 A->claim(); 3247 StringRef Val = A->getValue(); 3248 if (std::stoi(Val.str()) <= 0) 3249 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value); 3250 CmdArgs.push_back( 3251 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val)); 3252 } 3253 } 3254 3255 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, 3256 types::ID InputType) { 3257 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag 3258 // for denormal flushing handling based on the target. 3259 const unsigned ForwardedArguments[] = { 3260 options::OPT_cl_opt_disable, 3261 options::OPT_cl_strict_aliasing, 3262 options::OPT_cl_single_precision_constant, 3263 options::OPT_cl_finite_math_only, 3264 options::OPT_cl_kernel_arg_info, 3265 options::OPT_cl_unsafe_math_optimizations, 3266 options::OPT_cl_fast_relaxed_math, 3267 options::OPT_cl_mad_enable, 3268 options::OPT_cl_no_signed_zeros, 3269 options::OPT_cl_fp32_correctly_rounded_divide_sqrt, 3270 options::OPT_cl_uniform_work_group_size 3271 }; 3272 3273 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) { 3274 std::string CLStdStr = std::string("-cl-std=") + A->getValue(); 3275 CmdArgs.push_back(Args.MakeArgString(CLStdStr)); 3276 } 3277 3278 for (const auto &Arg : ForwardedArguments) 3279 if (const auto *A = Args.getLastArg(Arg)) 3280 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName())); 3281 3282 // Only add the default headers if we are compiling OpenCL sources. 3283 if ((types::isOpenCL(InputType) || 3284 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) && 3285 !Args.hasArg(options::OPT_cl_no_stdinc)) { 3286 CmdArgs.push_back("-finclude-default-header"); 3287 CmdArgs.push_back("-fdeclare-opencl-builtins"); 3288 } 3289 } 3290 3291 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args, 3292 ArgStringList &CmdArgs) { 3293 bool ARCMTEnabled = false; 3294 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) { 3295 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check, 3296 options::OPT_ccc_arcmt_modify, 3297 options::OPT_ccc_arcmt_migrate)) { 3298 ARCMTEnabled = true; 3299 switch (A->getOption().getID()) { 3300 default: llvm_unreachable("missed a case"); 3301 case options::OPT_ccc_arcmt_check: 3302 CmdArgs.push_back("-arcmt-action=check"); 3303 break; 3304 case options::OPT_ccc_arcmt_modify: 3305 CmdArgs.push_back("-arcmt-action=modify"); 3306 break; 3307 case options::OPT_ccc_arcmt_migrate: 3308 CmdArgs.push_back("-arcmt-action=migrate"); 3309 CmdArgs.push_back("-mt-migrate-directory"); 3310 CmdArgs.push_back(A->getValue()); 3311 3312 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output); 3313 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors); 3314 break; 3315 } 3316 } 3317 } else { 3318 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check); 3319 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify); 3320 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate); 3321 } 3322 3323 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) { 3324 if (ARCMTEnabled) 3325 D.Diag(diag::err_drv_argument_not_allowed_with) 3326 << A->getAsString(Args) << "-ccc-arcmt-migrate"; 3327 3328 CmdArgs.push_back("-mt-migrate-directory"); 3329 CmdArgs.push_back(A->getValue()); 3330 3331 if (!Args.hasArg(options::OPT_objcmt_migrate_literals, 3332 options::OPT_objcmt_migrate_subscripting, 3333 options::OPT_objcmt_migrate_property)) { 3334 // None specified, means enable them all. 3335 CmdArgs.push_back("-objcmt-migrate-literals"); 3336 CmdArgs.push_back("-objcmt-migrate-subscripting"); 3337 CmdArgs.push_back("-objcmt-migrate-property"); 3338 } else { 3339 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 3340 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 3341 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 3342 } 3343 } else { 3344 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 3345 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 3346 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 3347 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all); 3348 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property); 3349 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property); 3350 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax); 3351 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation); 3352 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype); 3353 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros); 3354 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance); 3355 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property); 3356 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property); 3357 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly); 3358 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init); 3359 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path); 3360 } 3361 } 3362 3363 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, 3364 const ArgList &Args, ArgStringList &CmdArgs) { 3365 // -fbuiltin is default unless -mkernel is used. 3366 bool UseBuiltins = 3367 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin, 3368 !Args.hasArg(options::OPT_mkernel)); 3369 if (!UseBuiltins) 3370 CmdArgs.push_back("-fno-builtin"); 3371 3372 // -ffreestanding implies -fno-builtin. 3373 if (Args.hasArg(options::OPT_ffreestanding)) 3374 UseBuiltins = false; 3375 3376 // Process the -fno-builtin-* options. 3377 for (const auto &Arg : Args) { 3378 const Option &O = Arg->getOption(); 3379 if (!O.matches(options::OPT_fno_builtin_)) 3380 continue; 3381 3382 Arg->claim(); 3383 3384 // If -fno-builtin is specified, then there's no need to pass the option to 3385 // the frontend. 3386 if (!UseBuiltins) 3387 continue; 3388 3389 StringRef FuncName = Arg->getValue(); 3390 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName)); 3391 } 3392 3393 // le32-specific flags: 3394 // -fno-math-builtin: clang should not convert math builtins to intrinsics 3395 // by default. 3396 if (TC.getArch() == llvm::Triple::le32) 3397 CmdArgs.push_back("-fno-math-builtin"); 3398 } 3399 3400 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) { 3401 if (llvm::sys::path::cache_directory(Result)) { 3402 llvm::sys::path::append(Result, "clang"); 3403 llvm::sys::path::append(Result, "ModuleCache"); 3404 return true; 3405 } 3406 return false; 3407 } 3408 3409 static void RenderModulesOptions(Compilation &C, const Driver &D, 3410 const ArgList &Args, const InputInfo &Input, 3411 const InputInfo &Output, 3412 ArgStringList &CmdArgs, bool &HaveModules) { 3413 // -fmodules enables the use of precompiled modules (off by default). 3414 // Users can pass -fno-cxx-modules to turn off modules support for 3415 // C++/Objective-C++ programs. 3416 bool HaveClangModules = false; 3417 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) { 3418 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 3419 options::OPT_fno_cxx_modules, true); 3420 if (AllowedInCXX || !types::isCXX(Input.getType())) { 3421 CmdArgs.push_back("-fmodules"); 3422 HaveClangModules = true; 3423 } 3424 } 3425 3426 HaveModules |= HaveClangModules; 3427 if (Args.hasArg(options::OPT_fmodules_ts)) { 3428 CmdArgs.push_back("-fmodules-ts"); 3429 HaveModules = true; 3430 } 3431 3432 // -fmodule-maps enables implicit reading of module map files. By default, 3433 // this is enabled if we are using Clang's flavor of precompiled modules. 3434 if (Args.hasFlag(options::OPT_fimplicit_module_maps, 3435 options::OPT_fno_implicit_module_maps, HaveClangModules)) 3436 CmdArgs.push_back("-fimplicit-module-maps"); 3437 3438 // -fmodules-decluse checks that modules used are declared so (off by default) 3439 if (Args.hasFlag(options::OPT_fmodules_decluse, 3440 options::OPT_fno_modules_decluse, false)) 3441 CmdArgs.push_back("-fmodules-decluse"); 3442 3443 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that 3444 // all #included headers are part of modules. 3445 if (Args.hasFlag(options::OPT_fmodules_strict_decluse, 3446 options::OPT_fno_modules_strict_decluse, false)) 3447 CmdArgs.push_back("-fmodules-strict-decluse"); 3448 3449 // -fno-implicit-modules turns off implicitly compiling modules on demand. 3450 bool ImplicitModules = false; 3451 if (!Args.hasFlag(options::OPT_fimplicit_modules, 3452 options::OPT_fno_implicit_modules, HaveClangModules)) { 3453 if (HaveModules) 3454 CmdArgs.push_back("-fno-implicit-modules"); 3455 } else if (HaveModules) { 3456 ImplicitModules = true; 3457 // -fmodule-cache-path specifies where our implicitly-built module files 3458 // should be written. 3459 SmallString<128> Path; 3460 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) 3461 Path = A->getValue(); 3462 3463 bool HasPath = true; 3464 if (C.isForDiagnostics()) { 3465 // When generating crash reports, we want to emit the modules along with 3466 // the reproduction sources, so we ignore any provided module path. 3467 Path = Output.getFilename(); 3468 llvm::sys::path::replace_extension(Path, ".cache"); 3469 llvm::sys::path::append(Path, "modules"); 3470 } else if (Path.empty()) { 3471 // No module path was provided: use the default. 3472 HasPath = Driver::getDefaultModuleCachePath(Path); 3473 } 3474 3475 // `HasPath` will only be false if getDefaultModuleCachePath() fails. 3476 // That being said, that failure is unlikely and not caching is harmless. 3477 if (HasPath) { 3478 const char Arg[] = "-fmodules-cache-path="; 3479 Path.insert(Path.begin(), Arg, Arg + strlen(Arg)); 3480 CmdArgs.push_back(Args.MakeArgString(Path)); 3481 } 3482 } 3483 3484 if (HaveModules) { 3485 // -fprebuilt-module-path specifies where to load the prebuilt module files. 3486 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) { 3487 CmdArgs.push_back(Args.MakeArgString( 3488 std::string("-fprebuilt-module-path=") + A->getValue())); 3489 A->claim(); 3490 } 3491 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules, 3492 options::OPT_fno_prebuilt_implicit_modules, false)) 3493 CmdArgs.push_back("-fprebuilt-implicit-modules"); 3494 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content, 3495 options::OPT_fno_modules_validate_input_files_content, 3496 false)) 3497 CmdArgs.push_back("-fvalidate-ast-input-files-content"); 3498 } 3499 3500 // -fmodule-name specifies the module that is currently being built (or 3501 // used for header checking by -fmodule-maps). 3502 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ); 3503 3504 // -fmodule-map-file can be used to specify files containing module 3505 // definitions. 3506 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file); 3507 3508 // -fbuiltin-module-map can be used to load the clang 3509 // builtin headers modulemap file. 3510 if (Args.hasArg(options::OPT_fbuiltin_module_map)) { 3511 SmallString<128> BuiltinModuleMap(D.ResourceDir); 3512 llvm::sys::path::append(BuiltinModuleMap, "include"); 3513 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap"); 3514 if (llvm::sys::fs::exists(BuiltinModuleMap)) 3515 CmdArgs.push_back( 3516 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap)); 3517 } 3518 3519 // The -fmodule-file=<name>=<file> form specifies the mapping of module 3520 // names to precompiled module files (the module is loaded only if used). 3521 // The -fmodule-file=<file> form can be used to unconditionally load 3522 // precompiled module files (whether used or not). 3523 if (HaveModules) 3524 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file); 3525 else 3526 Args.ClaimAllArgs(options::OPT_fmodule_file); 3527 3528 // When building modules and generating crashdumps, we need to dump a module 3529 // dependency VFS alongside the output. 3530 if (HaveClangModules && C.isForDiagnostics()) { 3531 SmallString<128> VFSDir(Output.getFilename()); 3532 llvm::sys::path::replace_extension(VFSDir, ".cache"); 3533 // Add the cache directory as a temp so the crash diagnostics pick it up. 3534 C.addTempFile(Args.MakeArgString(VFSDir)); 3535 3536 llvm::sys::path::append(VFSDir, "vfs"); 3537 CmdArgs.push_back("-module-dependency-dir"); 3538 CmdArgs.push_back(Args.MakeArgString(VFSDir)); 3539 } 3540 3541 if (HaveClangModules) 3542 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path); 3543 3544 // Pass through all -fmodules-ignore-macro arguments. 3545 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro); 3546 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval); 3547 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after); 3548 3549 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp); 3550 3551 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) { 3552 if (Args.hasArg(options::OPT_fbuild_session_timestamp)) 3553 D.Diag(diag::err_drv_argument_not_allowed_with) 3554 << A->getAsString(Args) << "-fbuild-session-timestamp"; 3555 3556 llvm::sys::fs::file_status Status; 3557 if (llvm::sys::fs::status(A->getValue(), Status)) 3558 D.Diag(diag::err_drv_no_such_file) << A->getValue(); 3559 CmdArgs.push_back( 3560 Args.MakeArgString("-fbuild-session-timestamp=" + 3561 Twine((uint64_t)Status.getLastModificationTime() 3562 .time_since_epoch() 3563 .count()))); 3564 } 3565 3566 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) { 3567 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp, 3568 options::OPT_fbuild_session_file)) 3569 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp); 3570 3571 Args.AddLastArg(CmdArgs, 3572 options::OPT_fmodules_validate_once_per_build_session); 3573 } 3574 3575 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers, 3576 options::OPT_fno_modules_validate_system_headers, 3577 ImplicitModules)) 3578 CmdArgs.push_back("-fmodules-validate-system-headers"); 3579 3580 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation); 3581 } 3582 3583 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, 3584 ArgStringList &CmdArgs) { 3585 // -fsigned-char is default. 3586 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char, 3587 options::OPT_fno_signed_char, 3588 options::OPT_funsigned_char, 3589 options::OPT_fno_unsigned_char)) { 3590 if (A->getOption().matches(options::OPT_funsigned_char) || 3591 A->getOption().matches(options::OPT_fno_signed_char)) { 3592 CmdArgs.push_back("-fno-signed-char"); 3593 } 3594 } else if (!isSignedCharDefault(T)) { 3595 CmdArgs.push_back("-fno-signed-char"); 3596 } 3597 3598 // The default depends on the language standard. 3599 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t); 3600 3601 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar, 3602 options::OPT_fno_short_wchar)) { 3603 if (A->getOption().matches(options::OPT_fshort_wchar)) { 3604 CmdArgs.push_back("-fwchar-type=short"); 3605 CmdArgs.push_back("-fno-signed-wchar"); 3606 } else { 3607 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64(); 3608 CmdArgs.push_back("-fwchar-type=int"); 3609 if (T.isOSzOS() || 3610 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD()))) 3611 CmdArgs.push_back("-fno-signed-wchar"); 3612 else 3613 CmdArgs.push_back("-fsigned-wchar"); 3614 } 3615 } 3616 } 3617 3618 static void RenderObjCOptions(const ToolChain &TC, const Driver &D, 3619 const llvm::Triple &T, const ArgList &Args, 3620 ObjCRuntime &Runtime, bool InferCovariantReturns, 3621 const InputInfo &Input, ArgStringList &CmdArgs) { 3622 const llvm::Triple::ArchType Arch = TC.getArch(); 3623 3624 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy 3625 // is the default. Except for deployment target of 10.5, next runtime is 3626 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently. 3627 if (Runtime.isNonFragile()) { 3628 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch, 3629 options::OPT_fno_objc_legacy_dispatch, 3630 Runtime.isLegacyDispatchDefaultForArch(Arch))) { 3631 if (TC.UseObjCMixedDispatch()) 3632 CmdArgs.push_back("-fobjc-dispatch-method=mixed"); 3633 else 3634 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy"); 3635 } 3636 } 3637 3638 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option 3639 // to do Array/Dictionary subscripting by default. 3640 if (Arch == llvm::Triple::x86 && T.isMacOSX() && 3641 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily()) 3642 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime"); 3643 3644 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc. 3645 // NOTE: This logic is duplicated in ToolChains.cpp. 3646 if (isObjCAutoRefCount(Args)) { 3647 TC.CheckObjCARC(); 3648 3649 CmdArgs.push_back("-fobjc-arc"); 3650 3651 // FIXME: It seems like this entire block, and several around it should be 3652 // wrapped in isObjC, but for now we just use it here as this is where it 3653 // was being used previously. 3654 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) { 3655 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) 3656 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++"); 3657 else 3658 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++"); 3659 } 3660 3661 // Allow the user to enable full exceptions code emission. 3662 // We default off for Objective-C, on for Objective-C++. 3663 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions, 3664 options::OPT_fno_objc_arc_exceptions, 3665 /*Default=*/types::isCXX(Input.getType()))) 3666 CmdArgs.push_back("-fobjc-arc-exceptions"); 3667 } 3668 3669 // Silence warning for full exception code emission options when explicitly 3670 // set to use no ARC. 3671 if (Args.hasArg(options::OPT_fno_objc_arc)) { 3672 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions); 3673 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions); 3674 } 3675 3676 // Allow the user to control whether messages can be converted to runtime 3677 // functions. 3678 if (types::isObjC(Input.getType())) { 3679 auto *Arg = Args.getLastArg( 3680 options::OPT_fobjc_convert_messages_to_runtime_calls, 3681 options::OPT_fno_objc_convert_messages_to_runtime_calls); 3682 if (Arg && 3683 Arg->getOption().matches( 3684 options::OPT_fno_objc_convert_messages_to_runtime_calls)) 3685 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls"); 3686 } 3687 3688 // -fobjc-infer-related-result-type is the default, except in the Objective-C 3689 // rewriter. 3690 if (InferCovariantReturns) 3691 CmdArgs.push_back("-fno-objc-infer-related-result-type"); 3692 3693 // Pass down -fobjc-weak or -fno-objc-weak if present. 3694 if (types::isObjC(Input.getType())) { 3695 auto WeakArg = 3696 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak); 3697 if (!WeakArg) { 3698 // nothing to do 3699 } else if (!Runtime.allowsWeak()) { 3700 if (WeakArg->getOption().matches(options::OPT_fobjc_weak)) 3701 D.Diag(diag::err_objc_weak_unsupported); 3702 } else { 3703 WeakArg->render(Args, CmdArgs); 3704 } 3705 } 3706 3707 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing)) 3708 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing"); 3709 } 3710 3711 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, 3712 ArgStringList &CmdArgs) { 3713 bool CaretDefault = true; 3714 bool ColumnDefault = true; 3715 3716 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic, 3717 options::OPT__SLASH_diagnostics_column, 3718 options::OPT__SLASH_diagnostics_caret)) { 3719 switch (A->getOption().getID()) { 3720 case options::OPT__SLASH_diagnostics_caret: 3721 CaretDefault = true; 3722 ColumnDefault = true; 3723 break; 3724 case options::OPT__SLASH_diagnostics_column: 3725 CaretDefault = false; 3726 ColumnDefault = true; 3727 break; 3728 case options::OPT__SLASH_diagnostics_classic: 3729 CaretDefault = false; 3730 ColumnDefault = false; 3731 break; 3732 } 3733 } 3734 3735 // -fcaret-diagnostics is default. 3736 if (!Args.hasFlag(options::OPT_fcaret_diagnostics, 3737 options::OPT_fno_caret_diagnostics, CaretDefault)) 3738 CmdArgs.push_back("-fno-caret-diagnostics"); 3739 3740 // -fdiagnostics-fixit-info is default, only pass non-default. 3741 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, 3742 options::OPT_fno_diagnostics_fixit_info)) 3743 CmdArgs.push_back("-fno-diagnostics-fixit-info"); 3744 3745 // Enable -fdiagnostics-show-option by default. 3746 if (!Args.hasFlag(options::OPT_fdiagnostics_show_option, 3747 options::OPT_fno_diagnostics_show_option, true)) 3748 CmdArgs.push_back("-fno-diagnostics-show-option"); 3749 3750 if (const Arg *A = 3751 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) { 3752 CmdArgs.push_back("-fdiagnostics-show-category"); 3753 CmdArgs.push_back(A->getValue()); 3754 } 3755 3756 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 3757 options::OPT_fno_diagnostics_show_hotness, false)) 3758 CmdArgs.push_back("-fdiagnostics-show-hotness"); 3759 3760 if (const Arg *A = 3761 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 3762 std::string Opt = 3763 std::string("-fdiagnostics-hotness-threshold=") + A->getValue(); 3764 CmdArgs.push_back(Args.MakeArgString(Opt)); 3765 } 3766 3767 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { 3768 CmdArgs.push_back("-fdiagnostics-format"); 3769 CmdArgs.push_back(A->getValue()); 3770 } 3771 3772 if (const Arg *A = Args.getLastArg( 3773 options::OPT_fdiagnostics_show_note_include_stack, 3774 options::OPT_fno_diagnostics_show_note_include_stack)) { 3775 const Option &O = A->getOption(); 3776 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack)) 3777 CmdArgs.push_back("-fdiagnostics-show-note-include-stack"); 3778 else 3779 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack"); 3780 } 3781 3782 // Color diagnostics are parsed by the driver directly from argv and later 3783 // re-parsed to construct this job; claim any possible color diagnostic here 3784 // to avoid warn_drv_unused_argument and diagnose bad 3785 // OPT_fdiagnostics_color_EQ values. 3786 for (const Arg *A : Args) { 3787 const Option &O = A->getOption(); 3788 if (!O.matches(options::OPT_fcolor_diagnostics) && 3789 !O.matches(options::OPT_fdiagnostics_color) && 3790 !O.matches(options::OPT_fno_color_diagnostics) && 3791 !O.matches(options::OPT_fno_diagnostics_color) && 3792 !O.matches(options::OPT_fdiagnostics_color_EQ)) 3793 continue; 3794 3795 if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 3796 StringRef Value(A->getValue()); 3797 if (Value != "always" && Value != "never" && Value != "auto") 3798 D.Diag(diag::err_drv_clang_unsupported) 3799 << ("-fdiagnostics-color=" + Value).str(); 3800 } 3801 A->claim(); 3802 } 3803 3804 if (D.getDiags().getDiagnosticOptions().ShowColors) 3805 CmdArgs.push_back("-fcolor-diagnostics"); 3806 3807 if (Args.hasArg(options::OPT_fansi_escape_codes)) 3808 CmdArgs.push_back("-fansi-escape-codes"); 3809 3810 if (!Args.hasFlag(options::OPT_fshow_source_location, 3811 options::OPT_fno_show_source_location)) 3812 CmdArgs.push_back("-fno-show-source-location"); 3813 3814 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths)) 3815 CmdArgs.push_back("-fdiagnostics-absolute-paths"); 3816 3817 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column, 3818 ColumnDefault)) 3819 CmdArgs.push_back("-fno-show-column"); 3820 3821 if (!Args.hasFlag(options::OPT_fspell_checking, 3822 options::OPT_fno_spell_checking)) 3823 CmdArgs.push_back("-fno-spell-checking"); 3824 } 3825 3826 enum class DwarfFissionKind { None, Split, Single }; 3827 3828 static DwarfFissionKind getDebugFissionKind(const Driver &D, 3829 const ArgList &Args, Arg *&Arg) { 3830 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ, 3831 options::OPT_gno_split_dwarf); 3832 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf)) 3833 return DwarfFissionKind::None; 3834 3835 if (Arg->getOption().matches(options::OPT_gsplit_dwarf)) 3836 return DwarfFissionKind::Split; 3837 3838 StringRef Value = Arg->getValue(); 3839 if (Value == "split") 3840 return DwarfFissionKind::Split; 3841 if (Value == "single") 3842 return DwarfFissionKind::Single; 3843 3844 D.Diag(diag::err_drv_unsupported_option_argument) 3845 << Arg->getOption().getName() << Arg->getValue(); 3846 return DwarfFissionKind::None; 3847 } 3848 3849 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, 3850 const ArgList &Args, ArgStringList &CmdArgs, 3851 unsigned DwarfVersion) { 3852 auto *DwarfFormatArg = 3853 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32); 3854 if (!DwarfFormatArg) 3855 return; 3856 3857 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) { 3858 if (DwarfVersion < 3) 3859 D.Diag(diag::err_drv_argument_only_allowed_with) 3860 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater"; 3861 else if (!T.isArch64Bit()) 3862 D.Diag(diag::err_drv_argument_only_allowed_with) 3863 << DwarfFormatArg->getAsString(Args) << "64 bit architecture"; 3864 else if (!T.isOSBinFormatELF()) 3865 D.Diag(diag::err_drv_argument_only_allowed_with) 3866 << DwarfFormatArg->getAsString(Args) << "ELF platforms"; 3867 } 3868 3869 DwarfFormatArg->render(Args, CmdArgs); 3870 } 3871 3872 static void renderDebugOptions(const ToolChain &TC, const Driver &D, 3873 const llvm::Triple &T, const ArgList &Args, 3874 bool EmitCodeView, bool IRInput, 3875 ArgStringList &CmdArgs, 3876 codegenoptions::DebugInfoKind &DebugInfoKind, 3877 DwarfFissionKind &DwarfFission) { 3878 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling, 3879 options::OPT_fno_debug_info_for_profiling, false) && 3880 checkDebugInfoOption( 3881 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC)) 3882 CmdArgs.push_back("-fdebug-info-for-profiling"); 3883 3884 // The 'g' groups options involve a somewhat intricate sequence of decisions 3885 // about what to pass from the driver to the frontend, but by the time they 3886 // reach cc1 they've been factored into three well-defined orthogonal choices: 3887 // * what level of debug info to generate 3888 // * what dwarf version to write 3889 // * what debugger tuning to use 3890 // This avoids having to monkey around further in cc1 other than to disable 3891 // codeview if not running in a Windows environment. Perhaps even that 3892 // decision should be made in the driver as well though. 3893 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning(); 3894 3895 bool SplitDWARFInlining = 3896 Args.hasFlag(options::OPT_fsplit_dwarf_inlining, 3897 options::OPT_fno_split_dwarf_inlining, false); 3898 3899 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does 3900 // object file generation and no IR generation, -gN should not be needed. So 3901 // allow -gsplit-dwarf with either -gN or IR input. 3902 if (IRInput || Args.hasArg(options::OPT_g_Group)) { 3903 Arg *SplitDWARFArg; 3904 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg); 3905 if (DwarfFission != DwarfFissionKind::None && 3906 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) { 3907 DwarfFission = DwarfFissionKind::None; 3908 SplitDWARFInlining = false; 3909 } 3910 } 3911 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { 3912 DebugInfoKind = codegenoptions::DebugInfoConstructor; 3913 3914 // If the last option explicitly specified a debug-info level, use it. 3915 if (checkDebugInfoOption(A, Args, D, TC) && 3916 A->getOption().matches(options::OPT_gN_Group)) { 3917 DebugInfoKind = DebugLevelToInfoKind(*A); 3918 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more 3919 // complicated if you've disabled inline info in the skeleton CUs 3920 // (SplitDWARFInlining) - then there's value in composing split-dwarf and 3921 // line-tables-only, so let those compose naturally in that case. 3922 if (DebugInfoKind == codegenoptions::NoDebugInfo || 3923 DebugInfoKind == codegenoptions::DebugDirectivesOnly || 3924 (DebugInfoKind == codegenoptions::DebugLineTablesOnly && 3925 SplitDWARFInlining)) 3926 DwarfFission = DwarfFissionKind::None; 3927 } 3928 } 3929 3930 // If a debugger tuning argument appeared, remember it. 3931 if (const Arg *A = 3932 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 3933 if (checkDebugInfoOption(A, Args, D, TC)) { 3934 if (A->getOption().matches(options::OPT_glldb)) 3935 DebuggerTuning = llvm::DebuggerKind::LLDB; 3936 else if (A->getOption().matches(options::OPT_gsce)) 3937 DebuggerTuning = llvm::DebuggerKind::SCE; 3938 else if (A->getOption().matches(options::OPT_gdbx)) 3939 DebuggerTuning = llvm::DebuggerKind::DBX; 3940 else 3941 DebuggerTuning = llvm::DebuggerKind::GDB; 3942 } 3943 } 3944 3945 // If a -gdwarf argument appeared, remember it. 3946 const Arg *GDwarfN = getDwarfNArg(Args); 3947 bool EmitDwarf = false; 3948 if (GDwarfN) { 3949 if (checkDebugInfoOption(GDwarfN, Args, D, TC)) 3950 EmitDwarf = true; 3951 else 3952 GDwarfN = nullptr; 3953 } 3954 3955 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) { 3956 if (checkDebugInfoOption(A, Args, D, TC)) 3957 EmitCodeView = true; 3958 } 3959 3960 // If the user asked for debug info but did not explicitly specify -gcodeview 3961 // or -gdwarf, ask the toolchain for the default format. 3962 if (!EmitCodeView && !EmitDwarf && 3963 DebugInfoKind != codegenoptions::NoDebugInfo) { 3964 switch (TC.getDefaultDebugFormat()) { 3965 case codegenoptions::DIF_CodeView: 3966 EmitCodeView = true; 3967 break; 3968 case codegenoptions::DIF_DWARF: 3969 EmitDwarf = true; 3970 break; 3971 } 3972 } 3973 3974 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user 3975 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may 3976 // be lower than what the user wanted. 3977 unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args); 3978 if (EmitDwarf) { 3979 // Start with the platform default DWARF version 3980 RequestedDWARFVersion = TC.GetDefaultDwarfVersion(); 3981 assert(RequestedDWARFVersion && 3982 "toolchain default DWARF version must be nonzero"); 3983 3984 // If the user specified a default DWARF version, that takes precedence 3985 // over the platform default. 3986 if (DefaultDWARFVersion) 3987 RequestedDWARFVersion = DefaultDWARFVersion; 3988 3989 // Override with a user-specified DWARF version 3990 if (GDwarfN) 3991 if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling())) 3992 RequestedDWARFVersion = ExplicitVersion; 3993 // Clamp effective DWARF version to the max supported by the toolchain. 3994 EffectiveDWARFVersion = 3995 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion()); 3996 } 3997 3998 // -gline-directives-only supported only for the DWARF debug info. 3999 if (RequestedDWARFVersion == 0 && 4000 DebugInfoKind == codegenoptions::DebugDirectivesOnly) 4001 DebugInfoKind = codegenoptions::NoDebugInfo; 4002 4003 // strict DWARF is set to false by default. But for DBX, we need it to be set 4004 // as true by default. 4005 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf)) 4006 (void)checkDebugInfoOption(A, Args, D, TC); 4007 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf, 4008 DebuggerTuning == llvm::DebuggerKind::DBX)) 4009 CmdArgs.push_back("-gstrict-dwarf"); 4010 4011 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags. 4012 Args.ClaimAllArgs(options::OPT_g_flags_Group); 4013 4014 // Column info is included by default for everything except SCE and 4015 // CodeView. Clang doesn't track end columns, just starting columns, which, 4016 // in theory, is fine for CodeView (and PDB). In practice, however, the 4017 // Microsoft debuggers don't handle missing end columns well, and the AIX 4018 // debugger DBX also doesn't handle the columns well, so it's better not to 4019 // include any column info. 4020 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info)) 4021 (void)checkDebugInfoOption(A, Args, D, TC); 4022 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info, 4023 !EmitCodeView && 4024 (DebuggerTuning != llvm::DebuggerKind::SCE && 4025 DebuggerTuning != llvm::DebuggerKind::DBX))) 4026 CmdArgs.push_back("-gno-column-info"); 4027 4028 // FIXME: Move backend command line options to the module. 4029 // If -gline-tables-only or -gline-directives-only is the last option it wins. 4030 if (const Arg *A = Args.getLastArg(options::OPT_gmodules)) 4031 if (checkDebugInfoOption(A, Args, D, TC)) { 4032 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly && 4033 DebugInfoKind != codegenoptions::DebugDirectivesOnly) { 4034 DebugInfoKind = codegenoptions::DebugInfoConstructor; 4035 CmdArgs.push_back("-dwarf-ext-refs"); 4036 CmdArgs.push_back("-fmodule-format=obj"); 4037 } 4038 } 4039 4040 if (T.isOSBinFormatELF() && SplitDWARFInlining) 4041 CmdArgs.push_back("-fsplit-dwarf-inlining"); 4042 4043 // After we've dealt with all combinations of things that could 4044 // make DebugInfoKind be other than None or DebugLineTablesOnly, 4045 // figure out if we need to "upgrade" it to standalone debug info. 4046 // We parse these two '-f' options whether or not they will be used, 4047 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only" 4048 bool NeedFullDebug = Args.hasFlag( 4049 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug, 4050 DebuggerTuning == llvm::DebuggerKind::LLDB || 4051 TC.GetDefaultStandaloneDebug()); 4052 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug)) 4053 (void)checkDebugInfoOption(A, Args, D, TC); 4054 4055 if (DebugInfoKind == codegenoptions::LimitedDebugInfo || 4056 DebugInfoKind == codegenoptions::DebugInfoConstructor) { 4057 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types, 4058 options::OPT_feliminate_unused_debug_types, false)) 4059 DebugInfoKind = codegenoptions::UnusedTypeInfo; 4060 else if (NeedFullDebug) 4061 DebugInfoKind = codegenoptions::FullDebugInfo; 4062 } 4063 4064 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, 4065 false)) { 4066 // Source embedding is a vendor extension to DWARF v5. By now we have 4067 // checked if a DWARF version was stated explicitly, and have otherwise 4068 // fallen back to the target default, so if this is still not at least 5 4069 // we emit an error. 4070 const Arg *A = Args.getLastArg(options::OPT_gembed_source); 4071 if (RequestedDWARFVersion < 5) 4072 D.Diag(diag::err_drv_argument_only_allowed_with) 4073 << A->getAsString(Args) << "-gdwarf-5"; 4074 else if (EffectiveDWARFVersion < 5) 4075 // The toolchain has reduced allowed dwarf version, so we can't enable 4076 // -gembed-source. 4077 D.Diag(diag::warn_drv_dwarf_version_limited_by_target) 4078 << A->getAsString(Args) << TC.getTripleString() << 5 4079 << EffectiveDWARFVersion; 4080 else if (checkDebugInfoOption(A, Args, D, TC)) 4081 CmdArgs.push_back("-gembed-source"); 4082 } 4083 4084 if (EmitCodeView) { 4085 CmdArgs.push_back("-gcodeview"); 4086 4087 // Emit codeview type hashes if requested. 4088 if (Args.hasFlag(options::OPT_gcodeview_ghash, 4089 options::OPT_gno_codeview_ghash, false)) { 4090 CmdArgs.push_back("-gcodeview-ghash"); 4091 } 4092 } 4093 4094 // Omit inline line tables if requested. 4095 if (Args.hasFlag(options::OPT_gno_inline_line_tables, 4096 options::OPT_ginline_line_tables, false)) { 4097 CmdArgs.push_back("-gno-inline-line-tables"); 4098 } 4099 4100 // When emitting remarks, we need at least debug lines in the output. 4101 if (willEmitRemarks(Args) && 4102 DebugInfoKind <= codegenoptions::DebugDirectivesOnly) 4103 DebugInfoKind = codegenoptions::DebugLineTablesOnly; 4104 4105 // Adjust the debug info kind for the given toolchain. 4106 TC.adjustDebugInfoKind(DebugInfoKind, Args); 4107 4108 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion, 4109 DebuggerTuning); 4110 4111 // -fdebug-macro turns on macro debug info generation. 4112 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro, 4113 false)) 4114 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args, 4115 D, TC)) 4116 CmdArgs.push_back("-debug-info-macro"); 4117 4118 // -ggnu-pubnames turns on gnu style pubnames in the backend. 4119 const auto *PubnamesArg = 4120 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames, 4121 options::OPT_gpubnames, options::OPT_gno_pubnames); 4122 if (DwarfFission != DwarfFissionKind::None || 4123 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) 4124 if (!PubnamesArg || 4125 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) && 4126 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))) 4127 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches( 4128 options::OPT_gpubnames) 4129 ? "-gpubnames" 4130 : "-ggnu-pubnames"); 4131 4132 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address, 4133 options::OPT_fno_debug_ranges_base_address, false)) { 4134 CmdArgs.push_back("-fdebug-ranges-base-address"); 4135 } 4136 4137 // -gdwarf-aranges turns on the emission of the aranges section in the 4138 // backend. 4139 // Always enabled for SCE tuning. 4140 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE; 4141 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges)) 4142 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges; 4143 if (NeedAranges) { 4144 CmdArgs.push_back("-mllvm"); 4145 CmdArgs.push_back("-generate-arange-section"); 4146 } 4147 4148 if (Args.hasFlag(options::OPT_fforce_dwarf_frame, 4149 options::OPT_fno_force_dwarf_frame, false)) 4150 CmdArgs.push_back("-fforce-dwarf-frame"); 4151 4152 if (Args.hasFlag(options::OPT_fdebug_types_section, 4153 options::OPT_fno_debug_types_section, false)) { 4154 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) { 4155 D.Diag(diag::err_drv_unsupported_opt_for_target) 4156 << Args.getLastArg(options::OPT_fdebug_types_section) 4157 ->getAsString(Args) 4158 << T.getTriple(); 4159 } else if (checkDebugInfoOption( 4160 Args.getLastArg(options::OPT_fdebug_types_section), Args, D, 4161 TC)) { 4162 CmdArgs.push_back("-mllvm"); 4163 CmdArgs.push_back("-generate-type-units"); 4164 } 4165 } 4166 4167 // To avoid join/split of directory+filename, the integrated assembler prefers 4168 // the directory form of .file on all DWARF versions. GNU as doesn't allow the 4169 // form before DWARF v5. 4170 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm, 4171 options::OPT_fno_dwarf_directory_asm, 4172 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5)) 4173 CmdArgs.push_back("-fno-dwarf-directory-asm"); 4174 4175 // Decide how to render forward declarations of template instantiations. 4176 // SCE wants full descriptions, others just get them in the name. 4177 if (DebuggerTuning == llvm::DebuggerKind::SCE) 4178 CmdArgs.push_back("-debug-forward-template-params"); 4179 4180 // Do we need to explicitly import anonymous namespaces into the parent 4181 // scope? 4182 if (DebuggerTuning == llvm::DebuggerKind::SCE) 4183 CmdArgs.push_back("-dwarf-explicit-import"); 4184 4185 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion); 4186 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC); 4187 } 4188 4189 void Clang::ConstructJob(Compilation &C, const JobAction &JA, 4190 const InputInfo &Output, const InputInfoList &Inputs, 4191 const ArgList &Args, const char *LinkingOutput) const { 4192 const auto &TC = getToolChain(); 4193 const llvm::Triple &RawTriple = TC.getTriple(); 4194 const llvm::Triple &Triple = TC.getEffectiveTriple(); 4195 const std::string &TripleStr = Triple.getTriple(); 4196 4197 bool KernelOrKext = 4198 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 4199 const Driver &D = TC.getDriver(); 4200 ArgStringList CmdArgs; 4201 4202 // Check number of inputs for sanity. We need at least one input. 4203 assert(Inputs.size() >= 1 && "Must have at least one input."); 4204 // CUDA/HIP compilation may have multiple inputs (source file + results of 4205 // device-side compilations). OpenMP device jobs also take the host IR as a 4206 // second input. Module precompilation accepts a list of header files to 4207 // include as part of the module. All other jobs are expected to have exactly 4208 // one input. 4209 bool IsCuda = JA.isOffloading(Action::OFK_Cuda); 4210 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda); 4211 bool IsHIP = JA.isOffloading(Action::OFK_HIP); 4212 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP); 4213 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP); 4214 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA); 4215 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) || 4216 JA.isDeviceOffloading(Action::OFK_Host)); 4217 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction); 4218 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction); 4219 4220 // A header module compilation doesn't have a main input file, so invent a 4221 // fake one as a placeholder. 4222 const char *ModuleName = [&]{ 4223 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ); 4224 return ModuleNameArg ? ModuleNameArg->getValue() : ""; 4225 }(); 4226 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName); 4227 4228 const InputInfo &Input = 4229 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0]; 4230 4231 InputInfoList ModuleHeaderInputs; 4232 const InputInfo *CudaDeviceInput = nullptr; 4233 const InputInfo *OpenMPDeviceInput = nullptr; 4234 for (const InputInfo &I : Inputs) { 4235 if (&I == &Input) { 4236 // This is the primary input. 4237 } else if (IsHeaderModulePrecompile && 4238 types::getPrecompiledType(I.getType()) == types::TY_PCH) { 4239 types::ID Expected = HeaderModuleInput.getType(); 4240 if (I.getType() != Expected) { 4241 D.Diag(diag::err_drv_module_header_wrong_kind) 4242 << I.getFilename() << types::getTypeName(I.getType()) 4243 << types::getTypeName(Expected); 4244 } 4245 ModuleHeaderInputs.push_back(I); 4246 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) { 4247 CudaDeviceInput = &I; 4248 } else if (IsOpenMPDevice && !OpenMPDeviceInput) { 4249 OpenMPDeviceInput = &I; 4250 } else { 4251 llvm_unreachable("unexpectedly given multiple inputs"); 4252 } 4253 } 4254 4255 const llvm::Triple *AuxTriple = 4256 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr; 4257 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment(); 4258 bool IsIAMCU = RawTriple.isOSIAMCU(); 4259 4260 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in 4261 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not 4262 // Windows), we need to pass Windows-specific flags to cc1. 4263 if (IsCuda || IsHIP) 4264 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment(); 4265 4266 // C++ is not supported for IAMCU. 4267 if (IsIAMCU && types::isCXX(Input.getType())) 4268 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU"; 4269 4270 // Invoke ourselves in -cc1 mode. 4271 // 4272 // FIXME: Implement custom jobs for internal actions. 4273 CmdArgs.push_back("-cc1"); 4274 4275 // Add the "effective" target triple. 4276 CmdArgs.push_back("-triple"); 4277 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 4278 4279 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) { 4280 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args); 4281 Args.ClaimAllArgs(options::OPT_MJ); 4282 } else if (const Arg *GenCDBFragment = 4283 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) { 4284 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C, 4285 TripleStr, Output, Input, Args); 4286 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path); 4287 } 4288 4289 if (IsCuda || IsHIP) { 4290 // We have to pass the triple of the host if compiling for a CUDA/HIP device 4291 // and vice-versa. 4292 std::string NormalizedTriple; 4293 if (JA.isDeviceOffloading(Action::OFK_Cuda) || 4294 JA.isDeviceOffloading(Action::OFK_HIP)) 4295 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>() 4296 ->getTriple() 4297 .normalize(); 4298 else { 4299 // Host-side compilation. 4300 NormalizedTriple = 4301 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 4302 : C.getSingleOffloadToolChain<Action::OFK_HIP>()) 4303 ->getTriple() 4304 .normalize(); 4305 if (IsCuda) { 4306 // We need to figure out which CUDA version we're compiling for, as that 4307 // determines how we load and launch GPU kernels. 4308 auto *CTC = static_cast<const toolchains::CudaToolChain *>( 4309 C.getSingleOffloadToolChain<Action::OFK_Cuda>()); 4310 assert(CTC && "Expected valid CUDA Toolchain."); 4311 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN) 4312 CmdArgs.push_back(Args.MakeArgString( 4313 Twine("-target-sdk-version=") + 4314 CudaVersionToString(CTC->CudaInstallation.version()))); 4315 } 4316 } 4317 CmdArgs.push_back("-aux-triple"); 4318 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 4319 } 4320 4321 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) { 4322 CmdArgs.push_back("-fsycl-is-device"); 4323 4324 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) { 4325 A->render(Args, CmdArgs); 4326 } else { 4327 // Ensure the default version in SYCL mode is 2020. 4328 CmdArgs.push_back("-sycl-std=2020"); 4329 } 4330 } 4331 4332 if (IsOpenMPDevice) { 4333 // We have to pass the triple of the host if compiling for an OpenMP device. 4334 std::string NormalizedTriple = 4335 C.getSingleOffloadToolChain<Action::OFK_Host>() 4336 ->getTriple() 4337 .normalize(); 4338 CmdArgs.push_back("-aux-triple"); 4339 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 4340 } 4341 4342 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm || 4343 Triple.getArch() == llvm::Triple::thumb)) { 4344 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6; 4345 unsigned Version = 0; 4346 bool Failure = 4347 Triple.getArchName().substr(Offset).consumeInteger(10, Version); 4348 if (Failure || Version < 7) 4349 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName() 4350 << TripleStr; 4351 } 4352 4353 // Push all default warning arguments that are specific to 4354 // the given target. These come before user provided warning options 4355 // are provided. 4356 TC.addClangWarningOptions(CmdArgs); 4357 4358 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions. 4359 if (Triple.isSPIR()) 4360 CmdArgs.push_back("-Wspir-compat"); 4361 4362 // Select the appropriate action. 4363 RewriteKind rewriteKind = RK_None; 4364 4365 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args 4366 // it claims when not running an assembler. Otherwise, clang would emit 4367 // "argument unused" warnings for assembler flags when e.g. adding "-E" to 4368 // flags while debugging something. That'd be somewhat inconvenient, and it's 4369 // also inconsistent with most other flags -- we don't warn on 4370 // -ffunction-sections not being used in -E mode either for example, even 4371 // though it's not really used either. 4372 if (!isa<AssembleJobAction>(JA)) { 4373 // The args claimed here should match the args used in 4374 // CollectArgsForIntegratedAssembler(). 4375 if (TC.useIntegratedAs()) { 4376 Args.ClaimAllArgs(options::OPT_mrelax_all); 4377 Args.ClaimAllArgs(options::OPT_mno_relax_all); 4378 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible); 4379 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible); 4380 switch (C.getDefaultToolChain().getArch()) { 4381 case llvm::Triple::arm: 4382 case llvm::Triple::armeb: 4383 case llvm::Triple::thumb: 4384 case llvm::Triple::thumbeb: 4385 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ); 4386 break; 4387 default: 4388 break; 4389 } 4390 } 4391 Args.ClaimAllArgs(options::OPT_Wa_COMMA); 4392 Args.ClaimAllArgs(options::OPT_Xassembler); 4393 } 4394 4395 if (isa<AnalyzeJobAction>(JA)) { 4396 assert(JA.getType() == types::TY_Plist && "Invalid output type."); 4397 CmdArgs.push_back("-analyze"); 4398 } else if (isa<MigrateJobAction>(JA)) { 4399 CmdArgs.push_back("-migrate"); 4400 } else if (isa<PreprocessJobAction>(JA)) { 4401 if (Output.getType() == types::TY_Dependencies) 4402 CmdArgs.push_back("-Eonly"); 4403 else { 4404 CmdArgs.push_back("-E"); 4405 if (Args.hasArg(options::OPT_rewrite_objc) && 4406 !Args.hasArg(options::OPT_g_Group)) 4407 CmdArgs.push_back("-P"); 4408 } 4409 } else if (isa<AssembleJobAction>(JA)) { 4410 CmdArgs.push_back("-emit-obj"); 4411 4412 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D); 4413 4414 // Also ignore explicit -force_cpusubtype_ALL option. 4415 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 4416 } else if (isa<PrecompileJobAction>(JA)) { 4417 if (JA.getType() == types::TY_Nothing) 4418 CmdArgs.push_back("-fsyntax-only"); 4419 else if (JA.getType() == types::TY_ModuleFile) 4420 CmdArgs.push_back(IsHeaderModulePrecompile 4421 ? "-emit-header-module" 4422 : "-emit-module-interface"); 4423 else 4424 CmdArgs.push_back("-emit-pch"); 4425 } else if (isa<VerifyPCHJobAction>(JA)) { 4426 CmdArgs.push_back("-verify-pch"); 4427 } else { 4428 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) && 4429 "Invalid action for clang tool."); 4430 if (JA.getType() == types::TY_Nothing) { 4431 CmdArgs.push_back("-fsyntax-only"); 4432 } else if (JA.getType() == types::TY_LLVM_IR || 4433 JA.getType() == types::TY_LTO_IR) { 4434 CmdArgs.push_back("-emit-llvm"); 4435 } else if (JA.getType() == types::TY_LLVM_BC || 4436 JA.getType() == types::TY_LTO_BC) { 4437 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S 4438 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) && 4439 Args.hasArg(options::OPT_emit_llvm)) { 4440 CmdArgs.push_back("-emit-llvm"); 4441 } else { 4442 CmdArgs.push_back("-emit-llvm-bc"); 4443 } 4444 } else if (JA.getType() == types::TY_IFS || 4445 JA.getType() == types::TY_IFS_CPP) { 4446 StringRef ArgStr = 4447 Args.hasArg(options::OPT_interface_stub_version_EQ) 4448 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ) 4449 : "ifs-v1"; 4450 CmdArgs.push_back("-emit-interface-stubs"); 4451 CmdArgs.push_back( 4452 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str())); 4453 } else if (JA.getType() == types::TY_PP_Asm) { 4454 CmdArgs.push_back("-S"); 4455 } else if (JA.getType() == types::TY_AST) { 4456 CmdArgs.push_back("-emit-pch"); 4457 } else if (JA.getType() == types::TY_ModuleFile) { 4458 CmdArgs.push_back("-module-file-info"); 4459 } else if (JA.getType() == types::TY_RewrittenObjC) { 4460 CmdArgs.push_back("-rewrite-objc"); 4461 rewriteKind = RK_NonFragile; 4462 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { 4463 CmdArgs.push_back("-rewrite-objc"); 4464 rewriteKind = RK_Fragile; 4465 } else { 4466 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!"); 4467 } 4468 4469 // Preserve use-list order by default when emitting bitcode, so that 4470 // loading the bitcode up in 'opt' or 'llc' and running passes gives the 4471 // same result as running passes here. For LTO, we don't need to preserve 4472 // the use-list order, since serialization to bitcode is part of the flow. 4473 if (JA.getType() == types::TY_LLVM_BC) 4474 CmdArgs.push_back("-emit-llvm-uselists"); 4475 4476 if (IsUsingLTO) { 4477 // Only AMDGPU supports device-side LTO. 4478 if (IsDeviceOffloadAction && !Triple.isAMDGPU()) { 4479 D.Diag(diag::err_drv_unsupported_opt_for_target) 4480 << Args.getLastArg(options::OPT_foffload_lto, 4481 options::OPT_foffload_lto_EQ) 4482 ->getAsString(Args) 4483 << Triple.getTriple(); 4484 } else { 4485 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin); 4486 CmdArgs.push_back(Args.MakeArgString( 4487 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full"))); 4488 CmdArgs.push_back("-flto-unit"); 4489 } 4490 } 4491 } 4492 4493 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) { 4494 if (!types::isLLVMIR(Input.getType())) 4495 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args); 4496 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ); 4497 } 4498 4499 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ)) 4500 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ); 4501 4502 if (Args.getLastArg(options::OPT_save_temps_EQ)) 4503 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ); 4504 4505 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile, 4506 options::OPT_fmemory_profile_EQ, 4507 options::OPT_fno_memory_profile); 4508 if (MemProfArg && 4509 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile)) 4510 MemProfArg->render(Args, CmdArgs); 4511 4512 // Embed-bitcode option. 4513 // Only white-listed flags below are allowed to be embedded. 4514 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO && 4515 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) { 4516 // Add flags implied by -fembed-bitcode. 4517 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ); 4518 // Disable all llvm IR level optimizations. 4519 CmdArgs.push_back("-disable-llvm-passes"); 4520 4521 // Render target options. 4522 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 4523 4524 // reject options that shouldn't be supported in bitcode 4525 // also reject kernel/kext 4526 static const constexpr unsigned kBitcodeOptionBlacklist[] = { 4527 options::OPT_mkernel, 4528 options::OPT_fapple_kext, 4529 options::OPT_ffunction_sections, 4530 options::OPT_fno_function_sections, 4531 options::OPT_fdata_sections, 4532 options::OPT_fno_data_sections, 4533 options::OPT_fbasic_block_sections_EQ, 4534 options::OPT_funique_internal_linkage_names, 4535 options::OPT_fno_unique_internal_linkage_names, 4536 options::OPT_funique_section_names, 4537 options::OPT_fno_unique_section_names, 4538 options::OPT_funique_basic_block_section_names, 4539 options::OPT_fno_unique_basic_block_section_names, 4540 options::OPT_mrestrict_it, 4541 options::OPT_mno_restrict_it, 4542 options::OPT_mstackrealign, 4543 options::OPT_mno_stackrealign, 4544 options::OPT_mstack_alignment, 4545 options::OPT_mcmodel_EQ, 4546 options::OPT_mlong_calls, 4547 options::OPT_mno_long_calls, 4548 options::OPT_ggnu_pubnames, 4549 options::OPT_gdwarf_aranges, 4550 options::OPT_fdebug_types_section, 4551 options::OPT_fno_debug_types_section, 4552 options::OPT_fdwarf_directory_asm, 4553 options::OPT_fno_dwarf_directory_asm, 4554 options::OPT_mrelax_all, 4555 options::OPT_mno_relax_all, 4556 options::OPT_ftrap_function_EQ, 4557 options::OPT_ffixed_r9, 4558 options::OPT_mfix_cortex_a53_835769, 4559 options::OPT_mno_fix_cortex_a53_835769, 4560 options::OPT_ffixed_x18, 4561 options::OPT_mglobal_merge, 4562 options::OPT_mno_global_merge, 4563 options::OPT_mred_zone, 4564 options::OPT_mno_red_zone, 4565 options::OPT_Wa_COMMA, 4566 options::OPT_Xassembler, 4567 options::OPT_mllvm, 4568 }; 4569 for (const auto &A : Args) 4570 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) != 4571 std::end(kBitcodeOptionBlacklist)) 4572 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling(); 4573 4574 // Render the CodeGen options that need to be passed. 4575 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 4576 options::OPT_fno_optimize_sibling_calls)) 4577 CmdArgs.push_back("-mdisable-tail-calls"); 4578 4579 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args, 4580 CmdArgs, JA); 4581 4582 // Render ABI arguments 4583 switch (TC.getArch()) { 4584 default: break; 4585 case llvm::Triple::arm: 4586 case llvm::Triple::armeb: 4587 case llvm::Triple::thumbeb: 4588 RenderARMABI(D, Triple, Args, CmdArgs); 4589 break; 4590 case llvm::Triple::aarch64: 4591 case llvm::Triple::aarch64_32: 4592 case llvm::Triple::aarch64_be: 4593 RenderAArch64ABI(Triple, Args, CmdArgs); 4594 break; 4595 } 4596 4597 // Optimization level for CodeGen. 4598 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) { 4599 if (A->getOption().matches(options::OPT_O4)) { 4600 CmdArgs.push_back("-O3"); 4601 D.Diag(diag::warn_O4_is_O3); 4602 } else { 4603 A->render(Args, CmdArgs); 4604 } 4605 } 4606 4607 // Input/Output file. 4608 if (Output.getType() == types::TY_Dependencies) { 4609 // Handled with other dependency code. 4610 } else if (Output.isFilename()) { 4611 CmdArgs.push_back("-o"); 4612 CmdArgs.push_back(Output.getFilename()); 4613 } else { 4614 assert(Output.isNothing() && "Input output."); 4615 } 4616 4617 for (const auto &II : Inputs) { 4618 addDashXForInput(Args, II, CmdArgs); 4619 if (II.isFilename()) 4620 CmdArgs.push_back(II.getFilename()); 4621 else 4622 II.getInputArg().renderAsInput(Args, CmdArgs); 4623 } 4624 4625 C.addCommand(std::make_unique<Command>( 4626 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(), 4627 CmdArgs, Inputs, Output)); 4628 return; 4629 } 4630 4631 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO) 4632 CmdArgs.push_back("-fembed-bitcode=marker"); 4633 4634 // We normally speed up the clang process a bit by skipping destructors at 4635 // exit, but when we're generating diagnostics we can rely on some of the 4636 // cleanup. 4637 if (!C.isForDiagnostics()) 4638 CmdArgs.push_back("-disable-free"); 4639 4640 #ifdef NDEBUG 4641 const bool IsAssertBuild = false; 4642 #else 4643 const bool IsAssertBuild = true; 4644 #endif 4645 4646 // Disable the verification pass in -asserts builds. 4647 if (!IsAssertBuild) 4648 CmdArgs.push_back("-disable-llvm-verifier"); 4649 4650 // Discard value names in assert builds unless otherwise specified. 4651 if (Args.hasFlag(options::OPT_fdiscard_value_names, 4652 options::OPT_fno_discard_value_names, !IsAssertBuild)) { 4653 if (Args.hasArg(options::OPT_fdiscard_value_names) && 4654 (std::any_of(Inputs.begin(), Inputs.end(), 4655 [](const clang::driver::InputInfo &II) { 4656 return types::isLLVMIR(II.getType()); 4657 }))) { 4658 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode); 4659 } 4660 CmdArgs.push_back("-discard-value-names"); 4661 } 4662 4663 // Set the main file name, so that debug info works even with 4664 // -save-temps. 4665 CmdArgs.push_back("-main-file-name"); 4666 CmdArgs.push_back(getBaseInputName(Args, Input)); 4667 4668 // Some flags which affect the language (via preprocessor 4669 // defines). 4670 if (Args.hasArg(options::OPT_static)) 4671 CmdArgs.push_back("-static-define"); 4672 4673 if (Args.hasArg(options::OPT_municode)) 4674 CmdArgs.push_back("-DUNICODE"); 4675 4676 if (isa<AnalyzeJobAction>(JA)) 4677 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input); 4678 4679 if (isa<AnalyzeJobAction>(JA) || 4680 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze))) 4681 CmdArgs.push_back("-setup-static-analyzer"); 4682 4683 // Enable compatilibily mode to avoid analyzer-config related errors. 4684 // Since we can't access frontend flags through hasArg, let's manually iterate 4685 // through them. 4686 bool FoundAnalyzerConfig = false; 4687 for (auto Arg : Args.filtered(options::OPT_Xclang)) 4688 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4689 FoundAnalyzerConfig = true; 4690 break; 4691 } 4692 if (!FoundAnalyzerConfig) 4693 for (auto Arg : Args.filtered(options::OPT_Xanalyzer)) 4694 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4695 FoundAnalyzerConfig = true; 4696 break; 4697 } 4698 if (FoundAnalyzerConfig) 4699 CmdArgs.push_back("-analyzer-config-compatibility-mode=true"); 4700 4701 CheckCodeGenerationOptions(D, Args); 4702 4703 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args); 4704 assert(FunctionAlignment <= 31 && "function alignment will be truncated!"); 4705 if (FunctionAlignment) { 4706 CmdArgs.push_back("-function-alignment"); 4707 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment))); 4708 } 4709 4710 // We support -falign-loops=N where N is a power of 2. GCC supports more 4711 // forms. 4712 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) { 4713 unsigned Value = 0; 4714 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 4715 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 4716 << A->getAsString(Args) << A->getValue(); 4717 else if (Value & (Value - 1)) 4718 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two) 4719 << A->getAsString(Args) << A->getValue(); 4720 // Treat =0 as unspecified (use the target preference). 4721 if (Value) 4722 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" + 4723 Twine(std::min(Value, 65536u)))); 4724 } 4725 4726 llvm::Reloc::Model RelocationModel; 4727 unsigned PICLevel; 4728 bool IsPIE; 4729 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args); 4730 4731 bool IsROPI = RelocationModel == llvm::Reloc::ROPI || 4732 RelocationModel == llvm::Reloc::ROPI_RWPI; 4733 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI || 4734 RelocationModel == llvm::Reloc::ROPI_RWPI; 4735 4736 if (Args.hasArg(options::OPT_mcmse) && 4737 !Args.hasArg(options::OPT_fallow_unsupported)) { 4738 if (IsROPI) 4739 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI; 4740 if (IsRWPI) 4741 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI; 4742 } 4743 4744 if (IsROPI && types::isCXX(Input.getType()) && 4745 !Args.hasArg(options::OPT_fallow_unsupported)) 4746 D.Diag(diag::err_drv_ropi_incompatible_with_cxx); 4747 4748 const char *RMName = RelocationModelName(RelocationModel); 4749 if (RMName) { 4750 CmdArgs.push_back("-mrelocation-model"); 4751 CmdArgs.push_back(RMName); 4752 } 4753 if (PICLevel > 0) { 4754 CmdArgs.push_back("-pic-level"); 4755 CmdArgs.push_back(PICLevel == 1 ? "1" : "2"); 4756 if (IsPIE) 4757 CmdArgs.push_back("-pic-is-pie"); 4758 } 4759 4760 if (RelocationModel == llvm::Reloc::ROPI || 4761 RelocationModel == llvm::Reloc::ROPI_RWPI) 4762 CmdArgs.push_back("-fropi"); 4763 if (RelocationModel == llvm::Reloc::RWPI || 4764 RelocationModel == llvm::Reloc::ROPI_RWPI) 4765 CmdArgs.push_back("-frwpi"); 4766 4767 if (Arg *A = Args.getLastArg(options::OPT_meabi)) { 4768 CmdArgs.push_back("-meabi"); 4769 CmdArgs.push_back(A->getValue()); 4770 } 4771 4772 // -fsemantic-interposition is forwarded to CC1: set the 4773 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and 4774 // make default visibility external linkage definitions dso_preemptable. 4775 // 4776 // -fno-semantic-interposition: if the target supports .Lfoo$local local 4777 // aliases (make default visibility external linkage definitions dso_local). 4778 // This is the CC1 default for ELF to match COFF/Mach-O. 4779 // 4780 // Otherwise use Clang's traditional behavior: like 4781 // -fno-semantic-interposition but local aliases are not used. So references 4782 // can be interposed if not optimized out. 4783 if (Triple.isOSBinFormatELF()) { 4784 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition, 4785 options::OPT_fno_semantic_interposition); 4786 if (RelocationModel != llvm::Reloc::Static && !IsPIE) { 4787 // The supported targets need to call AsmPrinter::getSymbolPreferLocal. 4788 bool SupportsLocalAlias = 4789 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86(); 4790 if (!A) 4791 CmdArgs.push_back("-fhalf-no-semantic-interposition"); 4792 else if (A->getOption().matches(options::OPT_fsemantic_interposition)) 4793 A->render(Args, CmdArgs); 4794 else if (!SupportsLocalAlias) 4795 CmdArgs.push_back("-fhalf-no-semantic-interposition"); 4796 } 4797 } 4798 4799 { 4800 std::string Model; 4801 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) { 4802 if (!TC.isThreadModelSupported(A->getValue())) 4803 D.Diag(diag::err_drv_invalid_thread_model_for_target) 4804 << A->getValue() << A->getAsString(Args); 4805 Model = A->getValue(); 4806 } else 4807 Model = TC.getThreadModel(); 4808 if (Model != "posix") { 4809 CmdArgs.push_back("-mthread-model"); 4810 CmdArgs.push_back(Args.MakeArgString(Model)); 4811 } 4812 } 4813 4814 Args.AddLastArg(CmdArgs, options::OPT_fveclib); 4815 4816 if (Args.hasFlag(options::OPT_fmerge_all_constants, 4817 options::OPT_fno_merge_all_constants, false)) 4818 CmdArgs.push_back("-fmerge-all-constants"); 4819 4820 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks, 4821 options::OPT_fdelete_null_pointer_checks, false)) 4822 CmdArgs.push_back("-fno-delete-null-pointer-checks"); 4823 4824 // LLVM Code Generator Options. 4825 4826 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) { 4827 StringRef Map = A->getValue(); 4828 if (!llvm::sys::fs::exists(Map)) { 4829 D.Diag(diag::err_drv_no_such_file) << Map; 4830 } else { 4831 A->render(Args, CmdArgs); 4832 A->claim(); 4833 } 4834 } 4835 4836 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi, 4837 options::OPT_mabi_EQ_vec_default)) { 4838 if (!Triple.isOSAIX()) 4839 D.Diag(diag::err_drv_unsupported_opt_for_target) 4840 << A->getSpelling() << RawTriple.str(); 4841 if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi) 4842 CmdArgs.push_back("-mabi=vec-extabi"); 4843 else 4844 CmdArgs.push_back("-mabi=vec-default"); 4845 } 4846 4847 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) { 4848 // Emit the unsupported option error until the Clang's library integration 4849 // support for 128-bit long double is available for AIX. 4850 if (Triple.isOSAIX()) 4851 D.Diag(diag::err_drv_unsupported_opt_for_target) 4852 << A->getSpelling() << RawTriple.str(); 4853 } 4854 4855 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) { 4856 StringRef v = A->getValue(); 4857 // FIXME: Validate the argument here so we don't produce meaningless errors 4858 // about -fwarn-stack-size=. 4859 if (v.empty()) 4860 D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1; 4861 else 4862 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v)); 4863 A->claim(); 4864 } 4865 4866 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables, 4867 true)) 4868 CmdArgs.push_back("-fno-jump-tables"); 4869 4870 if (Args.hasFlag(options::OPT_fprofile_sample_accurate, 4871 options::OPT_fno_profile_sample_accurate, false)) 4872 CmdArgs.push_back("-fprofile-sample-accurate"); 4873 4874 if (!Args.hasFlag(options::OPT_fpreserve_as_comments, 4875 options::OPT_fno_preserve_as_comments, true)) 4876 CmdArgs.push_back("-fno-preserve-as-comments"); 4877 4878 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { 4879 CmdArgs.push_back("-mregparm"); 4880 CmdArgs.push_back(A->getValue()); 4881 } 4882 4883 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return, 4884 options::OPT_msvr4_struct_return)) { 4885 if (!TC.getTriple().isPPC32()) { 4886 D.Diag(diag::err_drv_unsupported_opt_for_target) 4887 << A->getSpelling() << RawTriple.str(); 4888 } else if (A->getOption().matches(options::OPT_maix_struct_return)) { 4889 CmdArgs.push_back("-maix-struct-return"); 4890 } else { 4891 assert(A->getOption().matches(options::OPT_msvr4_struct_return)); 4892 CmdArgs.push_back("-msvr4-struct-return"); 4893 } 4894 } 4895 4896 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return, 4897 options::OPT_freg_struct_return)) { 4898 if (TC.getArch() != llvm::Triple::x86) { 4899 D.Diag(diag::err_drv_unsupported_opt_for_target) 4900 << A->getSpelling() << RawTriple.str(); 4901 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) { 4902 CmdArgs.push_back("-fpcc-struct-return"); 4903 } else { 4904 assert(A->getOption().matches(options::OPT_freg_struct_return)); 4905 CmdArgs.push_back("-freg-struct-return"); 4906 } 4907 } 4908 4909 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) 4910 CmdArgs.push_back("-fdefault-calling-conv=stdcall"); 4911 4912 if (Args.hasArg(options::OPT_fenable_matrix)) { 4913 // enable-matrix is needed by both the LangOpts and by LLVM. 4914 CmdArgs.push_back("-fenable-matrix"); 4915 CmdArgs.push_back("-mllvm"); 4916 CmdArgs.push_back("-enable-matrix"); 4917 } 4918 4919 CodeGenOptions::FramePointerKind FPKeepKind = 4920 getFramePointerKind(Args, RawTriple); 4921 const char *FPKeepKindStr = nullptr; 4922 switch (FPKeepKind) { 4923 case CodeGenOptions::FramePointerKind::None: 4924 FPKeepKindStr = "-mframe-pointer=none"; 4925 break; 4926 case CodeGenOptions::FramePointerKind::NonLeaf: 4927 FPKeepKindStr = "-mframe-pointer=non-leaf"; 4928 break; 4929 case CodeGenOptions::FramePointerKind::All: 4930 FPKeepKindStr = "-mframe-pointer=all"; 4931 break; 4932 } 4933 assert(FPKeepKindStr && "unknown FramePointerKind"); 4934 CmdArgs.push_back(FPKeepKindStr); 4935 4936 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss, 4937 options::OPT_fno_zero_initialized_in_bss, true)) 4938 CmdArgs.push_back("-fno-zero-initialized-in-bss"); 4939 4940 bool OFastEnabled = isOptimizationLevelFast(Args); 4941 // If -Ofast is the optimization level, then -fstrict-aliasing should be 4942 // enabled. This alias option is being used to simplify the hasFlag logic. 4943 OptSpecifier StrictAliasingAliasOption = 4944 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing; 4945 // We turn strict aliasing off by default if we're in CL mode, since MSVC 4946 // doesn't do any TBAA. 4947 bool TBAAOnByDefault = !D.IsCLMode(); 4948 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption, 4949 options::OPT_fno_strict_aliasing, TBAAOnByDefault)) 4950 CmdArgs.push_back("-relaxed-aliasing"); 4951 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa, 4952 options::OPT_fno_struct_path_tbaa)) 4953 CmdArgs.push_back("-no-struct-path-tbaa"); 4954 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums, 4955 false)) 4956 CmdArgs.push_back("-fstrict-enums"); 4957 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return, 4958 true)) 4959 CmdArgs.push_back("-fno-strict-return"); 4960 if (Args.hasFlag(options::OPT_fallow_editor_placeholders, 4961 options::OPT_fno_allow_editor_placeholders, false)) 4962 CmdArgs.push_back("-fallow-editor-placeholders"); 4963 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers, 4964 options::OPT_fno_strict_vtable_pointers, 4965 false)) 4966 CmdArgs.push_back("-fstrict-vtable-pointers"); 4967 if (Args.hasFlag(options::OPT_fforce_emit_vtables, 4968 options::OPT_fno_force_emit_vtables, 4969 false)) 4970 CmdArgs.push_back("-fforce-emit-vtables"); 4971 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 4972 options::OPT_fno_optimize_sibling_calls)) 4973 CmdArgs.push_back("-mdisable-tail-calls"); 4974 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls, 4975 options::OPT_fescaping_block_tail_calls, false)) 4976 CmdArgs.push_back("-fno-escaping-block-tail-calls"); 4977 4978 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses, 4979 options::OPT_fno_fine_grained_bitfield_accesses); 4980 4981 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables, 4982 options::OPT_fno_experimental_relative_cxx_abi_vtables); 4983 4984 // Handle segmented stacks. 4985 if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack, 4986 false)) 4987 CmdArgs.push_back("-fsplit-stack"); 4988 4989 // -fprotect-parens=0 is default. 4990 if (Args.hasFlag(options::OPT_fprotect_parens, 4991 options::OPT_fno_protect_parens, false)) 4992 CmdArgs.push_back("-fprotect-parens"); 4993 4994 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA); 4995 4996 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) { 4997 const llvm::Triple::ArchType Arch = TC.getArch(); 4998 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) { 4999 StringRef V = A->getValue(); 5000 if (V == "64") 5001 CmdArgs.push_back("-fextend-arguments=64"); 5002 else if (V != "32") 5003 D.Diag(diag::err_drv_invalid_argument_to_option) 5004 << A->getValue() << A->getOption().getName(); 5005 } else 5006 D.Diag(diag::err_drv_unsupported_opt_for_target) 5007 << A->getOption().getName() << TripleStr; 5008 } 5009 5010 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) { 5011 if (TC.getArch() == llvm::Triple::avr) 5012 A->render(Args, CmdArgs); 5013 else 5014 D.Diag(diag::err_drv_unsupported_opt_for_target) 5015 << A->getAsString(Args) << TripleStr; 5016 } 5017 5018 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) { 5019 if (TC.getTriple().isX86()) 5020 A->render(Args, CmdArgs); 5021 else if (TC.getTriple().isPPC() && 5022 (A->getOption().getID() != options::OPT_mlong_double_80)) 5023 A->render(Args, CmdArgs); 5024 else 5025 D.Diag(diag::err_drv_unsupported_opt_for_target) 5026 << A->getAsString(Args) << TripleStr; 5027 } 5028 5029 // Decide whether to use verbose asm. Verbose assembly is the default on 5030 // toolchains which have the integrated assembler on by default. 5031 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault(); 5032 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm, 5033 IsIntegratedAssemblerDefault)) 5034 CmdArgs.push_back("-fno-verbose-asm"); 5035 5036 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we 5037 // use that to indicate the MC default in the backend. 5038 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) { 5039 StringRef V = A->getValue(); 5040 unsigned Num; 5041 if (V == "none") 5042 A->render(Args, CmdArgs); 5043 else if (!V.consumeInteger(10, Num) && Num > 0 && 5044 (V.empty() || (V.consume_front(".") && 5045 !V.consumeInteger(10, Num) && V.empty()))) 5046 A->render(Args, CmdArgs); 5047 else 5048 D.Diag(diag::err_drv_invalid_argument_to_option) 5049 << A->getValue() << A->getOption().getName(); 5050 } 5051 5052 // If toolchain choose to use MCAsmParser for inline asm don't pass the 5053 // option to disable integrated-as explictly. 5054 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser()) 5055 CmdArgs.push_back("-no-integrated-as"); 5056 5057 if (Args.hasArg(options::OPT_fdebug_pass_structure)) { 5058 CmdArgs.push_back("-mdebug-pass"); 5059 CmdArgs.push_back("Structure"); 5060 } 5061 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) { 5062 CmdArgs.push_back("-mdebug-pass"); 5063 CmdArgs.push_back("Arguments"); 5064 } 5065 5066 // Enable -mconstructor-aliases except on darwin, where we have to work around 5067 // a linker bug (see <rdar://problem/7651567>), and CUDA/AMDGPU device code, 5068 // where aliases aren't supported. 5069 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX() && !RawTriple.isAMDGPU()) 5070 CmdArgs.push_back("-mconstructor-aliases"); 5071 5072 // Darwin's kernel doesn't support guard variables; just die if we 5073 // try to use them. 5074 if (KernelOrKext && RawTriple.isOSDarwin()) 5075 CmdArgs.push_back("-fforbid-guard-variables"); 5076 5077 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields, 5078 Triple.isWindowsGNUEnvironment())) { 5079 CmdArgs.push_back("-mms-bitfields"); 5080 } 5081 5082 // Non-PIC code defaults to -fdirect-access-external-data while PIC code 5083 // defaults to -fno-direct-access-external-data. Pass the option if different 5084 // from the default. 5085 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data, 5086 options::OPT_fno_direct_access_external_data)) 5087 if (A->getOption().matches(options::OPT_fdirect_access_external_data) != 5088 (PICLevel == 0)) 5089 A->render(Args, CmdArgs); 5090 5091 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) { 5092 CmdArgs.push_back("-fno-plt"); 5093 } 5094 5095 // -fhosted is default. 5096 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to 5097 // use Freestanding. 5098 bool Freestanding = 5099 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) || 5100 KernelOrKext; 5101 if (Freestanding) 5102 CmdArgs.push_back("-ffreestanding"); 5103 5104 // This is a coarse approximation of what llvm-gcc actually does, both 5105 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more 5106 // complicated ways. 5107 bool UnwindTables = 5108 Args.hasFlag(options::OPT_fasynchronous_unwind_tables, 5109 options::OPT_fno_asynchronous_unwind_tables, 5110 (TC.IsUnwindTablesDefault(Args) || 5111 TC.getSanitizerArgs().needsUnwindTables()) && 5112 !Freestanding); 5113 UnwindTables = Args.hasFlag(options::OPT_funwind_tables, 5114 options::OPT_fno_unwind_tables, UnwindTables); 5115 if (UnwindTables) 5116 CmdArgs.push_back("-munwind-tables"); 5117 5118 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless 5119 // `--gpu-use-aux-triple-only` is specified. 5120 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) && 5121 (IsCudaDevice || IsHIPDevice)) { 5122 const ArgList &HostArgs = 5123 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None); 5124 std::string HostCPU = 5125 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false); 5126 if (!HostCPU.empty()) { 5127 CmdArgs.push_back("-aux-target-cpu"); 5128 CmdArgs.push_back(Args.MakeArgString(HostCPU)); 5129 } 5130 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs, 5131 /*ForAS*/ false, /*IsAux*/ true); 5132 } 5133 5134 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 5135 5136 // FIXME: Handle -mtune=. 5137 (void)Args.hasArg(options::OPT_mtune_EQ); 5138 5139 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 5140 StringRef CM = A->getValue(); 5141 if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" || 5142 CM == "tiny") { 5143 if (Triple.isOSAIX() && CM == "medium") 5144 CmdArgs.push_back("-mcmodel=large"); 5145 else 5146 A->render(Args, CmdArgs); 5147 } else { 5148 D.Diag(diag::err_drv_invalid_argument_to_option) 5149 << CM << A->getOption().getName(); 5150 } 5151 } 5152 5153 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) { 5154 StringRef Value = A->getValue(); 5155 unsigned TLSSize = 0; 5156 Value.getAsInteger(10, TLSSize); 5157 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF()) 5158 D.Diag(diag::err_drv_unsupported_opt_for_target) 5159 << A->getOption().getName() << TripleStr; 5160 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48) 5161 D.Diag(diag::err_drv_invalid_int_value) 5162 << A->getOption().getName() << Value; 5163 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ); 5164 } 5165 5166 // Add the target cpu 5167 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false); 5168 if (!CPU.empty()) { 5169 CmdArgs.push_back("-target-cpu"); 5170 CmdArgs.push_back(Args.MakeArgString(CPU)); 5171 } 5172 5173 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs); 5174 5175 // FIXME: For now we want to demote any errors to warnings, when they have 5176 // been raised for asking the wrong question of scalable vectors, such as 5177 // asking for the fixed number of elements. This may happen because code that 5178 // is not yet ported to work for scalable vectors uses the wrong interfaces, 5179 // whereas the behaviour is actually correct. Emitting a warning helps bring 5180 // up scalable vector support in an incremental way. When scalable vector 5181 // support is stable enough, all uses of wrong interfaces should be considered 5182 // as errors, but until then, we can live with a warning being emitted by the 5183 // compiler. This way, Clang can be used to compile code with scalable vectors 5184 // and identify possible issues. 5185 if (isa<BackendJobAction>(JA)) { 5186 CmdArgs.push_back("-mllvm"); 5187 CmdArgs.push_back("-treat-scalable-fixed-error-as-warning"); 5188 } 5189 5190 // These two are potentially updated by AddClangCLArgs. 5191 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 5192 bool EmitCodeView = false; 5193 5194 // Add clang-cl arguments. 5195 types::ID InputType = Input.getType(); 5196 if (D.IsCLMode()) 5197 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView); 5198 5199 DwarfFissionKind DwarfFission = DwarfFissionKind::None; 5200 renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, 5201 types::isLLVMIR(InputType), CmdArgs, DebugInfoKind, 5202 DwarfFission); 5203 5204 // Add the split debug info name to the command lines here so we 5205 // can propagate it to the backend. 5206 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) && 5207 (TC.getTriple().isOSBinFormatELF() || 5208 TC.getTriple().isOSBinFormatWasm()) && 5209 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) || 5210 isa<BackendJobAction>(JA)); 5211 if (SplitDWARF) { 5212 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output); 5213 CmdArgs.push_back("-split-dwarf-file"); 5214 CmdArgs.push_back(SplitDWARFOut); 5215 if (DwarfFission == DwarfFissionKind::Split) { 5216 CmdArgs.push_back("-split-dwarf-output"); 5217 CmdArgs.push_back(SplitDWARFOut); 5218 } 5219 } 5220 5221 // Pass the linker version in use. 5222 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { 5223 CmdArgs.push_back("-target-linker-version"); 5224 CmdArgs.push_back(A->getValue()); 5225 } 5226 5227 // Explicitly error on some things we know we don't support and can't just 5228 // ignore. 5229 if (!Args.hasArg(options::OPT_fallow_unsupported)) { 5230 Arg *Unsupported; 5231 if (types::isCXX(InputType) && RawTriple.isOSDarwin() && 5232 TC.getArch() == llvm::Triple::x86) { 5233 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) || 5234 (Unsupported = Args.getLastArg(options::OPT_mkernel))) 5235 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386) 5236 << Unsupported->getOption().getName(); 5237 } 5238 // The faltivec option has been superseded by the maltivec option. 5239 if ((Unsupported = Args.getLastArg(options::OPT_faltivec))) 5240 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 5241 << Unsupported->getOption().getName() 5242 << "please use -maltivec and include altivec.h explicitly"; 5243 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec))) 5244 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 5245 << Unsupported->getOption().getName() << "please use -mno-altivec"; 5246 } 5247 5248 Args.AddAllArgs(CmdArgs, options::OPT_v); 5249 5250 if (Args.getLastArg(options::OPT_H)) { 5251 CmdArgs.push_back("-H"); 5252 CmdArgs.push_back("-sys-header-deps"); 5253 } 5254 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes); 5255 5256 if (D.CCPrintHeaders && !D.CCGenDiagnostics) { 5257 CmdArgs.push_back("-header-include-file"); 5258 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty() 5259 ? D.CCPrintHeadersFilename.c_str() 5260 : "-"); 5261 CmdArgs.push_back("-sys-header-deps"); 5262 } 5263 Args.AddLastArg(CmdArgs, options::OPT_P); 5264 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); 5265 5266 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { 5267 CmdArgs.push_back("-diagnostic-log-file"); 5268 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty() 5269 ? D.CCLogDiagnosticsFilename.c_str() 5270 : "-"); 5271 } 5272 5273 // Give the gen diagnostics more chances to succeed, by avoiding intentional 5274 // crashes. 5275 if (D.CCGenDiagnostics) 5276 CmdArgs.push_back("-disable-pragma-debug-crash"); 5277 5278 // Allow backend to put its diagnostic files in the same place as frontend 5279 // crash diagnostics files. 5280 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) { 5281 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir); 5282 CmdArgs.push_back("-mllvm"); 5283 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir)); 5284 } 5285 5286 bool UseSeparateSections = isUseSeparateSections(Triple); 5287 5288 if (Args.hasFlag(options::OPT_ffunction_sections, 5289 options::OPT_fno_function_sections, UseSeparateSections)) { 5290 CmdArgs.push_back("-ffunction-sections"); 5291 } 5292 5293 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) { 5294 StringRef Val = A->getValue(); 5295 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 5296 if (Val != "all" && Val != "labels" && Val != "none" && 5297 !Val.startswith("list=")) 5298 D.Diag(diag::err_drv_invalid_value) 5299 << A->getAsString(Args) << A->getValue(); 5300 else 5301 A->render(Args, CmdArgs); 5302 } else if (Triple.isNVPTX()) { 5303 // Do not pass the option to the GPU compilation. We still want it enabled 5304 // for the host-side compilation, so seeing it here is not an error. 5305 } else if (Val != "none") { 5306 // =none is allowed everywhere. It's useful for overriding the option 5307 // and is the same as not specifying the option. 5308 D.Diag(diag::err_drv_unsupported_opt_for_target) 5309 << A->getAsString(Args) << TripleStr; 5310 } 5311 } 5312 5313 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF(); 5314 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 5315 UseSeparateSections || HasDefaultDataSections)) { 5316 CmdArgs.push_back("-fdata-sections"); 5317 } 5318 5319 if (!Args.hasFlag(options::OPT_funique_section_names, 5320 options::OPT_fno_unique_section_names, true)) 5321 CmdArgs.push_back("-fno-unique-section-names"); 5322 5323 if (Args.hasFlag(options::OPT_funique_internal_linkage_names, 5324 options::OPT_fno_unique_internal_linkage_names, false)) 5325 CmdArgs.push_back("-funique-internal-linkage-names"); 5326 5327 if (Args.hasFlag(options::OPT_funique_basic_block_section_names, 5328 options::OPT_fno_unique_basic_block_section_names, false)) 5329 CmdArgs.push_back("-funique-basic-block-section-names"); 5330 5331 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 5332 options::OPT_fno_split_machine_functions)) { 5333 // This codegen pass is only available on x86-elf targets. 5334 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 5335 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 5336 A->render(Args, CmdArgs); 5337 } else { 5338 D.Diag(diag::err_drv_unsupported_opt_for_target) 5339 << A->getAsString(Args) << TripleStr; 5340 } 5341 } 5342 5343 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions, 5344 options::OPT_finstrument_functions_after_inlining, 5345 options::OPT_finstrument_function_entry_bare); 5346 5347 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support 5348 // for sampling, overhead of call arc collection is way too high and there's 5349 // no way to collect the output. 5350 if (!Triple.isNVPTX() && !Triple.isAMDGCN()) 5351 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs); 5352 5353 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ); 5354 5355 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled. 5356 if (RawTriple.isPS4CPU() && 5357 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { 5358 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs); 5359 PS4cpu::addSanitizerArgs(TC, CmdArgs); 5360 } 5361 5362 // Pass options for controlling the default header search paths. 5363 if (Args.hasArg(options::OPT_nostdinc)) { 5364 CmdArgs.push_back("-nostdsysteminc"); 5365 CmdArgs.push_back("-nobuiltininc"); 5366 } else { 5367 if (Args.hasArg(options::OPT_nostdlibinc)) 5368 CmdArgs.push_back("-nostdsysteminc"); 5369 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx); 5370 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc); 5371 } 5372 5373 // Pass the path to compiler resource files. 5374 CmdArgs.push_back("-resource-dir"); 5375 CmdArgs.push_back(D.ResourceDir.c_str()); 5376 5377 Args.AddLastArg(CmdArgs, options::OPT_working_directory); 5378 5379 RenderARCMigrateToolOptions(D, Args, CmdArgs); 5380 5381 // Add preprocessing options like -I, -D, etc. if we are using the 5382 // preprocessor. 5383 // 5384 // FIXME: Support -fpreprocessed 5385 if (types::getPreprocessedType(InputType) != types::TY_INVALID) 5386 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs); 5387 5388 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes 5389 // that "The compiler can only warn and ignore the option if not recognized". 5390 // When building with ccache, it will pass -D options to clang even on 5391 // preprocessed inputs and configure concludes that -fPIC is not supported. 5392 Args.ClaimAllArgs(options::OPT_D); 5393 5394 // Manually translate -O4 to -O3; let clang reject others. 5395 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 5396 if (A->getOption().matches(options::OPT_O4)) { 5397 CmdArgs.push_back("-O3"); 5398 D.Diag(diag::warn_O4_is_O3); 5399 } else { 5400 A->render(Args, CmdArgs); 5401 } 5402 } 5403 5404 // Warn about ignored options to clang. 5405 for (const Arg *A : 5406 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) { 5407 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args); 5408 A->claim(); 5409 } 5410 5411 for (const Arg *A : 5412 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) { 5413 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args); 5414 A->claim(); 5415 } 5416 5417 claimNoWarnArgs(Args); 5418 5419 Args.AddAllArgs(CmdArgs, options::OPT_R_Group); 5420 5421 Args.AddAllArgs(CmdArgs, options::OPT_W_Group); 5422 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false)) 5423 CmdArgs.push_back("-pedantic"); 5424 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors); 5425 Args.AddLastArg(CmdArgs, options::OPT_w); 5426 5427 // Fixed point flags 5428 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point, 5429 /*Default=*/false)) 5430 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point); 5431 5432 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ)) 5433 A->render(Args, CmdArgs); 5434 5435 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables, 5436 options::OPT_fno_experimental_relative_cxx_abi_vtables); 5437 5438 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} 5439 // (-ansi is equivalent to -std=c89 or -std=c++98). 5440 // 5441 // If a std is supplied, only add -trigraphs if it follows the 5442 // option. 5443 bool ImplyVCPPCVer = false; 5444 bool ImplyVCPPCXXVer = false; 5445 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi); 5446 if (Std) { 5447 if (Std->getOption().matches(options::OPT_ansi)) 5448 if (types::isCXX(InputType)) 5449 CmdArgs.push_back("-std=c++98"); 5450 else 5451 CmdArgs.push_back("-std=c89"); 5452 else 5453 Std->render(Args, CmdArgs); 5454 5455 // If -f(no-)trigraphs appears after the language standard flag, honor it. 5456 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi, 5457 options::OPT_ftrigraphs, 5458 options::OPT_fno_trigraphs)) 5459 if (A != Std) 5460 A->render(Args, CmdArgs); 5461 } else { 5462 // Honor -std-default. 5463 // 5464 // FIXME: Clang doesn't correctly handle -std= when the input language 5465 // doesn't match. For the time being just ignore this for C++ inputs; 5466 // eventually we want to do all the standard defaulting here instead of 5467 // splitting it between the driver and clang -cc1. 5468 if (!types::isCXX(InputType)) { 5469 if (!Args.hasArg(options::OPT__SLASH_std)) { 5470 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=", 5471 /*Joined=*/true); 5472 } else 5473 ImplyVCPPCVer = true; 5474 } 5475 else if (IsWindowsMSVC) 5476 ImplyVCPPCXXVer = true; 5477 5478 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs, 5479 options::OPT_fno_trigraphs); 5480 5481 // HIP headers has minimum C++ standard requirements. Therefore set the 5482 // default language standard. 5483 if (IsHIP) 5484 CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11"); 5485 } 5486 5487 // GCC's behavior for -Wwrite-strings is a bit strange: 5488 // * In C, this "warning flag" changes the types of string literals from 5489 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning 5490 // for the discarded qualifier. 5491 // * In C++, this is just a normal warning flag. 5492 // 5493 // Implementing this warning correctly in C is hard, so we follow GCC's 5494 // behavior for now. FIXME: Directly diagnose uses of a string literal as 5495 // a non-const char* in C, rather than using this crude hack. 5496 if (!types::isCXX(InputType)) { 5497 // FIXME: This should behave just like a warning flag, and thus should also 5498 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on. 5499 Arg *WriteStrings = 5500 Args.getLastArg(options::OPT_Wwrite_strings, 5501 options::OPT_Wno_write_strings, options::OPT_w); 5502 if (WriteStrings && 5503 WriteStrings->getOption().matches(options::OPT_Wwrite_strings)) 5504 CmdArgs.push_back("-fconst-strings"); 5505 } 5506 5507 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active 5508 // during C++ compilation, which it is by default. GCC keeps this define even 5509 // in the presence of '-w', match this behavior bug-for-bug. 5510 if (types::isCXX(InputType) && 5511 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated, 5512 true)) { 5513 CmdArgs.push_back("-fdeprecated-macro"); 5514 } 5515 5516 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'. 5517 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) { 5518 if (Asm->getOption().matches(options::OPT_fasm)) 5519 CmdArgs.push_back("-fgnu-keywords"); 5520 else 5521 CmdArgs.push_back("-fno-gnu-keywords"); 5522 } 5523 5524 if (!ShouldEnableAutolink(Args, TC, JA)) 5525 CmdArgs.push_back("-fno-autolink"); 5526 5527 // Add in -fdebug-compilation-dir if necessary. 5528 addDebugCompDirArg(Args, CmdArgs, D.getVFS()); 5529 5530 addDebugPrefixMapArg(D, Args, CmdArgs); 5531 5532 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, 5533 options::OPT_ftemplate_depth_EQ)) { 5534 CmdArgs.push_back("-ftemplate-depth"); 5535 CmdArgs.push_back(A->getValue()); 5536 } 5537 5538 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) { 5539 CmdArgs.push_back("-foperator-arrow-depth"); 5540 CmdArgs.push_back(A->getValue()); 5541 } 5542 5543 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { 5544 CmdArgs.push_back("-fconstexpr-depth"); 5545 CmdArgs.push_back(A->getValue()); 5546 } 5547 5548 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) { 5549 CmdArgs.push_back("-fconstexpr-steps"); 5550 CmdArgs.push_back(A->getValue()); 5551 } 5552 5553 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter)) 5554 CmdArgs.push_back("-fexperimental-new-constant-interpreter"); 5555 5556 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) { 5557 CmdArgs.push_back("-fbracket-depth"); 5558 CmdArgs.push_back(A->getValue()); 5559 } 5560 5561 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, 5562 options::OPT_Wlarge_by_value_copy_def)) { 5563 if (A->getNumValues()) { 5564 StringRef bytes = A->getValue(); 5565 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes)); 5566 } else 5567 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value 5568 } 5569 5570 if (Args.hasArg(options::OPT_relocatable_pch)) 5571 CmdArgs.push_back("-relocatable-pch"); 5572 5573 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) { 5574 static const char *kCFABIs[] = { 5575 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1", 5576 }; 5577 5578 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs)) 5579 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue(); 5580 else 5581 A->render(Args, CmdArgs); 5582 } 5583 5584 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { 5585 CmdArgs.push_back("-fconstant-string-class"); 5586 CmdArgs.push_back(A->getValue()); 5587 } 5588 5589 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { 5590 CmdArgs.push_back("-ftabstop"); 5591 CmdArgs.push_back(A->getValue()); 5592 } 5593 5594 if (Args.hasFlag(options::OPT_fstack_size_section, 5595 options::OPT_fno_stack_size_section, RawTriple.isPS4())) 5596 CmdArgs.push_back("-fstack-size-section"); 5597 5598 if (Args.hasArg(options::OPT_fstack_usage)) { 5599 CmdArgs.push_back("-stack-usage-file"); 5600 5601 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 5602 SmallString<128> OutputFilename(OutputOpt->getValue()); 5603 llvm::sys::path::replace_extension(OutputFilename, "su"); 5604 CmdArgs.push_back(Args.MakeArgString(OutputFilename)); 5605 } else 5606 CmdArgs.push_back( 5607 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su")); 5608 } 5609 5610 CmdArgs.push_back("-ferror-limit"); 5611 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) 5612 CmdArgs.push_back(A->getValue()); 5613 else 5614 CmdArgs.push_back("19"); 5615 5616 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) { 5617 CmdArgs.push_back("-fmacro-backtrace-limit"); 5618 CmdArgs.push_back(A->getValue()); 5619 } 5620 5621 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { 5622 CmdArgs.push_back("-ftemplate-backtrace-limit"); 5623 CmdArgs.push_back(A->getValue()); 5624 } 5625 5626 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { 5627 CmdArgs.push_back("-fconstexpr-backtrace-limit"); 5628 CmdArgs.push_back(A->getValue()); 5629 } 5630 5631 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) { 5632 CmdArgs.push_back("-fspell-checking-limit"); 5633 CmdArgs.push_back(A->getValue()); 5634 } 5635 5636 // Pass -fmessage-length=. 5637 unsigned MessageLength = 0; 5638 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { 5639 StringRef V(A->getValue()); 5640 if (V.getAsInteger(0, MessageLength)) 5641 D.Diag(diag::err_drv_invalid_argument_to_option) 5642 << V << A->getOption().getName(); 5643 } else { 5644 // If -fmessage-length=N was not specified, determine whether this is a 5645 // terminal and, if so, implicitly define -fmessage-length appropriately. 5646 MessageLength = llvm::sys::Process::StandardErrColumns(); 5647 } 5648 if (MessageLength != 0) 5649 CmdArgs.push_back( 5650 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength))); 5651 5652 // -fvisibility= and -fvisibility-ms-compat are of a piece. 5653 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ, 5654 options::OPT_fvisibility_ms_compat)) { 5655 if (A->getOption().matches(options::OPT_fvisibility_EQ)) { 5656 CmdArgs.push_back("-fvisibility"); 5657 CmdArgs.push_back(A->getValue()); 5658 } else { 5659 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat)); 5660 CmdArgs.push_back("-fvisibility"); 5661 CmdArgs.push_back("hidden"); 5662 CmdArgs.push_back("-ftype-visibility"); 5663 CmdArgs.push_back("default"); 5664 } 5665 } 5666 5667 if (!RawTriple.isPS4()) 5668 if (const Arg *A = 5669 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass, 5670 options::OPT_fno_visibility_from_dllstorageclass)) { 5671 if (A->getOption().matches( 5672 options::OPT_fvisibility_from_dllstorageclass)) { 5673 CmdArgs.push_back("-fvisibility-from-dllstorageclass"); 5674 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ); 5675 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ); 5676 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ); 5677 Args.AddLastArg(CmdArgs, 5678 options::OPT_fvisibility_externs_nodllstorageclass_EQ); 5679 } 5680 } 5681 5682 if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) { 5683 if (Triple.isOSAIX()) 5684 CmdArgs.push_back("-mignore-xcoff-visibility"); 5685 else 5686 D.Diag(diag::err_drv_unsupported_opt_for_target) 5687 << A->getAsString(Args) << TripleStr; 5688 } 5689 5690 5691 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden, 5692 options::OPT_fno_visibility_inlines_hidden, false)) 5693 CmdArgs.push_back("-fvisibility-inlines-hidden"); 5694 5695 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var, 5696 options::OPT_fno_visibility_inlines_hidden_static_local_var); 5697 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden); 5698 Args.AddLastArg(CmdArgs, options::OPT_fnew_infallible); 5699 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ); 5700 5701 if (Args.hasFlag(options::OPT_fno_operator_names, 5702 options::OPT_foperator_names, false)) 5703 CmdArgs.push_back("-fno-operator-names"); 5704 5705 // Forward -f (flag) options which we can pass directly. 5706 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); 5707 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); 5708 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs); 5709 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls, 5710 options::OPT_fno_emulated_tls); 5711 5712 // AltiVec-like language extensions aren't relevant for assembling. 5713 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) 5714 Args.AddLastArg(CmdArgs, options::OPT_fzvector); 5715 5716 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree); 5717 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type); 5718 5719 // Forward flags for OpenMP. We don't do this if the current action is an 5720 // device offloading action other than OpenMP. 5721 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 5722 options::OPT_fno_openmp, false) && 5723 (JA.isDeviceOffloading(Action::OFK_None) || 5724 JA.isDeviceOffloading(Action::OFK_OpenMP))) { 5725 switch (D.getOpenMPRuntime(Args)) { 5726 case Driver::OMPRT_OMP: 5727 case Driver::OMPRT_IOMP5: 5728 // Clang can generate useful OpenMP code for these two runtime libraries. 5729 CmdArgs.push_back("-fopenmp"); 5730 5731 // If no option regarding the use of TLS in OpenMP codegeneration is 5732 // given, decide a default based on the target. Otherwise rely on the 5733 // options and pass the right information to the frontend. 5734 if (!Args.hasFlag(options::OPT_fopenmp_use_tls, 5735 options::OPT_fnoopenmp_use_tls, /*Default=*/true)) 5736 CmdArgs.push_back("-fnoopenmp-use-tls"); 5737 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 5738 options::OPT_fno_openmp_simd); 5739 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder); 5740 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 5741 if (!Args.hasFlag(options::OPT_fopenmp_extensions, 5742 options::OPT_fno_openmp_extensions, /*Default=*/true)) 5743 CmdArgs.push_back("-fno-openmp-extensions"); 5744 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ); 5745 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ); 5746 Args.AddAllArgs(CmdArgs, 5747 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ); 5748 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse, 5749 options::OPT_fno_openmp_optimistic_collapse, 5750 /*Default=*/false)) 5751 CmdArgs.push_back("-fopenmp-optimistic-collapse"); 5752 5753 // When in OpenMP offloading mode with NVPTX target, forward 5754 // cuda-mode flag 5755 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode, 5756 options::OPT_fno_openmp_cuda_mode, /*Default=*/false)) 5757 CmdArgs.push_back("-fopenmp-cuda-mode"); 5758 5759 // When in OpenMP offloading mode with NVPTX target, check if full runtime 5760 // is required. 5761 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime, 5762 options::OPT_fno_openmp_cuda_force_full_runtime, 5763 /*Default=*/false)) 5764 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime"); 5765 break; 5766 default: 5767 // By default, if Clang doesn't know how to generate useful OpenMP code 5768 // for a specific runtime library, we just don't pass the '-fopenmp' flag 5769 // down to the actual compilation. 5770 // FIXME: It would be better to have a mode which *only* omits IR 5771 // generation based on the OpenMP support so that we get consistent 5772 // semantic analysis, etc. 5773 break; 5774 } 5775 } else { 5776 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 5777 options::OPT_fno_openmp_simd); 5778 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 5779 if (!Args.hasFlag(options::OPT_fopenmp_extensions, 5780 options::OPT_fno_openmp_extensions, /*Default=*/true)) 5781 CmdArgs.push_back("-fno-openmp-extensions"); 5782 } 5783 5784 const SanitizerArgs &Sanitize = TC.getSanitizerArgs(); 5785 Sanitize.addArgs(TC, Args, CmdArgs, InputType); 5786 5787 const XRayArgs &XRay = TC.getXRayArgs(); 5788 XRay.addArgs(TC, Args, CmdArgs, InputType); 5789 5790 for (const auto &Filename : 5791 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) { 5792 if (D.getVFS().exists(Filename)) 5793 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename)); 5794 else 5795 D.Diag(clang::diag::err_drv_no_such_file) << Filename; 5796 } 5797 5798 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) { 5799 StringRef S0 = A->getValue(), S = S0; 5800 unsigned Size, Offset = 0; 5801 if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86()) 5802 D.Diag(diag::err_drv_unsupported_opt_for_target) 5803 << A->getAsString(Args) << TripleStr; 5804 else if (S.consumeInteger(10, Size) || 5805 (!S.empty() && (!S.consume_front(",") || 5806 S.consumeInteger(10, Offset) || !S.empty()))) 5807 D.Diag(diag::err_drv_invalid_argument_to_option) 5808 << S0 << A->getOption().getName(); 5809 else if (Size < Offset) 5810 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument); 5811 else { 5812 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size))); 5813 CmdArgs.push_back(Args.MakeArgString( 5814 "-fpatchable-function-entry-offset=" + Twine(Offset))); 5815 } 5816 } 5817 5818 if (TC.SupportsProfiling()) { 5819 Args.AddLastArg(CmdArgs, options::OPT_pg); 5820 5821 llvm::Triple::ArchType Arch = TC.getArch(); 5822 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) { 5823 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86()) 5824 A->render(Args, CmdArgs); 5825 else 5826 D.Diag(diag::err_drv_unsupported_opt_for_target) 5827 << A->getAsString(Args) << TripleStr; 5828 } 5829 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) { 5830 if (Arch == llvm::Triple::systemz) 5831 A->render(Args, CmdArgs); 5832 else 5833 D.Diag(diag::err_drv_unsupported_opt_for_target) 5834 << A->getAsString(Args) << TripleStr; 5835 } 5836 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) { 5837 if (Arch == llvm::Triple::systemz) 5838 A->render(Args, CmdArgs); 5839 else 5840 D.Diag(diag::err_drv_unsupported_opt_for_target) 5841 << A->getAsString(Args) << TripleStr; 5842 } 5843 } 5844 5845 if (Args.getLastArg(options::OPT_fapple_kext) || 5846 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType))) 5847 CmdArgs.push_back("-fapple-kext"); 5848 5849 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat); 5850 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ); 5851 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch); 5852 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info); 5853 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits); 5854 Args.AddLastArg(CmdArgs, options::OPT_ftime_report); 5855 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ); 5856 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace); 5857 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ); 5858 Args.AddLastArg(CmdArgs, options::OPT_ftrapv); 5859 Args.AddLastArg(CmdArgs, options::OPT_malign_double); 5860 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file); 5861 5862 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) { 5863 CmdArgs.push_back("-ftrapv-handler"); 5864 CmdArgs.push_back(A->getValue()); 5865 } 5866 5867 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ); 5868 5869 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but 5870 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. 5871 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) { 5872 if (A->getOption().matches(options::OPT_fwrapv)) 5873 CmdArgs.push_back("-fwrapv"); 5874 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow, 5875 options::OPT_fno_strict_overflow)) { 5876 if (A->getOption().matches(options::OPT_fno_strict_overflow)) 5877 CmdArgs.push_back("-fwrapv"); 5878 } 5879 5880 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops, 5881 options::OPT_fno_reroll_loops)) 5882 if (A->getOption().matches(options::OPT_freroll_loops)) 5883 CmdArgs.push_back("-freroll-loops"); 5884 5885 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops, 5886 options::OPT_fno_finite_loops); 5887 5888 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); 5889 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops, 5890 options::OPT_fno_unroll_loops); 5891 5892 Args.AddLastArg(CmdArgs, options::OPT_pthread); 5893 5894 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, 5895 options::OPT_mno_speculative_load_hardening, false)) 5896 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening")); 5897 5898 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext); 5899 RenderSCPOptions(TC, Args, CmdArgs); 5900 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs); 5901 5902 // Translate -mstackrealign 5903 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign, 5904 false)) 5905 CmdArgs.push_back(Args.MakeArgString("-mstackrealign")); 5906 5907 if (Args.hasArg(options::OPT_mstack_alignment)) { 5908 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment); 5909 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment)); 5910 } 5911 5912 if (Args.hasArg(options::OPT_mstack_probe_size)) { 5913 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size); 5914 5915 if (!Size.empty()) 5916 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size)); 5917 else 5918 CmdArgs.push_back("-mstack-probe-size=0"); 5919 } 5920 5921 if (!Args.hasFlag(options::OPT_mstack_arg_probe, 5922 options::OPT_mno_stack_arg_probe, true)) 5923 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe")); 5924 5925 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it, 5926 options::OPT_mno_restrict_it)) { 5927 if (A->getOption().matches(options::OPT_mrestrict_it)) { 5928 CmdArgs.push_back("-mllvm"); 5929 CmdArgs.push_back("-arm-restrict-it"); 5930 } else { 5931 CmdArgs.push_back("-mllvm"); 5932 CmdArgs.push_back("-arm-no-restrict-it"); 5933 } 5934 } else if (Triple.isOSWindows() && 5935 (Triple.getArch() == llvm::Triple::arm || 5936 Triple.getArch() == llvm::Triple::thumb)) { 5937 // Windows on ARM expects restricted IT blocks 5938 CmdArgs.push_back("-mllvm"); 5939 CmdArgs.push_back("-arm-restrict-it"); 5940 } 5941 5942 // Forward -cl options to -cc1 5943 RenderOpenCLOptions(Args, CmdArgs, InputType); 5944 5945 if (IsHIP) { 5946 if (Args.hasFlag(options::OPT_fhip_new_launch_api, 5947 options::OPT_fno_hip_new_launch_api, true)) 5948 CmdArgs.push_back("-fhip-new-launch-api"); 5949 if (Args.hasFlag(options::OPT_fgpu_allow_device_init, 5950 options::OPT_fno_gpu_allow_device_init, false)) 5951 CmdArgs.push_back("-fgpu-allow-device-init"); 5952 } 5953 5954 if (IsCuda || IsHIP) { 5955 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 5956 CmdArgs.push_back("-fgpu-rdc"); 5957 if (Args.hasFlag(options::OPT_fgpu_defer_diag, 5958 options::OPT_fno_gpu_defer_diag, false)) 5959 CmdArgs.push_back("-fgpu-defer-diag"); 5960 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads, 5961 options::OPT_fno_gpu_exclude_wrong_side_overloads, 5962 false)) { 5963 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads"); 5964 CmdArgs.push_back("-fgpu-defer-diag"); 5965 } 5966 } 5967 5968 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) { 5969 CmdArgs.push_back( 5970 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue())); 5971 } 5972 5973 // Forward -f options with positive and negative forms; we translate these by 5974 // hand. Do not propagate PGO options to the GPU-side compilations as the 5975 // profile info is for the host-side compilation only. 5976 if (!(IsCudaDevice || IsHIPDevice)) { 5977 if (Arg *A = getLastProfileSampleUseArg(Args)) { 5978 auto *PGOArg = Args.getLastArg( 5979 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ, 5980 options::OPT_fcs_profile_generate, 5981 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use, 5982 options::OPT_fprofile_use_EQ); 5983 if (PGOArg) 5984 D.Diag(diag::err_drv_argument_not_allowed_with) 5985 << "SampleUse with PGO options"; 5986 5987 StringRef fname = A->getValue(); 5988 if (!llvm::sys::fs::exists(fname)) 5989 D.Diag(diag::err_drv_no_such_file) << fname; 5990 else 5991 A->render(Args, CmdArgs); 5992 } 5993 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ); 5994 5995 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling, 5996 options::OPT_fno_pseudo_probe_for_profiling, false)) { 5997 CmdArgs.push_back("-fpseudo-probe-for-profiling"); 5998 // Enforce -funique-internal-linkage-names if it's not explicitly turned 5999 // off. 6000 if (Args.hasFlag(options::OPT_funique_internal_linkage_names, 6001 options::OPT_fno_unique_internal_linkage_names, true)) 6002 CmdArgs.push_back("-funique-internal-linkage-names"); 6003 } 6004 } 6005 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs); 6006 6007 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 6008 options::OPT_fno_assume_sane_operator_new)) 6009 CmdArgs.push_back("-fno-assume-sane-operator-new"); 6010 6011 // -fblocks=0 is default. 6012 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks, 6013 TC.IsBlocksDefault()) || 6014 (Args.hasArg(options::OPT_fgnu_runtime) && 6015 Args.hasArg(options::OPT_fobjc_nonfragile_abi) && 6016 !Args.hasArg(options::OPT_fno_blocks))) { 6017 CmdArgs.push_back("-fblocks"); 6018 6019 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime()) 6020 CmdArgs.push_back("-fblocks-runtime-optional"); 6021 } 6022 6023 // -fencode-extended-block-signature=1 is default. 6024 if (TC.IsEncodeExtendedBlockSignatureDefault()) 6025 CmdArgs.push_back("-fencode-extended-block-signature"); 6026 6027 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts, 6028 false) && 6029 types::isCXX(InputType)) { 6030 CmdArgs.push_back("-fcoroutines-ts"); 6031 } 6032 6033 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes, 6034 options::OPT_fno_double_square_bracket_attributes); 6035 6036 // -faccess-control is default. 6037 if (Args.hasFlag(options::OPT_fno_access_control, 6038 options::OPT_faccess_control, false)) 6039 CmdArgs.push_back("-fno-access-control"); 6040 6041 // -felide-constructors is the default. 6042 if (Args.hasFlag(options::OPT_fno_elide_constructors, 6043 options::OPT_felide_constructors, false)) 6044 CmdArgs.push_back("-fno-elide-constructors"); 6045 6046 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); 6047 6048 if (KernelOrKext || (types::isCXX(InputType) && 6049 (RTTIMode == ToolChain::RM_Disabled))) 6050 CmdArgs.push_back("-fno-rtti"); 6051 6052 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS. 6053 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums, 6054 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS())) 6055 CmdArgs.push_back("-fshort-enums"); 6056 6057 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs); 6058 6059 // -fuse-cxa-atexit is default. 6060 if (!Args.hasFlag( 6061 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit, 6062 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() && 6063 TC.getArch() != llvm::Triple::xcore && 6064 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) || 6065 RawTriple.hasEnvironment())) || 6066 KernelOrKext) 6067 CmdArgs.push_back("-fno-use-cxa-atexit"); 6068 6069 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit, 6070 options::OPT_fno_register_global_dtors_with_atexit, 6071 RawTriple.isOSDarwin() && !KernelOrKext)) 6072 CmdArgs.push_back("-fregister-global-dtors-with-atexit"); 6073 6074 // -fno-use-line-directives is default. 6075 if (Args.hasFlag(options::OPT_fuse_line_directives, 6076 options::OPT_fno_use_line_directives, false)) 6077 CmdArgs.push_back("-fuse-line-directives"); 6078 6079 // -fno-minimize-whitespace is default. 6080 if (Args.hasFlag(options::OPT_fminimize_whitespace, 6081 options::OPT_fno_minimize_whitespace, false)) { 6082 types::ID InputType = Inputs[0].getType(); 6083 if (!isDerivedFromC(InputType)) 6084 D.Diag(diag::err_drv_minws_unsupported_input_type) 6085 << types::getTypeName(InputType); 6086 CmdArgs.push_back("-fminimize-whitespace"); 6087 } 6088 6089 // -fms-extensions=0 is default. 6090 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, 6091 IsWindowsMSVC)) 6092 CmdArgs.push_back("-fms-extensions"); 6093 6094 // -fms-compatibility=0 is default. 6095 bool IsMSVCCompat = Args.hasFlag( 6096 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility, 6097 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions, 6098 options::OPT_fno_ms_extensions, true))); 6099 if (IsMSVCCompat) 6100 CmdArgs.push_back("-fms-compatibility"); 6101 6102 // Handle -fgcc-version, if present. 6103 VersionTuple GNUCVer; 6104 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 6105 // Check that the version has 1 to 3 components and the minor and patch 6106 // versions fit in two decimal digits. 6107 StringRef Val = A->getValue(); 6108 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable. 6109 bool Invalid = GNUCVer.tryParse(Val); 6110 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 6111 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 6112 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 6113 D.Diag(diag::err_drv_invalid_value) 6114 << A->getAsString(Args) << A->getValue(); 6115 } 6116 } else if (!IsMSVCCompat) { 6117 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect. 6118 GNUCVer = VersionTuple(4, 2, 1); 6119 } 6120 if (!GNUCVer.empty()) { 6121 CmdArgs.push_back( 6122 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString())); 6123 } 6124 6125 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args); 6126 if (!MSVT.empty()) 6127 CmdArgs.push_back( 6128 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString())); 6129 6130 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19; 6131 if (ImplyVCPPCVer) { 6132 StringRef LanguageStandard; 6133 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 6134 Std = StdArg; 6135 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 6136 .Case("c11", "-std=c11") 6137 .Case("c17", "-std=c17") 6138 .Default(""); 6139 if (LanguageStandard.empty()) 6140 D.Diag(clang::diag::warn_drv_unused_argument) 6141 << StdArg->getAsString(Args); 6142 } 6143 CmdArgs.push_back(LanguageStandard.data()); 6144 } 6145 if (ImplyVCPPCXXVer) { 6146 StringRef LanguageStandard; 6147 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 6148 Std = StdArg; 6149 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 6150 .Case("c++14", "-std=c++14") 6151 .Case("c++17", "-std=c++17") 6152 .Case("c++20", "-std=c++20") 6153 .Case("c++latest", "-std=c++2b") 6154 .Default(""); 6155 if (LanguageStandard.empty()) 6156 D.Diag(clang::diag::warn_drv_unused_argument) 6157 << StdArg->getAsString(Args); 6158 } 6159 6160 if (LanguageStandard.empty()) { 6161 if (IsMSVC2015Compatible) 6162 LanguageStandard = "-std=c++14"; 6163 else 6164 LanguageStandard = "-std=c++11"; 6165 } 6166 6167 CmdArgs.push_back(LanguageStandard.data()); 6168 } 6169 6170 // -fno-borland-extensions is default. 6171 if (Args.hasFlag(options::OPT_fborland_extensions, 6172 options::OPT_fno_borland_extensions, false)) 6173 CmdArgs.push_back("-fborland-extensions"); 6174 6175 // -fno-declspec is default, except for PS4. 6176 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec, 6177 RawTriple.isPS4())) 6178 CmdArgs.push_back("-fdeclspec"); 6179 else if (Args.hasArg(options::OPT_fno_declspec)) 6180 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec. 6181 6182 // -fthreadsafe-static is default, except for MSVC compatibility versions less 6183 // than 19. 6184 if (!Args.hasFlag(options::OPT_fthreadsafe_statics, 6185 options::OPT_fno_threadsafe_statics, 6186 !types::isOpenCL(InputType) && 6187 (!IsWindowsMSVC || IsMSVC2015Compatible))) 6188 CmdArgs.push_back("-fno-threadsafe-statics"); 6189 6190 // -fno-delayed-template-parsing is default, except when targeting MSVC. 6191 // Many old Windows SDK versions require this to parse. 6192 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their 6193 // compiler. We should be able to disable this by default at some point. 6194 if (Args.hasFlag(options::OPT_fdelayed_template_parsing, 6195 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC)) 6196 CmdArgs.push_back("-fdelayed-template-parsing"); 6197 6198 // -fgnu-keywords default varies depending on language; only pass if 6199 // specified. 6200 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords, 6201 options::OPT_fno_gnu_keywords); 6202 6203 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline, 6204 false)) 6205 CmdArgs.push_back("-fgnu89-inline"); 6206 6207 if (Args.hasArg(options::OPT_fno_inline)) 6208 CmdArgs.push_back("-fno-inline"); 6209 6210 Args.AddLastArg(CmdArgs, options::OPT_finline_functions, 6211 options::OPT_finline_hint_functions, 6212 options::OPT_fno_inline_functions); 6213 6214 // FIXME: Find a better way to determine whether the language has modules 6215 // support by default, or just assume that all languages do. 6216 bool HaveModules = 6217 Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") || 6218 Std->containsValue("c++latest")); 6219 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules); 6220 6221 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content, 6222 options::OPT_fno_pch_validate_input_files_content, false)) 6223 CmdArgs.push_back("-fvalidate-ast-input-files-content"); 6224 if (Args.hasFlag(options::OPT_fpch_instantiate_templates, 6225 options::OPT_fno_pch_instantiate_templates, false)) 6226 CmdArgs.push_back("-fpch-instantiate-templates"); 6227 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen, 6228 false)) 6229 CmdArgs.push_back("-fmodules-codegen"); 6230 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo, 6231 false)) 6232 CmdArgs.push_back("-fmodules-debuginfo"); 6233 6234 Args.AddLastArg(CmdArgs, options::OPT_flegacy_pass_manager, 6235 options::OPT_fno_legacy_pass_manager); 6236 6237 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind); 6238 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None, 6239 Input, CmdArgs); 6240 6241 if (types::isObjC(Input.getType()) && 6242 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec, 6243 options::OPT_fno_objc_encode_cxx_class_template_spec, 6244 !Runtime.isNeXTFamily())) 6245 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec"); 6246 6247 if (Args.hasFlag(options::OPT_fapplication_extension, 6248 options::OPT_fno_application_extension, false)) 6249 CmdArgs.push_back("-fapplication-extension"); 6250 6251 // Handle GCC-style exception args. 6252 bool EH = false; 6253 if (!C.getDriver().IsCLMode()) 6254 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs); 6255 6256 // Handle exception personalities 6257 Arg *A = Args.getLastArg( 6258 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions, 6259 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions); 6260 if (A) { 6261 const Option &Opt = A->getOption(); 6262 if (Opt.matches(options::OPT_fsjlj_exceptions)) 6263 CmdArgs.push_back("-exception-model=sjlj"); 6264 if (Opt.matches(options::OPT_fseh_exceptions)) 6265 CmdArgs.push_back("-exception-model=seh"); 6266 if (Opt.matches(options::OPT_fdwarf_exceptions)) 6267 CmdArgs.push_back("-exception-model=dwarf"); 6268 if (Opt.matches(options::OPT_fwasm_exceptions)) 6269 CmdArgs.push_back("-exception-model=wasm"); 6270 } else { 6271 switch (TC.GetExceptionModel(Args)) { 6272 default: 6273 break; 6274 case llvm::ExceptionHandling::DwarfCFI: 6275 CmdArgs.push_back("-exception-model=dwarf"); 6276 break; 6277 case llvm::ExceptionHandling::SjLj: 6278 CmdArgs.push_back("-exception-model=sjlj"); 6279 break; 6280 case llvm::ExceptionHandling::WinEH: 6281 CmdArgs.push_back("-exception-model=seh"); 6282 break; 6283 } 6284 } 6285 6286 // C++ "sane" operator new. 6287 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 6288 options::OPT_fno_assume_sane_operator_new)) 6289 CmdArgs.push_back("-fno-assume-sane-operator-new"); 6290 6291 // -frelaxed-template-template-args is off by default, as it is a severe 6292 // breaking change until a corresponding change to template partial ordering 6293 // is provided. 6294 if (Args.hasFlag(options::OPT_frelaxed_template_template_args, 6295 options::OPT_fno_relaxed_template_template_args, false)) 6296 CmdArgs.push_back("-frelaxed-template-template-args"); 6297 6298 // -fsized-deallocation is off by default, as it is an ABI-breaking change for 6299 // most platforms. 6300 if (Args.hasFlag(options::OPT_fsized_deallocation, 6301 options::OPT_fno_sized_deallocation, false)) 6302 CmdArgs.push_back("-fsized-deallocation"); 6303 6304 // -faligned-allocation is on by default in C++17 onwards and otherwise off 6305 // by default. 6306 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation, 6307 options::OPT_fno_aligned_allocation, 6308 options::OPT_faligned_new_EQ)) { 6309 if (A->getOption().matches(options::OPT_fno_aligned_allocation)) 6310 CmdArgs.push_back("-fno-aligned-allocation"); 6311 else 6312 CmdArgs.push_back("-faligned-allocation"); 6313 } 6314 6315 // The default new alignment can be specified using a dedicated option or via 6316 // a GCC-compatible option that also turns on aligned allocation. 6317 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ, 6318 options::OPT_faligned_new_EQ)) 6319 CmdArgs.push_back( 6320 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue())); 6321 6322 // -fconstant-cfstrings is default, and may be subject to argument translation 6323 // on Darwin. 6324 if (!Args.hasFlag(options::OPT_fconstant_cfstrings, 6325 options::OPT_fno_constant_cfstrings) || 6326 !Args.hasFlag(options::OPT_mconstant_cfstrings, 6327 options::OPT_mno_constant_cfstrings)) 6328 CmdArgs.push_back("-fno-constant-cfstrings"); 6329 6330 // -fno-pascal-strings is default, only pass non-default. 6331 if (Args.hasFlag(options::OPT_fpascal_strings, 6332 options::OPT_fno_pascal_strings, false)) 6333 CmdArgs.push_back("-fpascal-strings"); 6334 6335 // Honor -fpack-struct= and -fpack-struct, if given. Note that 6336 // -fno-pack-struct doesn't apply to -fpack-struct=. 6337 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) { 6338 std::string PackStructStr = "-fpack-struct="; 6339 PackStructStr += A->getValue(); 6340 CmdArgs.push_back(Args.MakeArgString(PackStructStr)); 6341 } else if (Args.hasFlag(options::OPT_fpack_struct, 6342 options::OPT_fno_pack_struct, false)) { 6343 CmdArgs.push_back("-fpack-struct=1"); 6344 } 6345 6346 // Handle -fmax-type-align=N and -fno-type-align 6347 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align); 6348 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) { 6349 if (!SkipMaxTypeAlign) { 6350 std::string MaxTypeAlignStr = "-fmax-type-align="; 6351 MaxTypeAlignStr += A->getValue(); 6352 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 6353 } 6354 } else if (RawTriple.isOSDarwin()) { 6355 if (!SkipMaxTypeAlign) { 6356 std::string MaxTypeAlignStr = "-fmax-type-align=16"; 6357 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 6358 } 6359 } 6360 6361 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true)) 6362 CmdArgs.push_back("-Qn"); 6363 6364 // -fno-common is the default, set -fcommon only when that flag is set. 6365 if (Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common, false)) 6366 CmdArgs.push_back("-fcommon"); 6367 6368 // -fsigned-bitfields is default, and clang doesn't yet support 6369 // -funsigned-bitfields. 6370 if (!Args.hasFlag(options::OPT_fsigned_bitfields, 6371 options::OPT_funsigned_bitfields)) 6372 D.Diag(diag::warn_drv_clang_unsupported) 6373 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); 6374 6375 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope. 6376 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope)) 6377 D.Diag(diag::err_drv_clang_unsupported) 6378 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args); 6379 6380 // -finput_charset=UTF-8 is default. Reject others 6381 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) { 6382 StringRef value = inputCharset->getValue(); 6383 if (!value.equals_insensitive("utf-8")) 6384 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) 6385 << value; 6386 } 6387 6388 // -fexec_charset=UTF-8 is default. Reject others 6389 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) { 6390 StringRef value = execCharset->getValue(); 6391 if (!value.equals_insensitive("utf-8")) 6392 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) 6393 << value; 6394 } 6395 6396 RenderDiagnosticsOptions(D, Args, CmdArgs); 6397 6398 // -fno-asm-blocks is default. 6399 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks, 6400 false)) 6401 CmdArgs.push_back("-fasm-blocks"); 6402 6403 // -fgnu-inline-asm is default. 6404 if (!Args.hasFlag(options::OPT_fgnu_inline_asm, 6405 options::OPT_fno_gnu_inline_asm, true)) 6406 CmdArgs.push_back("-fno-gnu-inline-asm"); 6407 6408 // Enable vectorization per default according to the optimization level 6409 // selected. For optimization levels that want vectorization we use the alias 6410 // option to simplify the hasFlag logic. 6411 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false); 6412 OptSpecifier VectorizeAliasOption = 6413 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize; 6414 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption, 6415 options::OPT_fno_vectorize, EnableVec)) 6416 CmdArgs.push_back("-vectorize-loops"); 6417 6418 // -fslp-vectorize is enabled based on the optimization level selected. 6419 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true); 6420 OptSpecifier SLPVectAliasOption = 6421 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize; 6422 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption, 6423 options::OPT_fno_slp_vectorize, EnableSLPVec)) 6424 CmdArgs.push_back("-vectorize-slp"); 6425 6426 ParseMPreferVectorWidth(D, Args, CmdArgs); 6427 6428 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ); 6429 Args.AddLastArg(CmdArgs, 6430 options::OPT_fsanitize_undefined_strip_path_components_EQ); 6431 6432 // -fdollars-in-identifiers default varies depending on platform and 6433 // language; only pass if specified. 6434 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, 6435 options::OPT_fno_dollars_in_identifiers)) { 6436 if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) 6437 CmdArgs.push_back("-fdollars-in-identifiers"); 6438 else 6439 CmdArgs.push_back("-fno-dollars-in-identifiers"); 6440 } 6441 6442 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for 6443 // practical purposes. 6444 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, 6445 options::OPT_fno_unit_at_a_time)) { 6446 if (A->getOption().matches(options::OPT_fno_unit_at_a_time)) 6447 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args); 6448 } 6449 6450 if (Args.hasFlag(options::OPT_fapple_pragma_pack, 6451 options::OPT_fno_apple_pragma_pack, false)) 6452 CmdArgs.push_back("-fapple-pragma-pack"); 6453 6454 if (Args.hasFlag(options::OPT_fxl_pragma_pack, 6455 options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX())) 6456 CmdArgs.push_back("-fxl-pragma-pack"); 6457 6458 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags. 6459 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple)) 6460 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA); 6461 6462 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports, 6463 options::OPT_fno_rewrite_imports, false); 6464 if (RewriteImports) 6465 CmdArgs.push_back("-frewrite-imports"); 6466 6467 // Enable rewrite includes if the user's asked for it or if we're generating 6468 // diagnostics. 6469 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be 6470 // nice to enable this when doing a crashdump for modules as well. 6471 if (Args.hasFlag(options::OPT_frewrite_includes, 6472 options::OPT_fno_rewrite_includes, false) || 6473 (C.isForDiagnostics() && !HaveModules)) 6474 CmdArgs.push_back("-frewrite-includes"); 6475 6476 // Only allow -traditional or -traditional-cpp outside in preprocessing modes. 6477 if (Arg *A = Args.getLastArg(options::OPT_traditional, 6478 options::OPT_traditional_cpp)) { 6479 if (isa<PreprocessJobAction>(JA)) 6480 CmdArgs.push_back("-traditional-cpp"); 6481 else 6482 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); 6483 } 6484 6485 Args.AddLastArg(CmdArgs, options::OPT_dM); 6486 Args.AddLastArg(CmdArgs, options::OPT_dD); 6487 6488 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ); 6489 6490 // Handle serialized diagnostics. 6491 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) { 6492 CmdArgs.push_back("-serialize-diagnostic-file"); 6493 CmdArgs.push_back(Args.MakeArgString(A->getValue())); 6494 } 6495 6496 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers)) 6497 CmdArgs.push_back("-fretain-comments-from-system-headers"); 6498 6499 // Forward -fcomment-block-commands to -cc1. 6500 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands); 6501 // Forward -fparse-all-comments to -cc1. 6502 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments); 6503 6504 // Turn -fplugin=name.so into -load name.so 6505 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) { 6506 CmdArgs.push_back("-load"); 6507 CmdArgs.push_back(A->getValue()); 6508 A->claim(); 6509 } 6510 6511 // Forward -fpass-plugin=name.so to -cc1. 6512 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) { 6513 CmdArgs.push_back( 6514 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue())); 6515 A->claim(); 6516 } 6517 6518 // Setup statistics file output. 6519 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 6520 if (!StatsFile.empty()) 6521 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); 6522 6523 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option 6524 // parser. 6525 // -finclude-default-header flag is for preprocessor, 6526 // do not pass it to other cc1 commands when save-temps is enabled 6527 if (C.getDriver().isSaveTempsEnabled() && 6528 !isa<PreprocessJobAction>(JA)) { 6529 for (auto Arg : Args.filtered(options::OPT_Xclang)) { 6530 Arg->claim(); 6531 if (StringRef(Arg->getValue()) != "-finclude-default-header") 6532 CmdArgs.push_back(Arg->getValue()); 6533 } 6534 } 6535 else { 6536 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); 6537 } 6538 for (const Arg *A : Args.filtered(options::OPT_mllvm)) { 6539 A->claim(); 6540 6541 // We translate this by hand to the -cc1 argument, since nightly test uses 6542 // it and developers have been trained to spell it with -mllvm. Both 6543 // spellings are now deprecated and should be removed. 6544 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") { 6545 CmdArgs.push_back("-disable-llvm-optzns"); 6546 } else { 6547 A->render(Args, CmdArgs); 6548 } 6549 } 6550 6551 // With -save-temps, we want to save the unoptimized bitcode output from the 6552 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated 6553 // by the frontend. 6554 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it 6555 // has slightly different breakdown between stages. 6556 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of 6557 // pristine IR generated by the frontend. Ideally, a new compile action should 6558 // be added so both IR can be captured. 6559 if ((C.getDriver().isSaveTempsEnabled() || 6560 JA.isHostOffloading(Action::OFK_OpenMP)) && 6561 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) && 6562 isa<CompileJobAction>(JA)) 6563 CmdArgs.push_back("-disable-llvm-passes"); 6564 6565 Args.AddAllArgs(CmdArgs, options::OPT_undef); 6566 6567 const char *Exec = D.getClangProgramPath(); 6568 6569 // Optionally embed the -cc1 level arguments into the debug info or a 6570 // section, for build analysis. 6571 // Also record command line arguments into the debug info if 6572 // -grecord-gcc-switches options is set on. 6573 // By default, -gno-record-gcc-switches is set on and no recording. 6574 auto GRecordSwitches = 6575 Args.hasFlag(options::OPT_grecord_command_line, 6576 options::OPT_gno_record_command_line, false); 6577 auto FRecordSwitches = 6578 Args.hasFlag(options::OPT_frecord_command_line, 6579 options::OPT_fno_record_command_line, false); 6580 if (FRecordSwitches && !Triple.isOSBinFormatELF()) 6581 D.Diag(diag::err_drv_unsupported_opt_for_target) 6582 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args) 6583 << TripleStr; 6584 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) { 6585 ArgStringList OriginalArgs; 6586 for (const auto &Arg : Args) 6587 Arg->render(Args, OriginalArgs); 6588 6589 SmallString<256> Flags; 6590 EscapeSpacesAndBackslashes(Exec, Flags); 6591 for (const char *OriginalArg : OriginalArgs) { 6592 SmallString<128> EscapedArg; 6593 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 6594 Flags += " "; 6595 Flags += EscapedArg; 6596 } 6597 auto FlagsArgString = Args.MakeArgString(Flags); 6598 if (TC.UseDwarfDebugFlags() || GRecordSwitches) { 6599 CmdArgs.push_back("-dwarf-debug-flags"); 6600 CmdArgs.push_back(FlagsArgString); 6601 } 6602 if (FRecordSwitches) { 6603 CmdArgs.push_back("-record-command-line"); 6604 CmdArgs.push_back(FlagsArgString); 6605 } 6606 } 6607 6608 // Host-side cuda compilation receives all device-side outputs in a single 6609 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary. 6610 if ((IsCuda || IsHIP) && CudaDeviceInput) { 6611 CmdArgs.push_back("-fcuda-include-gpubinary"); 6612 CmdArgs.push_back(CudaDeviceInput->getFilename()); 6613 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 6614 CmdArgs.push_back("-fgpu-rdc"); 6615 } 6616 6617 if (IsCuda) { 6618 if (Args.hasFlag(options::OPT_fcuda_short_ptr, 6619 options::OPT_fno_cuda_short_ptr, false)) 6620 CmdArgs.push_back("-fcuda-short-ptr"); 6621 } 6622 6623 if (IsCuda || IsHIP) { 6624 // Determine the original source input. 6625 const Action *SourceAction = &JA; 6626 while (SourceAction->getKind() != Action::InputClass) { 6627 assert(!SourceAction->getInputs().empty() && "unexpected root action!"); 6628 SourceAction = SourceAction->getInputs()[0]; 6629 } 6630 auto CUID = cast<InputAction>(SourceAction)->getId(); 6631 if (!CUID.empty()) 6632 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID))); 6633 } 6634 6635 if (IsHIP) 6636 CmdArgs.push_back("-fcuda-allow-variadic-functions"); 6637 6638 if (IsCudaDevice || IsHIPDevice) { 6639 StringRef InlineThresh = 6640 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ); 6641 if (!InlineThresh.empty()) { 6642 std::string ArgStr = 6643 std::string("-inline-threshold=") + InlineThresh.str(); 6644 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)}); 6645 } 6646 } 6647 6648 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path 6649 // to specify the result of the compile phase on the host, so the meaningful 6650 // device declarations can be identified. Also, -fopenmp-is-device is passed 6651 // along to tell the frontend that it is generating code for a device, so that 6652 // only the relevant declarations are emitted. 6653 if (IsOpenMPDevice) { 6654 CmdArgs.push_back("-fopenmp-is-device"); 6655 if (OpenMPDeviceInput) { 6656 CmdArgs.push_back("-fopenmp-host-ir-file-path"); 6657 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename())); 6658 } 6659 } 6660 6661 if (Triple.isAMDGPU()) { 6662 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs); 6663 6664 if (Args.hasFlag(options::OPT_munsafe_fp_atomics, 6665 options::OPT_mno_unsafe_fp_atomics, /*Default=*/false)) 6666 CmdArgs.push_back("-munsafe-fp-atomics"); 6667 } 6668 6669 // For all the host OpenMP offloading compile jobs we need to pass the targets 6670 // information using -fopenmp-targets= option. 6671 if (JA.isHostOffloading(Action::OFK_OpenMP)) { 6672 SmallString<128> TargetInfo("-fopenmp-targets="); 6673 6674 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ); 6675 assert(Tgts && Tgts->getNumValues() && 6676 "OpenMP offloading has to have targets specified."); 6677 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) { 6678 if (i) 6679 TargetInfo += ','; 6680 // We need to get the string from the triple because it may be not exactly 6681 // the same as the one we get directly from the arguments. 6682 llvm::Triple T(Tgts->getValue(i)); 6683 TargetInfo += T.getTriple(); 6684 } 6685 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str())); 6686 } 6687 6688 bool VirtualFunctionElimination = 6689 Args.hasFlag(options::OPT_fvirtual_function_elimination, 6690 options::OPT_fno_virtual_function_elimination, false); 6691 if (VirtualFunctionElimination) { 6692 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO 6693 // in the future). 6694 if (LTOMode != LTOK_Full) 6695 D.Diag(diag::err_drv_argument_only_allowed_with) 6696 << "-fvirtual-function-elimination" 6697 << "-flto=full"; 6698 6699 CmdArgs.push_back("-fvirtual-function-elimination"); 6700 } 6701 6702 // VFE requires whole-program-vtables, and enables it by default. 6703 bool WholeProgramVTables = Args.hasFlag( 6704 options::OPT_fwhole_program_vtables, 6705 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination); 6706 if (VirtualFunctionElimination && !WholeProgramVTables) { 6707 D.Diag(diag::err_drv_argument_not_allowed_with) 6708 << "-fno-whole-program-vtables" 6709 << "-fvirtual-function-elimination"; 6710 } 6711 6712 if (WholeProgramVTables) { 6713 // Propagate -fwhole-program-vtables if this is an LTO compile. 6714 if (IsUsingLTO) 6715 CmdArgs.push_back("-fwhole-program-vtables"); 6716 // Check if we passed LTO options but they were suppressed because this is a 6717 // device offloading action, or we passed device offload LTO options which 6718 // were suppressed because this is not the device offload action. 6719 // Otherwise, issue an error. 6720 else if (!D.isUsingLTO(!IsDeviceOffloadAction)) 6721 D.Diag(diag::err_drv_argument_only_allowed_with) 6722 << "-fwhole-program-vtables" 6723 << "-flto"; 6724 } 6725 6726 bool DefaultsSplitLTOUnit = 6727 (WholeProgramVTables || Sanitize.needsLTO()) && 6728 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit()); 6729 bool SplitLTOUnit = 6730 Args.hasFlag(options::OPT_fsplit_lto_unit, 6731 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit); 6732 if (Sanitize.needsLTO() && !SplitLTOUnit) 6733 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit" 6734 << "-fsanitize=cfi"; 6735 if (SplitLTOUnit) 6736 CmdArgs.push_back("-fsplit-lto-unit"); 6737 6738 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel, 6739 options::OPT_fno_global_isel)) { 6740 CmdArgs.push_back("-mllvm"); 6741 if (A->getOption().matches(options::OPT_fglobal_isel)) { 6742 CmdArgs.push_back("-global-isel=1"); 6743 6744 // GISel is on by default on AArch64 -O0, so don't bother adding 6745 // the fallback remarks for it. Other combinations will add a warning of 6746 // some kind. 6747 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64; 6748 bool IsOptLevelSupported = false; 6749 6750 Arg *A = Args.getLastArg(options::OPT_O_Group); 6751 if (Triple.getArch() == llvm::Triple::aarch64) { 6752 if (!A || A->getOption().matches(options::OPT_O0)) 6753 IsOptLevelSupported = true; 6754 } 6755 if (!IsArchSupported || !IsOptLevelSupported) { 6756 CmdArgs.push_back("-mllvm"); 6757 CmdArgs.push_back("-global-isel-abort=2"); 6758 6759 if (!IsArchSupported) 6760 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName(); 6761 else 6762 D.Diag(diag::warn_drv_global_isel_incomplete_opt); 6763 } 6764 } else { 6765 CmdArgs.push_back("-global-isel=0"); 6766 } 6767 } 6768 6769 if (Args.hasArg(options::OPT_forder_file_instrumentation)) { 6770 CmdArgs.push_back("-forder-file-instrumentation"); 6771 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is 6772 // on, we need to pass these flags as linker flags and that will be handled 6773 // outside of the compiler. 6774 if (!IsUsingLTO) { 6775 CmdArgs.push_back("-mllvm"); 6776 CmdArgs.push_back("-enable-order-file-instrumentation"); 6777 } 6778 } 6779 6780 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128, 6781 options::OPT_fno_force_enable_int128)) { 6782 if (A->getOption().matches(options::OPT_fforce_enable_int128)) 6783 CmdArgs.push_back("-fforce-enable-int128"); 6784 } 6785 6786 if (Args.hasFlag(options::OPT_fkeep_static_consts, 6787 options::OPT_fno_keep_static_consts, false)) 6788 CmdArgs.push_back("-fkeep-static-consts"); 6789 6790 if (Args.hasFlag(options::OPT_fcomplete_member_pointers, 6791 options::OPT_fno_complete_member_pointers, false)) 6792 CmdArgs.push_back("-fcomplete-member-pointers"); 6793 6794 if (!Args.hasFlag(options::OPT_fcxx_static_destructors, 6795 options::OPT_fno_cxx_static_destructors, true)) 6796 CmdArgs.push_back("-fno-c++-static-destructors"); 6797 6798 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false); 6799 6800 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics, 6801 options::OPT_mno_outline_atomics)) { 6802 if (A->getOption().matches(options::OPT_moutline_atomics)) { 6803 // Option -moutline-atomics supported for AArch64 target only. 6804 if (!Triple.isAArch64()) { 6805 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt) 6806 << Triple.getArchName(); 6807 } else { 6808 CmdArgs.push_back("-target-feature"); 6809 CmdArgs.push_back("+outline-atomics"); 6810 } 6811 } else { 6812 CmdArgs.push_back("-target-feature"); 6813 CmdArgs.push_back("-outline-atomics"); 6814 } 6815 } else if (Triple.isAArch64() && 6816 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) { 6817 CmdArgs.push_back("-target-feature"); 6818 CmdArgs.push_back("+outline-atomics"); 6819 } 6820 6821 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig, 6822 (TC.getTriple().isOSBinFormatELF() || 6823 TC.getTriple().isOSBinFormatCOFF()) && 6824 !TC.getTriple().isPS4() && !TC.getTriple().isVE() && 6825 !TC.getTriple().isOSNetBSD() && 6826 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() && 6827 !TC.getTriple().isAndroid() && TC.useIntegratedAs())) 6828 CmdArgs.push_back("-faddrsig"); 6829 6830 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) && 6831 (EH || UnwindTables || DebugInfoKind != codegenoptions::NoDebugInfo)) 6832 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1"); 6833 6834 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) { 6835 std::string Str = A->getAsString(Args); 6836 if (!TC.getTriple().isOSBinFormatELF()) 6837 D.Diag(diag::err_drv_unsupported_opt_for_target) 6838 << Str << TC.getTripleString(); 6839 CmdArgs.push_back(Args.MakeArgString(Str)); 6840 } 6841 6842 // Add the "-o out -x type src.c" flags last. This is done primarily to make 6843 // the -cc1 command easier to edit when reproducing compiler crashes. 6844 if (Output.getType() == types::TY_Dependencies) { 6845 // Handled with other dependency code. 6846 } else if (Output.isFilename()) { 6847 if (Output.getType() == clang::driver::types::TY_IFS_CPP || 6848 Output.getType() == clang::driver::types::TY_IFS) { 6849 SmallString<128> OutputFilename(Output.getFilename()); 6850 llvm::sys::path::replace_extension(OutputFilename, "ifs"); 6851 CmdArgs.push_back("-o"); 6852 CmdArgs.push_back(Args.MakeArgString(OutputFilename)); 6853 } else { 6854 CmdArgs.push_back("-o"); 6855 CmdArgs.push_back(Output.getFilename()); 6856 } 6857 } else { 6858 assert(Output.isNothing() && "Invalid output."); 6859 } 6860 6861 addDashXForInput(Args, Input, CmdArgs); 6862 6863 ArrayRef<InputInfo> FrontendInputs = Input; 6864 if (IsHeaderModulePrecompile) 6865 FrontendInputs = ModuleHeaderInputs; 6866 else if (Input.isNothing()) 6867 FrontendInputs = {}; 6868 6869 for (const InputInfo &Input : FrontendInputs) { 6870 if (Input.isFilename()) 6871 CmdArgs.push_back(Input.getFilename()); 6872 else 6873 Input.getInputArg().renderAsInput(Args, CmdArgs); 6874 } 6875 6876 if (D.CC1Main && !D.CCGenDiagnostics) { 6877 // Invoke the CC1 directly in this process 6878 C.addCommand(std::make_unique<CC1Command>(JA, *this, 6879 ResponseFileSupport::AtFileUTF8(), 6880 Exec, CmdArgs, Inputs, Output)); 6881 } else { 6882 C.addCommand(std::make_unique<Command>(JA, *this, 6883 ResponseFileSupport::AtFileUTF8(), 6884 Exec, CmdArgs, Inputs, Output)); 6885 } 6886 6887 // Make the compile command echo its inputs for /showFilenames. 6888 if (Output.getType() == types::TY_Object && 6889 Args.hasFlag(options::OPT__SLASH_showFilenames, 6890 options::OPT__SLASH_showFilenames_, false)) { 6891 C.getJobs().getJobs().back()->PrintInputFilenames = true; 6892 } 6893 6894 if (Arg *A = Args.getLastArg(options::OPT_pg)) 6895 if (FPKeepKind == CodeGenOptions::FramePointerKind::None && 6896 !Args.hasArg(options::OPT_mfentry)) 6897 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer" 6898 << A->getAsString(Args); 6899 6900 // Claim some arguments which clang supports automatically. 6901 6902 // -fpch-preprocess is used with gcc to add a special marker in the output to 6903 // include the PCH file. 6904 Args.ClaimAllArgs(options::OPT_fpch_preprocess); 6905 6906 // Claim some arguments which clang doesn't support, but we don't 6907 // care to warn the user about. 6908 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group); 6909 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group); 6910 6911 // Disable warnings for clang -E -emit-llvm foo.c 6912 Args.ClaimAllArgs(options::OPT_emit_llvm); 6913 } 6914 6915 Clang::Clang(const ToolChain &TC) 6916 // CAUTION! The first constructor argument ("clang") is not arbitrary, 6917 // as it is for other tools. Some operations on a Tool actually test 6918 // whether that tool is Clang based on the Tool's Name as a string. 6919 : Tool("clang", "clang frontend", TC) {} 6920 6921 Clang::~Clang() {} 6922 6923 /// Add options related to the Objective-C runtime/ABI. 6924 /// 6925 /// Returns true if the runtime is non-fragile. 6926 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args, 6927 const InputInfoList &inputs, 6928 ArgStringList &cmdArgs, 6929 RewriteKind rewriteKind) const { 6930 // Look for the controlling runtime option. 6931 Arg *runtimeArg = 6932 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime, 6933 options::OPT_fobjc_runtime_EQ); 6934 6935 // Just forward -fobjc-runtime= to the frontend. This supercedes 6936 // options about fragility. 6937 if (runtimeArg && 6938 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) { 6939 ObjCRuntime runtime; 6940 StringRef value = runtimeArg->getValue(); 6941 if (runtime.tryParse(value)) { 6942 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime) 6943 << value; 6944 } 6945 if ((runtime.getKind() == ObjCRuntime::GNUstep) && 6946 (runtime.getVersion() >= VersionTuple(2, 0))) 6947 if (!getToolChain().getTriple().isOSBinFormatELF() && 6948 !getToolChain().getTriple().isOSBinFormatCOFF()) { 6949 getToolChain().getDriver().Diag( 6950 diag::err_drv_gnustep_objc_runtime_incompatible_binary) 6951 << runtime.getVersion().getMajor(); 6952 } 6953 6954 runtimeArg->render(args, cmdArgs); 6955 return runtime; 6956 } 6957 6958 // Otherwise, we'll need the ABI "version". Version numbers are 6959 // slightly confusing for historical reasons: 6960 // 1 - Traditional "fragile" ABI 6961 // 2 - Non-fragile ABI, version 1 6962 // 3 - Non-fragile ABI, version 2 6963 unsigned objcABIVersion = 1; 6964 // If -fobjc-abi-version= is present, use that to set the version. 6965 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { 6966 StringRef value = abiArg->getValue(); 6967 if (value == "1") 6968 objcABIVersion = 1; 6969 else if (value == "2") 6970 objcABIVersion = 2; 6971 else if (value == "3") 6972 objcABIVersion = 3; 6973 else 6974 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value; 6975 } else { 6976 // Otherwise, determine if we are using the non-fragile ABI. 6977 bool nonFragileABIIsDefault = 6978 (rewriteKind == RK_NonFragile || 6979 (rewriteKind == RK_None && 6980 getToolChain().IsObjCNonFragileABIDefault())); 6981 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi, 6982 options::OPT_fno_objc_nonfragile_abi, 6983 nonFragileABIIsDefault)) { 6984 // Determine the non-fragile ABI version to use. 6985 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO 6986 unsigned nonFragileABIVersion = 1; 6987 #else 6988 unsigned nonFragileABIVersion = 2; 6989 #endif 6990 6991 if (Arg *abiArg = 6992 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) { 6993 StringRef value = abiArg->getValue(); 6994 if (value == "1") 6995 nonFragileABIVersion = 1; 6996 else if (value == "2") 6997 nonFragileABIVersion = 2; 6998 else 6999 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) 7000 << value; 7001 } 7002 7003 objcABIVersion = 1 + nonFragileABIVersion; 7004 } else { 7005 objcABIVersion = 1; 7006 } 7007 } 7008 7009 // We don't actually care about the ABI version other than whether 7010 // it's non-fragile. 7011 bool isNonFragile = objcABIVersion != 1; 7012 7013 // If we have no runtime argument, ask the toolchain for its default runtime. 7014 // However, the rewriter only really supports the Mac runtime, so assume that. 7015 ObjCRuntime runtime; 7016 if (!runtimeArg) { 7017 switch (rewriteKind) { 7018 case RK_None: 7019 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 7020 break; 7021 case RK_Fragile: 7022 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple()); 7023 break; 7024 case RK_NonFragile: 7025 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 7026 break; 7027 } 7028 7029 // -fnext-runtime 7030 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) { 7031 // On Darwin, make this use the default behavior for the toolchain. 7032 if (getToolChain().getTriple().isOSDarwin()) { 7033 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 7034 7035 // Otherwise, build for a generic macosx port. 7036 } else { 7037 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 7038 } 7039 7040 // -fgnu-runtime 7041 } else { 7042 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime)); 7043 // Legacy behaviour is to target the gnustep runtime if we are in 7044 // non-fragile mode or the GCC runtime in fragile mode. 7045 if (isNonFragile) 7046 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0)); 7047 else 7048 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple()); 7049 } 7050 7051 if (llvm::any_of(inputs, [](const InputInfo &input) { 7052 return types::isObjC(input.getType()); 7053 })) 7054 cmdArgs.push_back( 7055 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString())); 7056 return runtime; 7057 } 7058 7059 static bool maybeConsumeDash(const std::string &EH, size_t &I) { 7060 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-'); 7061 I += HaveDash; 7062 return !HaveDash; 7063 } 7064 7065 namespace { 7066 struct EHFlags { 7067 bool Synch = false; 7068 bool Asynch = false; 7069 bool NoUnwindC = false; 7070 }; 7071 } // end anonymous namespace 7072 7073 /// /EH controls whether to run destructor cleanups when exceptions are 7074 /// thrown. There are three modifiers: 7075 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions. 7076 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions. 7077 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR. 7078 /// - c: Assume that extern "C" functions are implicitly nounwind. 7079 /// The default is /EHs-c-, meaning cleanups are disabled. 7080 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) { 7081 EHFlags EH; 7082 7083 std::vector<std::string> EHArgs = 7084 Args.getAllArgValues(options::OPT__SLASH_EH); 7085 for (auto EHVal : EHArgs) { 7086 for (size_t I = 0, E = EHVal.size(); I != E; ++I) { 7087 switch (EHVal[I]) { 7088 case 'a': 7089 EH.Asynch = maybeConsumeDash(EHVal, I); 7090 if (EH.Asynch) 7091 EH.Synch = false; 7092 continue; 7093 case 'c': 7094 EH.NoUnwindC = maybeConsumeDash(EHVal, I); 7095 continue; 7096 case 's': 7097 EH.Synch = maybeConsumeDash(EHVal, I); 7098 if (EH.Synch) 7099 EH.Asynch = false; 7100 continue; 7101 default: 7102 break; 7103 } 7104 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal; 7105 break; 7106 } 7107 } 7108 // The /GX, /GX- flags are only processed if there are not /EH flags. 7109 // The default is that /GX is not specified. 7110 if (EHArgs.empty() && 7111 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_, 7112 /*Default=*/false)) { 7113 EH.Synch = true; 7114 EH.NoUnwindC = true; 7115 } 7116 7117 return EH; 7118 } 7119 7120 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType, 7121 ArgStringList &CmdArgs, 7122 codegenoptions::DebugInfoKind *DebugInfoKind, 7123 bool *EmitCodeView) const { 7124 unsigned RTOptionID = options::OPT__SLASH_MT; 7125 bool isNVPTX = getToolChain().getTriple().isNVPTX(); 7126 7127 if (Args.hasArg(options::OPT__SLASH_LDd)) 7128 // The /LDd option implies /MTd. The dependent lib part can be overridden, 7129 // but defining _DEBUG is sticky. 7130 RTOptionID = options::OPT__SLASH_MTd; 7131 7132 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) 7133 RTOptionID = A->getOption().getID(); 7134 7135 StringRef FlagForCRT; 7136 switch (RTOptionID) { 7137 case options::OPT__SLASH_MD: 7138 if (Args.hasArg(options::OPT__SLASH_LDd)) 7139 CmdArgs.push_back("-D_DEBUG"); 7140 CmdArgs.push_back("-D_MT"); 7141 CmdArgs.push_back("-D_DLL"); 7142 FlagForCRT = "--dependent-lib=msvcrt"; 7143 break; 7144 case options::OPT__SLASH_MDd: 7145 CmdArgs.push_back("-D_DEBUG"); 7146 CmdArgs.push_back("-D_MT"); 7147 CmdArgs.push_back("-D_DLL"); 7148 FlagForCRT = "--dependent-lib=msvcrtd"; 7149 break; 7150 case options::OPT__SLASH_MT: 7151 if (Args.hasArg(options::OPT__SLASH_LDd)) 7152 CmdArgs.push_back("-D_DEBUG"); 7153 CmdArgs.push_back("-D_MT"); 7154 CmdArgs.push_back("-flto-visibility-public-std"); 7155 FlagForCRT = "--dependent-lib=libcmt"; 7156 break; 7157 case options::OPT__SLASH_MTd: 7158 CmdArgs.push_back("-D_DEBUG"); 7159 CmdArgs.push_back("-D_MT"); 7160 CmdArgs.push_back("-flto-visibility-public-std"); 7161 FlagForCRT = "--dependent-lib=libcmtd"; 7162 break; 7163 default: 7164 llvm_unreachable("Unexpected option ID."); 7165 } 7166 7167 if (Args.hasArg(options::OPT__SLASH_Zl)) { 7168 CmdArgs.push_back("-D_VC_NODEFAULTLIB"); 7169 } else { 7170 CmdArgs.push_back(FlagForCRT.data()); 7171 7172 // This provides POSIX compatibility (maps 'open' to '_open'), which most 7173 // users want. The /Za flag to cl.exe turns this off, but it's not 7174 // implemented in clang. 7175 CmdArgs.push_back("--dependent-lib=oldnames"); 7176 } 7177 7178 if (Arg *ShowIncludes = 7179 Args.getLastArg(options::OPT__SLASH_showIncludes, 7180 options::OPT__SLASH_showIncludes_user)) { 7181 CmdArgs.push_back("--show-includes"); 7182 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes)) 7183 CmdArgs.push_back("-sys-header-deps"); 7184 } 7185 7186 // This controls whether or not we emit RTTI data for polymorphic types. 7187 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR, 7188 /*Default=*/false)) 7189 CmdArgs.push_back("-fno-rtti-data"); 7190 7191 // This controls whether or not we emit stack-protector instrumentation. 7192 // In MSVC, Buffer Security Check (/GS) is on by default. 7193 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_, 7194 /*Default=*/true)) { 7195 CmdArgs.push_back("-stack-protector"); 7196 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong))); 7197 } 7198 7199 // Emit CodeView if -Z7 or -gline-tables-only are present. 7200 if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7, 7201 options::OPT_gline_tables_only)) { 7202 *EmitCodeView = true; 7203 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7)) 7204 *DebugInfoKind = codegenoptions::DebugInfoConstructor; 7205 else 7206 *DebugInfoKind = codegenoptions::DebugLineTablesOnly; 7207 } else { 7208 *EmitCodeView = false; 7209 } 7210 7211 const Driver &D = getToolChain().getDriver(); 7212 EHFlags EH = parseClangCLEHFlags(D, Args); 7213 if (!isNVPTX && (EH.Synch || EH.Asynch)) { 7214 if (types::isCXX(InputType)) 7215 CmdArgs.push_back("-fcxx-exceptions"); 7216 CmdArgs.push_back("-fexceptions"); 7217 } 7218 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC) 7219 CmdArgs.push_back("-fexternc-nounwind"); 7220 7221 // /EP should expand to -E -P. 7222 if (Args.hasArg(options::OPT__SLASH_EP)) { 7223 CmdArgs.push_back("-E"); 7224 CmdArgs.push_back("-P"); 7225 } 7226 7227 unsigned VolatileOptionID; 7228 if (getToolChain().getTriple().isX86()) 7229 VolatileOptionID = options::OPT__SLASH_volatile_ms; 7230 else 7231 VolatileOptionID = options::OPT__SLASH_volatile_iso; 7232 7233 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group)) 7234 VolatileOptionID = A->getOption().getID(); 7235 7236 if (VolatileOptionID == options::OPT__SLASH_volatile_ms) 7237 CmdArgs.push_back("-fms-volatile"); 7238 7239 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_, 7240 options::OPT__SLASH_Zc_dllexportInlines, 7241 false)) { 7242 CmdArgs.push_back("-fno-dllexport-inlines"); 7243 } 7244 7245 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg); 7246 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb); 7247 if (MostGeneralArg && BestCaseArg) 7248 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 7249 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args); 7250 7251 if (MostGeneralArg) { 7252 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms); 7253 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm); 7254 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv); 7255 7256 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg; 7257 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg; 7258 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict) 7259 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 7260 << FirstConflict->getAsString(Args) 7261 << SecondConflict->getAsString(Args); 7262 7263 if (SingleArg) 7264 CmdArgs.push_back("-fms-memptr-rep=single"); 7265 else if (MultipleArg) 7266 CmdArgs.push_back("-fms-memptr-rep=multiple"); 7267 else 7268 CmdArgs.push_back("-fms-memptr-rep=virtual"); 7269 } 7270 7271 // Parse the default calling convention options. 7272 if (Arg *CCArg = 7273 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr, 7274 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv, 7275 options::OPT__SLASH_Gregcall)) { 7276 unsigned DCCOptId = CCArg->getOption().getID(); 7277 const char *DCCFlag = nullptr; 7278 bool ArchSupported = !isNVPTX; 7279 llvm::Triple::ArchType Arch = getToolChain().getArch(); 7280 switch (DCCOptId) { 7281 case options::OPT__SLASH_Gd: 7282 DCCFlag = "-fdefault-calling-conv=cdecl"; 7283 break; 7284 case options::OPT__SLASH_Gr: 7285 ArchSupported = Arch == llvm::Triple::x86; 7286 DCCFlag = "-fdefault-calling-conv=fastcall"; 7287 break; 7288 case options::OPT__SLASH_Gz: 7289 ArchSupported = Arch == llvm::Triple::x86; 7290 DCCFlag = "-fdefault-calling-conv=stdcall"; 7291 break; 7292 case options::OPT__SLASH_Gv: 7293 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 7294 DCCFlag = "-fdefault-calling-conv=vectorcall"; 7295 break; 7296 case options::OPT__SLASH_Gregcall: 7297 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 7298 DCCFlag = "-fdefault-calling-conv=regcall"; 7299 break; 7300 } 7301 7302 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either. 7303 if (ArchSupported && DCCFlag) 7304 CmdArgs.push_back(DCCFlag); 7305 } 7306 7307 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ); 7308 7309 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) { 7310 CmdArgs.push_back("-fdiagnostics-format"); 7311 CmdArgs.push_back("msvc"); 7312 } 7313 7314 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 7315 StringRef GuardArgs = A->getValue(); 7316 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and 7317 // "ehcont-". 7318 if (GuardArgs.equals_insensitive("cf")) { 7319 // Emit CFG instrumentation and the table of address-taken functions. 7320 CmdArgs.push_back("-cfguard"); 7321 } else if (GuardArgs.equals_insensitive("cf,nochecks")) { 7322 // Emit only the table of address-taken functions. 7323 CmdArgs.push_back("-cfguard-no-checks"); 7324 } else if (GuardArgs.equals_insensitive("ehcont")) { 7325 // Emit EH continuation table. 7326 CmdArgs.push_back("-ehcontguard"); 7327 } else if (GuardArgs.equals_insensitive("cf-") || 7328 GuardArgs.equals_insensitive("ehcont-")) { 7329 // Do nothing, but we might want to emit a security warning in future. 7330 } else { 7331 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs; 7332 } 7333 } 7334 } 7335 7336 const char *Clang::getBaseInputName(const ArgList &Args, 7337 const InputInfo &Input) { 7338 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput())); 7339 } 7340 7341 const char *Clang::getBaseInputStem(const ArgList &Args, 7342 const InputInfoList &Inputs) { 7343 const char *Str = getBaseInputName(Args, Inputs[0]); 7344 7345 if (const char *End = strrchr(Str, '.')) 7346 return Args.MakeArgString(std::string(Str, End)); 7347 7348 return Str; 7349 } 7350 7351 const char *Clang::getDependencyFileName(const ArgList &Args, 7352 const InputInfoList &Inputs) { 7353 // FIXME: Think about this more. 7354 7355 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 7356 SmallString<128> OutputFilename(OutputOpt->getValue()); 7357 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d')); 7358 return Args.MakeArgString(OutputFilename); 7359 } 7360 7361 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d"); 7362 } 7363 7364 // Begin ClangAs 7365 7366 void ClangAs::AddMIPSTargetArgs(const ArgList &Args, 7367 ArgStringList &CmdArgs) const { 7368 StringRef CPUName; 7369 StringRef ABIName; 7370 const llvm::Triple &Triple = getToolChain().getTriple(); 7371 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 7372 7373 CmdArgs.push_back("-target-abi"); 7374 CmdArgs.push_back(ABIName.data()); 7375 } 7376 7377 void ClangAs::AddX86TargetArgs(const ArgList &Args, 7378 ArgStringList &CmdArgs) const { 7379 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs, 7380 /*IsLTO=*/false); 7381 7382 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) { 7383 StringRef Value = A->getValue(); 7384 if (Value == "intel" || Value == "att") { 7385 CmdArgs.push_back("-mllvm"); 7386 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value)); 7387 } else { 7388 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument) 7389 << A->getOption().getName() << Value; 7390 } 7391 } 7392 } 7393 7394 void ClangAs::AddRISCVTargetArgs(const ArgList &Args, 7395 ArgStringList &CmdArgs) const { 7396 const llvm::Triple &Triple = getToolChain().getTriple(); 7397 StringRef ABIName = riscv::getRISCVABI(Args, Triple); 7398 7399 CmdArgs.push_back("-target-abi"); 7400 CmdArgs.push_back(ABIName.data()); 7401 } 7402 7403 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, 7404 const InputInfo &Output, const InputInfoList &Inputs, 7405 const ArgList &Args, 7406 const char *LinkingOutput) const { 7407 ArgStringList CmdArgs; 7408 7409 assert(Inputs.size() == 1 && "Unexpected number of inputs."); 7410 const InputInfo &Input = Inputs[0]; 7411 7412 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 7413 const std::string &TripleStr = Triple.getTriple(); 7414 const auto &D = getToolChain().getDriver(); 7415 7416 // Don't warn about "clang -w -c foo.s" 7417 Args.ClaimAllArgs(options::OPT_w); 7418 // and "clang -emit-llvm -c foo.s" 7419 Args.ClaimAllArgs(options::OPT_emit_llvm); 7420 7421 claimNoWarnArgs(Args); 7422 7423 // Invoke ourselves in -cc1as mode. 7424 // 7425 // FIXME: Implement custom jobs for internal actions. 7426 CmdArgs.push_back("-cc1as"); 7427 7428 // Add the "effective" target triple. 7429 CmdArgs.push_back("-triple"); 7430 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 7431 7432 // Set the output mode, we currently only expect to be used as a real 7433 // assembler. 7434 CmdArgs.push_back("-filetype"); 7435 CmdArgs.push_back("obj"); 7436 7437 // Set the main file name, so that debug info works even with 7438 // -save-temps or preprocessed assembly. 7439 CmdArgs.push_back("-main-file-name"); 7440 CmdArgs.push_back(Clang::getBaseInputName(Args, Input)); 7441 7442 // Add the target cpu 7443 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true); 7444 if (!CPU.empty()) { 7445 CmdArgs.push_back("-target-cpu"); 7446 CmdArgs.push_back(Args.MakeArgString(CPU)); 7447 } 7448 7449 // Add the target features 7450 getTargetFeatures(D, Triple, Args, CmdArgs, true); 7451 7452 // Ignore explicit -force_cpusubtype_ALL option. 7453 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 7454 7455 // Pass along any -I options so we get proper .include search paths. 7456 Args.AddAllArgs(CmdArgs, options::OPT_I_Group); 7457 7458 // Determine the original source input. 7459 const Action *SourceAction = &JA; 7460 while (SourceAction->getKind() != Action::InputClass) { 7461 assert(!SourceAction->getInputs().empty() && "unexpected root action!"); 7462 SourceAction = SourceAction->getInputs()[0]; 7463 } 7464 7465 // Forward -g and handle debug info related flags, assuming we are dealing 7466 // with an actual assembly file. 7467 bool WantDebug = false; 7468 Args.ClaimAllArgs(options::OPT_g_Group); 7469 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) 7470 WantDebug = !A->getOption().matches(options::OPT_g0) && 7471 !A->getOption().matches(options::OPT_ggdb0); 7472 7473 unsigned DwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args); 7474 if (const Arg *GDwarfN = getDwarfNArg(Args)) 7475 DwarfVersion = DwarfVersionNum(GDwarfN->getSpelling()); 7476 7477 if (DwarfVersion == 0) 7478 DwarfVersion = getToolChain().GetDefaultDwarfVersion(); 7479 7480 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 7481 7482 if (SourceAction->getType() == types::TY_Asm || 7483 SourceAction->getType() == types::TY_PP_Asm) { 7484 // You might think that it would be ok to set DebugInfoKind outside of 7485 // the guard for source type, however there is a test which asserts 7486 // that some assembler invocation receives no -debug-info-kind, 7487 // and it's not clear whether that test is just overly restrictive. 7488 DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor 7489 : codegenoptions::NoDebugInfo); 7490 // Add the -fdebug-compilation-dir flag if needed. 7491 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS()); 7492 7493 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs); 7494 7495 // Set the AT_producer to the clang version when using the integrated 7496 // assembler on assembly source files. 7497 CmdArgs.push_back("-dwarf-debug-producer"); 7498 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion())); 7499 7500 // And pass along -I options 7501 Args.AddAllArgs(CmdArgs, options::OPT_I); 7502 } 7503 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, 7504 llvm::DebuggerKind::Default); 7505 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion); 7506 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); 7507 7508 7509 // Handle -fPIC et al -- the relocation-model affects the assembler 7510 // for some targets. 7511 llvm::Reloc::Model RelocationModel; 7512 unsigned PICLevel; 7513 bool IsPIE; 7514 std::tie(RelocationModel, PICLevel, IsPIE) = 7515 ParsePICArgs(getToolChain(), Args); 7516 7517 const char *RMName = RelocationModelName(RelocationModel); 7518 if (RMName) { 7519 CmdArgs.push_back("-mrelocation-model"); 7520 CmdArgs.push_back(RMName); 7521 } 7522 7523 // Optionally embed the -cc1as level arguments into the debug info, for build 7524 // analysis. 7525 if (getToolChain().UseDwarfDebugFlags()) { 7526 ArgStringList OriginalArgs; 7527 for (const auto &Arg : Args) 7528 Arg->render(Args, OriginalArgs); 7529 7530 SmallString<256> Flags; 7531 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7532 EscapeSpacesAndBackslashes(Exec, Flags); 7533 for (const char *OriginalArg : OriginalArgs) { 7534 SmallString<128> EscapedArg; 7535 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 7536 Flags += " "; 7537 Flags += EscapedArg; 7538 } 7539 CmdArgs.push_back("-dwarf-debug-flags"); 7540 CmdArgs.push_back(Args.MakeArgString(Flags)); 7541 } 7542 7543 // FIXME: Add -static support, once we have it. 7544 7545 // Add target specific flags. 7546 switch (getToolChain().getArch()) { 7547 default: 7548 break; 7549 7550 case llvm::Triple::mips: 7551 case llvm::Triple::mipsel: 7552 case llvm::Triple::mips64: 7553 case llvm::Triple::mips64el: 7554 AddMIPSTargetArgs(Args, CmdArgs); 7555 break; 7556 7557 case llvm::Triple::x86: 7558 case llvm::Triple::x86_64: 7559 AddX86TargetArgs(Args, CmdArgs); 7560 break; 7561 7562 case llvm::Triple::arm: 7563 case llvm::Triple::armeb: 7564 case llvm::Triple::thumb: 7565 case llvm::Triple::thumbeb: 7566 // This isn't in AddARMTargetArgs because we want to do this for assembly 7567 // only, not C/C++. 7568 if (Args.hasFlag(options::OPT_mdefault_build_attributes, 7569 options::OPT_mno_default_build_attributes, true)) { 7570 CmdArgs.push_back("-mllvm"); 7571 CmdArgs.push_back("-arm-add-build-attributes"); 7572 } 7573 break; 7574 7575 case llvm::Triple::aarch64: 7576 case llvm::Triple::aarch64_32: 7577 case llvm::Triple::aarch64_be: 7578 if (Args.hasArg(options::OPT_mmark_bti_property)) { 7579 CmdArgs.push_back("-mllvm"); 7580 CmdArgs.push_back("-aarch64-mark-bti-property"); 7581 } 7582 break; 7583 7584 case llvm::Triple::riscv32: 7585 case llvm::Triple::riscv64: 7586 AddRISCVTargetArgs(Args, CmdArgs); 7587 break; 7588 } 7589 7590 // Consume all the warning flags. Usually this would be handled more 7591 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as 7592 // doesn't handle that so rather than warning about unused flags that are 7593 // actually used, we'll lie by omission instead. 7594 // FIXME: Stop lying and consume only the appropriate driver flags 7595 Args.ClaimAllArgs(options::OPT_W_Group); 7596 7597 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, 7598 getToolChain().getDriver()); 7599 7600 Args.AddAllArgs(CmdArgs, options::OPT_mllvm); 7601 7602 assert(Output.isFilename() && "Unexpected lipo output."); 7603 CmdArgs.push_back("-o"); 7604 CmdArgs.push_back(Output.getFilename()); 7605 7606 const llvm::Triple &T = getToolChain().getTriple(); 7607 Arg *A; 7608 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split && 7609 T.isOSBinFormatELF()) { 7610 CmdArgs.push_back("-split-dwarf-output"); 7611 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output)); 7612 } 7613 7614 if (Triple.isAMDGPU()) 7615 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs); 7616 7617 assert(Input.isFilename() && "Invalid input."); 7618 CmdArgs.push_back(Input.getFilename()); 7619 7620 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7621 if (D.CC1Main && !D.CCGenDiagnostics) { 7622 // Invoke cc1as directly in this process. 7623 C.addCommand(std::make_unique<CC1Command>(JA, *this, 7624 ResponseFileSupport::AtFileUTF8(), 7625 Exec, CmdArgs, Inputs, Output)); 7626 } else { 7627 C.addCommand(std::make_unique<Command>(JA, *this, 7628 ResponseFileSupport::AtFileUTF8(), 7629 Exec, CmdArgs, Inputs, Output)); 7630 } 7631 } 7632 7633 // Begin OffloadBundler 7634 7635 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA, 7636 const InputInfo &Output, 7637 const InputInfoList &Inputs, 7638 const llvm::opt::ArgList &TCArgs, 7639 const char *LinkingOutput) const { 7640 // The version with only one output is expected to refer to a bundling job. 7641 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!"); 7642 7643 // The bundling command looks like this: 7644 // clang-offload-bundler -type=bc 7645 // -targets=host-triple,openmp-triple1,openmp-triple2 7646 // -outputs=input_file 7647 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 7648 7649 ArgStringList CmdArgs; 7650 7651 // Get the type. 7652 CmdArgs.push_back(TCArgs.MakeArgString( 7653 Twine("-type=") + types::getTypeTempSuffix(Output.getType()))); 7654 7655 assert(JA.getInputs().size() == Inputs.size() && 7656 "Not have inputs for all dependence actions??"); 7657 7658 // Get the targets. 7659 SmallString<128> Triples; 7660 Triples += "-targets="; 7661 for (unsigned I = 0; I < Inputs.size(); ++I) { 7662 if (I) 7663 Triples += ','; 7664 7665 // Find ToolChain for this input. 7666 Action::OffloadKind CurKind = Action::OFK_Host; 7667 const ToolChain *CurTC = &getToolChain(); 7668 const Action *CurDep = JA.getInputs()[I]; 7669 7670 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) { 7671 CurTC = nullptr; 7672 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) { 7673 assert(CurTC == nullptr && "Expected one dependence!"); 7674 CurKind = A->getOffloadingDeviceKind(); 7675 CurTC = TC; 7676 }); 7677 } 7678 Triples += Action::GetOffloadKindName(CurKind); 7679 Triples += '-'; 7680 Triples += CurTC->getTriple().normalize(); 7681 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_OpenMP || 7682 CurKind == Action::OFK_Cuda) && 7683 CurDep->getOffloadingArch()) { 7684 Triples += '-'; 7685 Triples += CurDep->getOffloadingArch(); 7686 } 7687 } 7688 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 7689 7690 // Get bundled file command. 7691 CmdArgs.push_back( 7692 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename())); 7693 7694 // Get unbundled files command. 7695 SmallString<128> UB; 7696 UB += "-inputs="; 7697 for (unsigned I = 0; I < Inputs.size(); ++I) { 7698 if (I) 7699 UB += ','; 7700 7701 // Find ToolChain for this input. 7702 const ToolChain *CurTC = &getToolChain(); 7703 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) { 7704 CurTC = nullptr; 7705 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) { 7706 assert(CurTC == nullptr && "Expected one dependence!"); 7707 CurTC = TC; 7708 }); 7709 UB += C.addTempFile( 7710 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I]))); 7711 } else { 7712 UB += CurTC->getInputFilename(Inputs[I]); 7713 } 7714 } 7715 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 7716 7717 // All the inputs are encoded as commands. 7718 C.addCommand(std::make_unique<Command>( 7719 JA, *this, ResponseFileSupport::None(), 7720 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7721 CmdArgs, None, Output)); 7722 } 7723 7724 void OffloadBundler::ConstructJobMultipleOutputs( 7725 Compilation &C, const JobAction &JA, const InputInfoList &Outputs, 7726 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, 7727 const char *LinkingOutput) const { 7728 // The version with multiple outputs is expected to refer to a unbundling job. 7729 auto &UA = cast<OffloadUnbundlingJobAction>(JA); 7730 7731 // The unbundling command looks like this: 7732 // clang-offload-bundler -type=bc 7733 // -targets=host-triple,openmp-triple1,openmp-triple2 7734 // -inputs=input_file 7735 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 7736 // -unbundle 7737 7738 ArgStringList CmdArgs; 7739 7740 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!"); 7741 InputInfo Input = Inputs.front(); 7742 7743 // Get the type. 7744 CmdArgs.push_back(TCArgs.MakeArgString( 7745 Twine("-type=") + types::getTypeTempSuffix(Input.getType()))); 7746 7747 // Get the targets. 7748 SmallString<128> Triples; 7749 Triples += "-targets="; 7750 auto DepInfo = UA.getDependentActionsInfo(); 7751 for (unsigned I = 0; I < DepInfo.size(); ++I) { 7752 if (I) 7753 Triples += ','; 7754 7755 auto &Dep = DepInfo[I]; 7756 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind); 7757 Triples += '-'; 7758 Triples += Dep.DependentToolChain->getTriple().normalize(); 7759 if ((Dep.DependentOffloadKind == Action::OFK_HIP || 7760 Dep.DependentOffloadKind == Action::OFK_OpenMP || 7761 Dep.DependentOffloadKind == Action::OFK_Cuda) && 7762 !Dep.DependentBoundArch.empty()) { 7763 Triples += '-'; 7764 Triples += Dep.DependentBoundArch; 7765 } 7766 } 7767 7768 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 7769 7770 // Get bundled file command. 7771 CmdArgs.push_back( 7772 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename())); 7773 7774 // Get unbundled files command. 7775 SmallString<128> UB; 7776 UB += "-outputs="; 7777 for (unsigned I = 0; I < Outputs.size(); ++I) { 7778 if (I) 7779 UB += ','; 7780 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]); 7781 } 7782 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 7783 CmdArgs.push_back("-unbundle"); 7784 CmdArgs.push_back("-allow-missing-bundles"); 7785 7786 // All the inputs are encoded as commands. 7787 C.addCommand(std::make_unique<Command>( 7788 JA, *this, ResponseFileSupport::None(), 7789 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7790 CmdArgs, None, Outputs)); 7791 } 7792 7793 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA, 7794 const InputInfo &Output, 7795 const InputInfoList &Inputs, 7796 const ArgList &Args, 7797 const char *LinkingOutput) const { 7798 ArgStringList CmdArgs; 7799 7800 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 7801 7802 // Add the "effective" target triple. 7803 CmdArgs.push_back("-target"); 7804 CmdArgs.push_back(Args.MakeArgString(Triple.getTriple())); 7805 7806 // Add the output file name. 7807 assert(Output.isFilename() && "Invalid output."); 7808 CmdArgs.push_back("-o"); 7809 CmdArgs.push_back(Output.getFilename()); 7810 7811 // Add inputs. 7812 for (const InputInfo &I : Inputs) { 7813 assert(I.isFilename() && "Invalid input."); 7814 CmdArgs.push_back(I.getFilename()); 7815 } 7816 7817 C.addCommand(std::make_unique<Command>( 7818 JA, *this, ResponseFileSupport::None(), 7819 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7820 CmdArgs, Inputs, Output)); 7821 } 7822