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