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