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