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