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