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