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