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