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