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