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