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