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