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