1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/Driver/Driver.h" 11 #include "InputInfo.h" 12 #include "ToolChains.h" 13 #include "clang/Basic/Version.h" 14 #include "clang/Basic/VirtualFileSystem.h" 15 #include "clang/Config/config.h" 16 #include "clang/Driver/Action.h" 17 #include "clang/Driver/Compilation.h" 18 #include "clang/Driver/DriverDiagnostic.h" 19 #include "clang/Driver/Job.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/SanitizerArgs.h" 22 #include "clang/Driver/Tool.h" 23 #include "clang/Driver/ToolChain.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallSet.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include "llvm/ADT/StringSet.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/Option/Arg.h" 31 #include "llvm/Option/ArgList.h" 32 #include "llvm/Option/OptSpecifier.h" 33 #include "llvm/Option/OptTable.h" 34 #include "llvm/Option/Option.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/PrettyStackTrace.h" 40 #include "llvm/Support/Process.h" 41 #include "llvm/Support/Program.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <map> 44 #include <memory> 45 #include <utility> 46 47 using namespace clang::driver; 48 using namespace clang; 49 using namespace llvm::opt; 50 51 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple, 52 DiagnosticsEngine &Diags, 53 IntrusiveRefCntPtr<vfs::FileSystem> VFS) 54 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)), 55 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 56 LTOMode(LTOK_None), ClangExecutable(ClangExecutable), 57 SysRoot(DEFAULT_SYSROOT), UseStdLib(true), 58 DefaultTargetTriple(DefaultTargetTriple), 59 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr), 60 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr), 61 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false), 62 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 63 CCCUsePCH(true), SuppressMissingInputWarning(false) { 64 65 // Provide a sane fallback if no VFS is specified. 66 if (!this->VFS) 67 this->VFS = vfs::getRealFileSystem(); 68 69 Name = llvm::sys::path::filename(ClangExecutable); 70 Dir = llvm::sys::path::parent_path(ClangExecutable); 71 InstalledDir = Dir; // Provide a sensible default installed dir. 72 73 // Compute the path to the resource directory. 74 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 75 SmallString<128> P(Dir); 76 if (ClangResourceDir != "") { 77 llvm::sys::path::append(P, ClangResourceDir); 78 } else { 79 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX); 80 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang", 81 CLANG_VERSION_STRING); 82 } 83 ResourceDir = P.str(); 84 } 85 86 Driver::~Driver() { 87 delete Opts; 88 89 llvm::DeleteContainerSeconds(ToolChains); 90 } 91 92 void Driver::ParseDriverMode(ArrayRef<const char *> Args) { 93 const std::string OptName = 94 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 95 96 for (const char *ArgPtr : Args) { 97 // Ingore nullptrs, they are response file's EOL markers 98 if (ArgPtr == nullptr) 99 continue; 100 const StringRef Arg = ArgPtr; 101 if (!Arg.startswith(OptName)) 102 continue; 103 104 const StringRef Value = Arg.drop_front(OptName.size()); 105 const unsigned M = llvm::StringSwitch<unsigned>(Value) 106 .Case("gcc", GCCMode) 107 .Case("g++", GXXMode) 108 .Case("cpp", CPPMode) 109 .Case("cl", CLMode) 110 .Default(~0U); 111 112 if (M != ~0U) 113 Mode = static_cast<DriverMode>(M); 114 else 115 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 116 } 117 } 118 119 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { 120 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 121 122 unsigned IncludedFlagsBitmask; 123 unsigned ExcludedFlagsBitmask; 124 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 125 getIncludeExcludeOptionFlagMasks(); 126 127 unsigned MissingArgIndex, MissingArgCount; 128 InputArgList Args = 129 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 130 IncludedFlagsBitmask, ExcludedFlagsBitmask); 131 132 // Check for missing argument error. 133 if (MissingArgCount) 134 Diag(clang::diag::err_drv_missing_argument) 135 << Args.getArgString(MissingArgIndex) << MissingArgCount; 136 137 // Check for unsupported options. 138 for (const Arg *A : Args) { 139 if (A->getOption().hasFlag(options::Unsupported)) { 140 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args); 141 continue; 142 } 143 144 // Warn about -mcpu= without an argument. 145 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 146 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 147 } 148 } 149 150 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) 151 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl : 152 diag::err_drv_unknown_argument) 153 << A->getAsString(Args); 154 155 return Args; 156 } 157 158 // Determine which compilation mode we are in. We look for options which 159 // affect the phase, starting with the earliest phases, and record which 160 // option we used to determine the final phase. 161 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 162 Arg **FinalPhaseArg) const { 163 Arg *PhaseArg = nullptr; 164 phases::ID FinalPhase; 165 166 // -{E,EP,P,M,MM} only run the preprocessor. 167 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 168 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 169 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 170 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) { 171 FinalPhase = phases::Preprocess; 172 173 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 174 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 175 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 176 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 177 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 178 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 179 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 180 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 181 options::OPT__analyze_auto)) || 182 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 183 FinalPhase = phases::Compile; 184 185 // -S only runs up to the backend. 186 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 187 FinalPhase = phases::Backend; 188 189 // -c compilation only runs up to the assembler. 190 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 191 FinalPhase = phases::Assemble; 192 193 // Otherwise do everything. 194 } else 195 FinalPhase = phases::Link; 196 197 if (FinalPhaseArg) 198 *FinalPhaseArg = PhaseArg; 199 200 return FinalPhase; 201 } 202 203 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts, 204 StringRef Value) { 205 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value, 206 Args.getBaseArgs().MakeIndex(Value), Value.data()); 207 Args.AddSynthesizedArg(A); 208 A->claim(); 209 return A; 210 } 211 212 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 213 DerivedArgList *DAL = new DerivedArgList(Args); 214 215 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 216 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 217 for (Arg *A : Args) { 218 // Unfortunately, we have to parse some forwarding options (-Xassembler, 219 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 220 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 221 222 // Rewrite linker options, to replace --no-demangle with a custom internal 223 // option. 224 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 225 A->getOption().matches(options::OPT_Xlinker)) && 226 A->containsValue("--no-demangle")) { 227 // Add the rewritten no-demangle argument. 228 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 229 230 // Add the remaining values as Xlinker arguments. 231 for (StringRef Val : A->getValues()) 232 if (Val != "--no-demangle") 233 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val); 234 235 continue; 236 } 237 238 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 239 // some build systems. We don't try to be complete here because we don't 240 // care to encourage this usage model. 241 if (A->getOption().matches(options::OPT_Wp_COMMA) && 242 (A->getValue(0) == StringRef("-MD") || 243 A->getValue(0) == StringRef("-MMD"))) { 244 // Rewrite to -MD/-MMD along with -MF. 245 if (A->getValue(0) == StringRef("-MD")) 246 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 247 else 248 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 249 if (A->getNumValues() == 2) 250 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 251 A->getValue(1)); 252 continue; 253 } 254 255 // Rewrite reserved library names. 256 if (A->getOption().matches(options::OPT_l)) { 257 StringRef Value = A->getValue(); 258 259 // Rewrite unless -nostdlib is present. 260 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") { 261 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx)); 262 continue; 263 } 264 265 // Rewrite unconditionally. 266 if (Value == "cc_kext") { 267 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext)); 268 continue; 269 } 270 } 271 272 // Pick up inputs via the -- option. 273 if (A->getOption().matches(options::OPT__DASH_DASH)) { 274 A->claim(); 275 for (StringRef Val : A->getValues()) 276 DAL->append(MakeInputArg(*DAL, Opts, Val)); 277 continue; 278 } 279 280 DAL->append(A); 281 } 282 283 // Enforce -static if -miamcu is present. 284 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) 285 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static)); 286 287 // Add a default value of -mlinker-version=, if one was given and the user 288 // didn't specify one. 289 #if defined(HOST_LINK_VERSION) 290 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 291 strlen(HOST_LINK_VERSION) > 0) { 292 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 293 HOST_LINK_VERSION); 294 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 295 } 296 #endif 297 298 return DAL; 299 } 300 301 /// \brief Compute target triple from args. 302 /// 303 /// This routine provides the logic to compute a target triple from various 304 /// args passed to the driver and the default triple string. 305 static llvm::Triple computeTargetTriple(const Driver &D, 306 StringRef DefaultTargetTriple, 307 const ArgList &Args, 308 StringRef DarwinArchName = "") { 309 // FIXME: Already done in Compilation *Driver::BuildCompilation 310 if (const Arg *A = Args.getLastArg(options::OPT_target)) 311 DefaultTargetTriple = A->getValue(); 312 313 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 314 315 // Handle Apple-specific options available here. 316 if (Target.isOSBinFormatMachO()) { 317 // If an explict Darwin arch name is given, that trumps all. 318 if (!DarwinArchName.empty()) { 319 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName); 320 return Target; 321 } 322 323 // Handle the Darwin '-arch' flag. 324 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 325 StringRef ArchName = A->getValue(); 326 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName); 327 } 328 } 329 330 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 331 // '-mbig-endian'/'-EB'. 332 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 333 options::OPT_mbig_endian)) { 334 if (A->getOption().matches(options::OPT_mlittle_endian)) { 335 llvm::Triple LE = Target.getLittleEndianArchVariant(); 336 if (LE.getArch() != llvm::Triple::UnknownArch) 337 Target = std::move(LE); 338 } else { 339 llvm::Triple BE = Target.getBigEndianArchVariant(); 340 if (BE.getArch() != llvm::Triple::UnknownArch) 341 Target = std::move(BE); 342 } 343 } 344 345 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 346 if (Target.getArch() == llvm::Triple::tce || 347 Target.getOS() == llvm::Triple::Minix) 348 return Target; 349 350 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 351 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 352 options::OPT_m32, options::OPT_m16); 353 if (A) { 354 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 355 356 if (A->getOption().matches(options::OPT_m64)) { 357 AT = Target.get64BitArchVariant().getArch(); 358 if (Target.getEnvironment() == llvm::Triple::GNUX32) 359 Target.setEnvironment(llvm::Triple::GNU); 360 } else if (A->getOption().matches(options::OPT_mx32) && 361 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 362 AT = llvm::Triple::x86_64; 363 Target.setEnvironment(llvm::Triple::GNUX32); 364 } else if (A->getOption().matches(options::OPT_m32)) { 365 AT = Target.get32BitArchVariant().getArch(); 366 if (Target.getEnvironment() == llvm::Triple::GNUX32) 367 Target.setEnvironment(llvm::Triple::GNU); 368 } else if (A->getOption().matches(options::OPT_m16) && 369 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 370 AT = llvm::Triple::x86; 371 Target.setEnvironment(llvm::Triple::CODE16); 372 } 373 374 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 375 Target.setArch(AT); 376 } 377 378 // Handle -miamcu flag. 379 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 380 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 381 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 382 << Target.str(); 383 384 if (A && !A->getOption().matches(options::OPT_m32)) 385 D.Diag(diag::err_drv_argument_not_allowed_with) 386 << "-miamcu" << A->getBaseArg().getAsString(Args); 387 388 Target.setArch(llvm::Triple::x86); 389 Target.setArchName("i586"); 390 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 391 Target.setEnvironmentName(""); 392 Target.setOS(llvm::Triple::ELFIAMCU); 393 Target.setVendor(llvm::Triple::UnknownVendor); 394 Target.setVendorName("intel"); 395 } 396 397 return Target; 398 } 399 400 // \brief Parse the LTO options and record the type of LTO compilation 401 // based on which -f(no-)?lto(=.*)? option occurs last. 402 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 403 LTOMode = LTOK_None; 404 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ, 405 options::OPT_fno_lto, false)) 406 return; 407 408 StringRef LTOName("full"); 409 410 const Arg *A = Args.getLastArg(options::OPT_flto_EQ); 411 if (A) 412 LTOName = A->getValue(); 413 414 LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 415 .Case("full", LTOK_Full) 416 .Case("thin", LTOK_Thin) 417 .Default(LTOK_Unknown); 418 419 if (LTOMode == LTOK_Unknown) { 420 assert(A); 421 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName() 422 << A->getValue(); 423 } 424 } 425 426 void Driver::CreateOffloadingDeviceToolChains(Compilation &C, 427 InputList &Inputs) { 428 429 // 430 // CUDA 431 // 432 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type. 433 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 434 return types::isCuda(I.first); 435 })) { 436 const ToolChain &TC = getToolChain( 437 C.getInputArgs(), 438 llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>() 439 ->getTriple() 440 .isArch64Bit() 441 ? "nvptx64-nvidia-cuda" 442 : "nvptx-nvidia-cuda")); 443 C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda); 444 } 445 446 // 447 // TODO: Add support for other offloading programming models here. 448 // 449 450 return; 451 } 452 453 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 454 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 455 456 // FIXME: Handle environment options which affect driver behavior, somewhere 457 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 458 459 if (char *env = ::getenv("COMPILER_PATH")) { 460 StringRef CompilerPath = env; 461 while (!CompilerPath.empty()) { 462 std::pair<StringRef, StringRef> Split = 463 CompilerPath.split(llvm::sys::EnvPathSeparator); 464 PrefixDirs.push_back(Split.first); 465 CompilerPath = Split.second; 466 } 467 } 468 469 // We look for the driver mode option early, because the mode can affect 470 // how other options are parsed. 471 ParseDriverMode(ArgList.slice(1)); 472 473 // FIXME: What are we going to do with -V and -b? 474 475 // FIXME: This stuff needs to go into the Compilation, not the driver. 476 bool CCCPrintPhases; 477 478 InputArgList Args = ParseArgStrings(ArgList.slice(1)); 479 480 // Silence driver warnings if requested 481 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w)); 482 483 // -no-canonical-prefixes is used very early in main. 484 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 485 486 // Ignore -pipe. 487 Args.ClaimAllArgs(options::OPT_pipe); 488 489 // Extract -ccc args. 490 // 491 // FIXME: We need to figure out where this behavior should live. Most of it 492 // should be outside in the client; the parts that aren't should have proper 493 // options, either by introducing new ones or by overloading gcc ones like -V 494 // or -b. 495 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 496 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 497 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 498 CCCGenericGCCName = A->getValue(); 499 CCCUsePCH = 500 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth); 501 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 502 // and getToolChain is const. 503 if (IsCLMode()) { 504 // clang-cl targets MSVC-style Win32. 505 llvm::Triple T(DefaultTargetTriple); 506 T.setOS(llvm::Triple::Win32); 507 T.setVendor(llvm::Triple::PC); 508 T.setEnvironment(llvm::Triple::MSVC); 509 DefaultTargetTriple = T.str(); 510 } 511 if (const Arg *A = Args.getLastArg(options::OPT_target)) 512 DefaultTargetTriple = A->getValue(); 513 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 514 Dir = InstalledDir = A->getValue(); 515 for (const Arg *A : Args.filtered(options::OPT_B)) { 516 A->claim(); 517 PrefixDirs.push_back(A->getValue(0)); 518 } 519 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 520 SysRoot = A->getValue(); 521 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 522 DyldPrefix = A->getValue(); 523 if (Args.hasArg(options::OPT_nostdlib)) 524 UseStdLib = false; 525 526 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 527 ResourceDir = A->getValue(); 528 529 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 530 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 531 .Case("cwd", SaveTempsCwd) 532 .Case("obj", SaveTempsObj) 533 .Default(SaveTempsCwd); 534 } 535 536 setLTOMode(Args); 537 538 // Ignore -fembed-bitcode options with LTO 539 // since the output will be bitcode anyway. 540 if (getLTOMode() == LTOK_None) { 541 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 542 StringRef Name = A->getValue(); 543 unsigned Model = llvm::StringSwitch<unsigned>(Name) 544 .Case("off", EmbedNone) 545 .Case("all", EmbedBitcode) 546 .Case("bitcode", EmbedBitcode) 547 .Case("marker", EmbedMarker) 548 .Default(~0U); 549 if (Model == ~0U) { 550 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 551 << Name; 552 } else 553 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 554 } 555 } else { 556 // claim the bitcode option under LTO so no warning is issued. 557 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ); 558 } 559 560 std::unique_ptr<llvm::opt::InputArgList> UArgs = 561 llvm::make_unique<InputArgList>(std::move(Args)); 562 563 // Perform the default argument translations. 564 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 565 566 // Owned by the host. 567 const ToolChain &TC = getToolChain( 568 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs)); 569 570 // The compilation takes ownership of Args. 571 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs); 572 573 if (!HandleImmediateArgs(*C)) 574 return C; 575 576 // Construct the list of inputs. 577 InputList Inputs; 578 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 579 580 // Populate the tool chains for the offloading devices, if any. 581 CreateOffloadingDeviceToolChains(*C, Inputs); 582 583 // Construct the list of abstract actions to perform for this compilation. On 584 // MachO targets this uses the driver-driver and universal actions. 585 if (TC.getTriple().isOSBinFormatMachO()) 586 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 587 else 588 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 589 590 if (CCCPrintPhases) { 591 PrintActions(*C); 592 return C; 593 } 594 595 BuildJobs(*C); 596 597 return C; 598 } 599 600 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 601 llvm::opt::ArgStringList ASL; 602 for (const auto *A : Args) 603 A->render(Args, ASL); 604 605 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 606 if (I != ASL.begin()) 607 OS << ' '; 608 Command::printArg(OS, *I, true); 609 } 610 OS << '\n'; 611 } 612 613 // When clang crashes, produce diagnostic information including the fully 614 // preprocessed source file(s). Request that the developer attach the 615 // diagnostic information to a bug report. 616 void Driver::generateCompilationDiagnostics(Compilation &C, 617 const Command &FailingCommand) { 618 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 619 return; 620 621 // Don't try to generate diagnostics for link or dsymutil jobs. 622 if (FailingCommand.getCreator().isLinkJob() || 623 FailingCommand.getCreator().isDsymutilJob()) 624 return; 625 626 // Print the version of the compiler. 627 PrintVersion(C, llvm::errs()); 628 629 Diag(clang::diag::note_drv_command_failed_diag_msg) 630 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 631 "crash backtrace, preprocessed source, and associated run script."; 632 633 // Suppress driver output and emit preprocessor output to temp file. 634 Mode = CPPMode; 635 CCGenDiagnostics = true; 636 637 // Save the original job command(s). 638 Command Cmd = FailingCommand; 639 640 // Keep track of whether we produce any errors while trying to produce 641 // preprocessed sources. 642 DiagnosticErrorTrap Trap(Diags); 643 644 // Suppress tool output. 645 C.initCompilationForDiagnostics(); 646 647 // Construct the list of inputs. 648 InputList Inputs; 649 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 650 651 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 652 bool IgnoreInput = false; 653 654 // Ignore input from stdin or any inputs that cannot be preprocessed. 655 // Check type first as not all linker inputs have a value. 656 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 657 IgnoreInput = true; 658 } else if (!strcmp(it->second->getValue(), "-")) { 659 Diag(clang::diag::note_drv_command_failed_diag_msg) 660 << "Error generating preprocessed source(s) - " 661 "ignoring input from stdin."; 662 IgnoreInput = true; 663 } 664 665 if (IgnoreInput) { 666 it = Inputs.erase(it); 667 ie = Inputs.end(); 668 } else { 669 ++it; 670 } 671 } 672 673 if (Inputs.empty()) { 674 Diag(clang::diag::note_drv_command_failed_diag_msg) 675 << "Error generating preprocessed source(s) - " 676 "no preprocessable inputs."; 677 return; 678 } 679 680 // Don't attempt to generate preprocessed files if multiple -arch options are 681 // used, unless they're all duplicates. 682 llvm::StringSet<> ArchNames; 683 for (const Arg *A : C.getArgs()) { 684 if (A->getOption().matches(options::OPT_arch)) { 685 StringRef ArchName = A->getValue(); 686 ArchNames.insert(ArchName); 687 } 688 } 689 if (ArchNames.size() > 1) { 690 Diag(clang::diag::note_drv_command_failed_diag_msg) 691 << "Error generating preprocessed source(s) - cannot generate " 692 "preprocessed source with multiple -arch options."; 693 return; 694 } 695 696 // Construct the list of abstract actions to perform for this compilation. On 697 // Darwin OSes this uses the driver-driver and builds universal actions. 698 const ToolChain &TC = C.getDefaultToolChain(); 699 if (TC.getTriple().isOSBinFormatMachO()) 700 BuildUniversalActions(C, TC, Inputs); 701 else 702 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 703 704 BuildJobs(C); 705 706 // If there were errors building the compilation, quit now. 707 if (Trap.hasErrorOccurred()) { 708 Diag(clang::diag::note_drv_command_failed_diag_msg) 709 << "Error generating preprocessed source(s)."; 710 return; 711 } 712 713 // Generate preprocessed output. 714 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 715 C.ExecuteJobs(C.getJobs(), FailingCommands); 716 717 // If any of the preprocessing commands failed, clean up and exit. 718 if (!FailingCommands.empty()) { 719 if (!isSaveTempsEnabled()) 720 C.CleanupFileList(C.getTempFiles(), true); 721 722 Diag(clang::diag::note_drv_command_failed_diag_msg) 723 << "Error generating preprocessed source(s)."; 724 return; 725 } 726 727 const ArgStringList &TempFiles = C.getTempFiles(); 728 if (TempFiles.empty()) { 729 Diag(clang::diag::note_drv_command_failed_diag_msg) 730 << "Error generating preprocessed source(s)."; 731 return; 732 } 733 734 Diag(clang::diag::note_drv_command_failed_diag_msg) 735 << "\n********************\n\n" 736 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 737 "Preprocessed source(s) and associated run script(s) are located at:"; 738 739 SmallString<128> VFS; 740 for (const char *TempFile : TempFiles) { 741 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 742 if (StringRef(TempFile).endswith(".cache")) { 743 // In some cases (modules) we'll dump extra data to help with reproducing 744 // the crash into a directory next to the output. 745 VFS = llvm::sys::path::filename(TempFile); 746 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 747 } 748 } 749 750 // Assume associated files are based off of the first temporary file. 751 CrashReportInfo CrashInfo(TempFiles[0], VFS); 752 753 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh"; 754 std::error_code EC; 755 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl); 756 if (EC) { 757 Diag(clang::diag::note_drv_command_failed_diag_msg) 758 << "Error generating run script: " + Script + " " + EC.message(); 759 } else { 760 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 761 << "# Driver args: "; 762 printArgList(ScriptOS, C.getInputArgs()); 763 ScriptOS << "# Original command: "; 764 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 765 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 766 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 767 } 768 769 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file, 770 options::OPT_frewrite_map_file_EQ)) 771 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue(); 772 773 Diag(clang::diag::note_drv_command_failed_diag_msg) 774 << "\n\n********************"; 775 } 776 777 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 778 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity 779 // if the tool does not support response files, there is a chance/ that things 780 // will just work without a response file, so we silently just skip it. 781 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None || 782 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments())) 783 return; 784 785 std::string TmpName = GetTemporaryPath("response", "txt"); 786 Cmd.setResponseFile( 787 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()))); 788 } 789 790 int Driver::ExecuteCompilation( 791 Compilation &C, 792 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 793 // Just print if -### was present. 794 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 795 C.getJobs().Print(llvm::errs(), "\n", true); 796 return 0; 797 } 798 799 // If there were errors building the compilation, quit now. 800 if (Diags.hasErrorOccurred()) 801 return 1; 802 803 // Set up response file names for each command, if necessary 804 for (auto &Job : C.getJobs()) 805 setUpResponseFiles(C, Job); 806 807 C.ExecuteJobs(C.getJobs(), FailingCommands); 808 809 // Remove temp files. 810 C.CleanupFileList(C.getTempFiles()); 811 812 // If the command succeeded, we are done. 813 if (FailingCommands.empty()) 814 return 0; 815 816 // Otherwise, remove result files and print extra information about abnormal 817 // failures. 818 for (const auto &CmdPair : FailingCommands) { 819 int Res = CmdPair.first; 820 const Command *FailingCommand = CmdPair.second; 821 822 // Remove result files if we're not saving temps. 823 if (!isSaveTempsEnabled()) { 824 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 825 C.CleanupFileMap(C.getResultFiles(), JA, true); 826 827 // Failure result files are valid unless we crashed. 828 if (Res < 0) 829 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 830 } 831 832 // Print extra information about abnormal failures, if possible. 833 // 834 // This is ad-hoc, but we don't want to be excessively noisy. If the result 835 // status was 1, assume the command failed normally. In particular, if it 836 // was the compiler then assume it gave a reasonable error code. Failures 837 // in other tools are less common, and they generally have worse 838 // diagnostics, so always print the diagnostic there. 839 const Tool &FailingTool = FailingCommand->getCreator(); 840 841 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 842 // FIXME: See FIXME above regarding result code interpretation. 843 if (Res < 0) 844 Diag(clang::diag::err_drv_command_signalled) 845 << FailingTool.getShortName(); 846 else 847 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() 848 << Res; 849 } 850 } 851 return 0; 852 } 853 854 void Driver::PrintHelp(bool ShowHidden) const { 855 unsigned IncludedFlagsBitmask; 856 unsigned ExcludedFlagsBitmask; 857 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 858 getIncludeExcludeOptionFlagMasks(); 859 860 ExcludedFlagsBitmask |= options::NoDriverOption; 861 if (!ShowHidden) 862 ExcludedFlagsBitmask |= HelpHidden; 863 864 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 865 IncludedFlagsBitmask, ExcludedFlagsBitmask); 866 } 867 868 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 869 // FIXME: The following handlers should use a callback mechanism, we don't 870 // know what the client would like to do. 871 OS << getClangFullVersion() << '\n'; 872 const ToolChain &TC = C.getDefaultToolChain(); 873 OS << "Target: " << TC.getTripleString() << '\n'; 874 875 // Print the threading model. 876 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 877 // Don't print if the ToolChain would have barfed on it already 878 if (TC.isThreadModelSupported(A->getValue())) 879 OS << "Thread model: " << A->getValue(); 880 } else 881 OS << "Thread model: " << TC.getThreadModel(); 882 OS << '\n'; 883 884 // Print out the install directory. 885 OS << "InstalledDir: " << InstalledDir << '\n'; 886 } 887 888 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 889 /// option. 890 static void PrintDiagnosticCategories(raw_ostream &OS) { 891 // Skip the empty category. 892 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 893 ++i) 894 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 895 } 896 897 bool Driver::HandleImmediateArgs(const Compilation &C) { 898 // The order these options are handled in gcc is all over the place, but we 899 // don't expect inconsistencies w.r.t. that to matter in practice. 900 901 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 902 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 903 return false; 904 } 905 906 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 907 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 908 // return an answer which matches our definition of __VERSION__. 909 // 910 // If we want to return a more correct answer some day, then we should 911 // introduce a non-pedantically GCC compatible mode to Clang in which we 912 // provide sensible definitions for -dumpversion, __VERSION__, etc. 913 llvm::outs() << "4.2.1\n"; 914 return false; 915 } 916 917 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 918 PrintDiagnosticCategories(llvm::outs()); 919 return false; 920 } 921 922 if (C.getArgs().hasArg(options::OPT_help) || 923 C.getArgs().hasArg(options::OPT__help_hidden)) { 924 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 925 return false; 926 } 927 928 if (C.getArgs().hasArg(options::OPT__version)) { 929 // Follow gcc behavior and use stdout for --version and stderr for -v. 930 PrintVersion(C, llvm::outs()); 931 return false; 932 } 933 934 if (C.getArgs().hasArg(options::OPT_v) || 935 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 936 PrintVersion(C, llvm::errs()); 937 SuppressMissingInputWarning = true; 938 } 939 940 const ToolChain &TC = C.getDefaultToolChain(); 941 942 if (C.getArgs().hasArg(options::OPT_v)) 943 TC.printVerboseInfo(llvm::errs()); 944 945 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 946 llvm::outs() << "programs: ="; 947 bool separator = false; 948 for (const std::string &Path : TC.getProgramPaths()) { 949 if (separator) 950 llvm::outs() << ':'; 951 llvm::outs() << Path; 952 separator = true; 953 } 954 llvm::outs() << "\n"; 955 llvm::outs() << "libraries: =" << ResourceDir; 956 957 StringRef sysroot = C.getSysRoot(); 958 959 for (const std::string &Path : TC.getFilePaths()) { 960 // Always print a separator. ResourceDir was the first item shown. 961 llvm::outs() << ':'; 962 // Interpretation of leading '=' is needed only for NetBSD. 963 if (Path[0] == '=') 964 llvm::outs() << sysroot << Path.substr(1); 965 else 966 llvm::outs() << Path; 967 } 968 llvm::outs() << "\n"; 969 return false; 970 } 971 972 // FIXME: The following handlers should use a callback mechanism, we don't 973 // know what the client would like to do. 974 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 975 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 976 return false; 977 } 978 979 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 980 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 981 return false; 982 } 983 984 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 985 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 986 return false; 987 } 988 989 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 990 for (const Multilib &Multilib : TC.getMultilibs()) 991 llvm::outs() << Multilib << "\n"; 992 return false; 993 } 994 995 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 996 for (const Multilib &Multilib : TC.getMultilibs()) { 997 if (Multilib.gccSuffix().empty()) 998 llvm::outs() << ".\n"; 999 else { 1000 StringRef Suffix(Multilib.gccSuffix()); 1001 assert(Suffix.front() == '/'); 1002 llvm::outs() << Suffix.substr(1) << "\n"; 1003 } 1004 } 1005 return false; 1006 } 1007 return true; 1008 } 1009 1010 // Display an action graph human-readably. Action A is the "sink" node 1011 // and latest-occuring action. Traversal is in pre-order, visiting the 1012 // inputs to each action before printing the action itself. 1013 static unsigned PrintActions1(const Compilation &C, Action *A, 1014 std::map<Action *, unsigned> &Ids) { 1015 if (Ids.count(A)) // A was already visited. 1016 return Ids[A]; 1017 1018 std::string str; 1019 llvm::raw_string_ostream os(str); 1020 1021 os << Action::getClassName(A->getKind()) << ", "; 1022 if (InputAction *IA = dyn_cast<InputAction>(A)) { 1023 os << "\"" << IA->getInputArg().getValue() << "\""; 1024 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 1025 os << '"' << BIA->getArchName() << '"' << ", {" 1026 << PrintActions1(C, *BIA->input_begin(), Ids) << "}"; 1027 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 1028 bool IsFirst = true; 1029 OA->doOnEachDependence( 1030 [&](Action *A, const ToolChain *TC, const char *BoundArch) { 1031 // E.g. for two CUDA device dependences whose bound arch is sm_20 and 1032 // sm_35 this will generate: 1033 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" 1034 // (nvptx64-nvidia-cuda:sm_35) {#ID} 1035 if (!IsFirst) 1036 os << ", "; 1037 os << '"'; 1038 if (TC) 1039 os << A->getOffloadingKindPrefix(); 1040 else 1041 os << "host"; 1042 os << " ("; 1043 os << TC->getTriple().normalize(); 1044 1045 if (BoundArch) 1046 os << ":" << BoundArch; 1047 os << ")"; 1048 os << '"'; 1049 os << " {" << PrintActions1(C, A, Ids) << "}"; 1050 IsFirst = false; 1051 }); 1052 } else { 1053 const ActionList *AL = &A->getInputs(); 1054 1055 if (AL->size()) { 1056 const char *Prefix = "{"; 1057 for (Action *PreRequisite : *AL) { 1058 os << Prefix << PrintActions1(C, PreRequisite, Ids); 1059 Prefix = ", "; 1060 } 1061 os << "}"; 1062 } else 1063 os << "{}"; 1064 } 1065 1066 // Append offload info for all options other than the offloading action 1067 // itself (e.g. (cuda-device, sm_20) or (cuda-host)). 1068 std::string offload_str; 1069 llvm::raw_string_ostream offload_os(offload_str); 1070 if (!isa<OffloadAction>(A)) { 1071 auto S = A->getOffloadingKindPrefix(); 1072 if (!S.empty()) { 1073 offload_os << ", (" << S; 1074 if (A->getOffloadingArch()) 1075 offload_os << ", " << A->getOffloadingArch(); 1076 offload_os << ")"; 1077 } 1078 } 1079 1080 unsigned Id = Ids.size(); 1081 Ids[A] = Id; 1082 llvm::errs() << Id << ": " << os.str() << ", " 1083 << types::getTypeName(A->getType()) << offload_os.str() << "\n"; 1084 1085 return Id; 1086 } 1087 1088 // Print the action graphs in a compilation C. 1089 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 1090 void Driver::PrintActions(const Compilation &C) const { 1091 std::map<Action *, unsigned> Ids; 1092 for (Action *A : C.getActions()) 1093 PrintActions1(C, A, Ids); 1094 } 1095 1096 /// \brief Check whether the given input tree contains any compilation or 1097 /// assembly actions. 1098 static bool ContainsCompileOrAssembleAction(const Action *A) { 1099 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 1100 isa<AssembleJobAction>(A)) 1101 return true; 1102 1103 for (const Action *Input : A->inputs()) 1104 if (ContainsCompileOrAssembleAction(Input)) 1105 return true; 1106 1107 return false; 1108 } 1109 1110 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 1111 const InputList &BAInputs) const { 1112 DerivedArgList &Args = C.getArgs(); 1113 ActionList &Actions = C.getActions(); 1114 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 1115 // Collect the list of architectures. Duplicates are allowed, but should only 1116 // be handled once (in the order seen). 1117 llvm::StringSet<> ArchNames; 1118 SmallVector<const char *, 4> Archs; 1119 for (Arg *A : Args) { 1120 if (A->getOption().matches(options::OPT_arch)) { 1121 // Validate the option here; we don't save the type here because its 1122 // particular spelling may participate in other driver choices. 1123 llvm::Triple::ArchType Arch = 1124 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 1125 if (Arch == llvm::Triple::UnknownArch) { 1126 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 1127 continue; 1128 } 1129 1130 A->claim(); 1131 if (ArchNames.insert(A->getValue()).second) 1132 Archs.push_back(A->getValue()); 1133 } 1134 } 1135 1136 // When there is no explicit arch for this platform, make sure we still bind 1137 // the architecture (to the default) so that -Xarch_ is handled correctly. 1138 if (!Archs.size()) 1139 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 1140 1141 ActionList SingleActions; 1142 BuildActions(C, Args, BAInputs, SingleActions); 1143 1144 // Add in arch bindings for every top level action, as well as lipo and 1145 // dsymutil steps if needed. 1146 for (Action* Act : SingleActions) { 1147 // Make sure we can lipo this kind of output. If not (and it is an actual 1148 // output) then we disallow, since we can't create an output file with the 1149 // right name without overwriting it. We could remove this oddity by just 1150 // changing the output names to include the arch, which would also fix 1151 // -save-temps. Compatibility wins for now. 1152 1153 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 1154 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 1155 << types::getTypeName(Act->getType()); 1156 1157 ActionList Inputs; 1158 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 1159 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 1160 1161 // Lipo if necessary, we do it this way because we need to set the arch flag 1162 // so that -Xarch_ gets overwritten. 1163 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 1164 Actions.append(Inputs.begin(), Inputs.end()); 1165 else 1166 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 1167 1168 // Handle debug info queries. 1169 Arg *A = Args.getLastArg(options::OPT_g_Group); 1170 if (A && !A->getOption().matches(options::OPT_g0) && 1171 !A->getOption().matches(options::OPT_gstabs) && 1172 ContainsCompileOrAssembleAction(Actions.back())) { 1173 1174 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 1175 // have a compile input. We need to run 'dsymutil' ourselves in such cases 1176 // because the debug info will refer to a temporary object file which 1177 // will be removed at the end of the compilation process. 1178 if (Act->getType() == types::TY_Image) { 1179 ActionList Inputs; 1180 Inputs.push_back(Actions.back()); 1181 Actions.pop_back(); 1182 Actions.push_back( 1183 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 1184 } 1185 1186 // Verify the debug info output. 1187 if (Args.hasArg(options::OPT_verify_debug_info)) { 1188 Action* LastAction = Actions.back(); 1189 Actions.pop_back(); 1190 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 1191 LastAction, types::TY_Nothing)); 1192 } 1193 } 1194 } 1195 } 1196 1197 /// \brief Check that the file referenced by Value exists. If it doesn't, 1198 /// issue a diagnostic and return false. 1199 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, 1200 StringRef Value, types::ID Ty) { 1201 if (!D.getCheckInputsExist()) 1202 return true; 1203 1204 // stdin always exists. 1205 if (Value == "-") 1206 return true; 1207 1208 SmallString<64> Path(Value); 1209 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 1210 if (!llvm::sys::path::is_absolute(Path)) { 1211 SmallString<64> Directory(WorkDir->getValue()); 1212 llvm::sys::path::append(Directory, Value); 1213 Path.assign(Directory); 1214 } 1215 } 1216 1217 if (llvm::sys::fs::exists(Twine(Path))) 1218 return true; 1219 1220 if (D.IsCLMode()) { 1221 if (!llvm::sys::path::is_absolute(Twine(Path)) && 1222 llvm::sys::Process::FindInEnvPath("LIB", Value)) 1223 return true; 1224 1225 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) { 1226 // Arguments to the /link flag might cause the linker to search for object 1227 // and library files in paths we don't know about. Don't error in such 1228 // cases. 1229 return true; 1230 } 1231 } 1232 1233 D.Diag(clang::diag::err_drv_no_such_file) << Path; 1234 return false; 1235 } 1236 1237 // Construct a the list of inputs and their types. 1238 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 1239 InputList &Inputs) const { 1240 // Track the current user specified (-x) input. We also explicitly track the 1241 // argument used to set the type; we only want to claim the type when we 1242 // actually use it, so we warn about unused -x arguments. 1243 types::ID InputType = types::TY_Nothing; 1244 Arg *InputTypeArg = nullptr; 1245 1246 // The last /TC or /TP option sets the input type to C or C++ globally. 1247 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 1248 options::OPT__SLASH_TP)) { 1249 InputTypeArg = TCTP; 1250 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 1251 ? types::TY_C 1252 : types::TY_CXX; 1253 1254 arg_iterator it = 1255 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP); 1256 const arg_iterator ie = Args.filtered_end(); 1257 Arg *Previous = *it++; 1258 bool ShowNote = false; 1259 while (it != ie) { 1260 Diag(clang::diag::warn_drv_overriding_flag_option) 1261 << Previous->getSpelling() << (*it)->getSpelling(); 1262 Previous = *it++; 1263 ShowNote = true; 1264 } 1265 if (ShowNote) 1266 Diag(clang::diag::note_drv_t_option_is_global); 1267 1268 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 1269 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 1270 } 1271 1272 for (Arg *A : Args) { 1273 if (A->getOption().getKind() == Option::InputClass) { 1274 const char *Value = A->getValue(); 1275 types::ID Ty = types::TY_INVALID; 1276 1277 // Infer the input type if necessary. 1278 if (InputType == types::TY_Nothing) { 1279 // If there was an explicit arg for this, claim it. 1280 if (InputTypeArg) 1281 InputTypeArg->claim(); 1282 1283 // stdin must be handled specially. 1284 if (memcmp(Value, "-", 2) == 0) { 1285 // If running with -E, treat as a C input (this changes the builtin 1286 // macros, for example). This may be overridden by -ObjC below. 1287 // 1288 // Otherwise emit an error but still use a valid type to avoid 1289 // spurious errors (e.g., no inputs). 1290 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 1291 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 1292 : clang::diag::err_drv_unknown_stdin_type); 1293 Ty = types::TY_C; 1294 } else { 1295 // Otherwise lookup by extension. 1296 // Fallback is C if invoked as C preprocessor or Object otherwise. 1297 // We use a host hook here because Darwin at least has its own 1298 // idea of what .s is. 1299 if (const char *Ext = strrchr(Value, '.')) 1300 Ty = TC.LookupTypeForExtension(Ext + 1); 1301 1302 if (Ty == types::TY_INVALID) { 1303 if (CCCIsCPP()) 1304 Ty = types::TY_C; 1305 else 1306 Ty = types::TY_Object; 1307 } 1308 1309 // If the driver is invoked as C++ compiler (like clang++ or c++) it 1310 // should autodetect some input files as C++ for g++ compatibility. 1311 if (CCCIsCXX()) { 1312 types::ID OldTy = Ty; 1313 Ty = types::lookupCXXTypeForCType(Ty); 1314 1315 if (Ty != OldTy) 1316 Diag(clang::diag::warn_drv_treating_input_as_cxx) 1317 << getTypeName(OldTy) << getTypeName(Ty); 1318 } 1319 } 1320 1321 // -ObjC and -ObjC++ override the default language, but only for "source 1322 // files". We just treat everything that isn't a linker input as a 1323 // source file. 1324 // 1325 // FIXME: Clean this up if we move the phase sequence into the type. 1326 if (Ty != types::TY_Object) { 1327 if (Args.hasArg(options::OPT_ObjC)) 1328 Ty = types::TY_ObjC; 1329 else if (Args.hasArg(options::OPT_ObjCXX)) 1330 Ty = types::TY_ObjCXX; 1331 } 1332 } else { 1333 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 1334 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 1335 // If emulating cl.exe, make sure that /TC and /TP don't affect input 1336 // object files. 1337 const char *Ext = strrchr(Value, '.'); 1338 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 1339 Ty = types::TY_Object; 1340 } 1341 if (Ty == types::TY_INVALID) { 1342 Ty = InputType; 1343 InputTypeArg->claim(); 1344 } 1345 } 1346 1347 if (DiagnoseInputExistence(*this, Args, Value, Ty)) 1348 Inputs.push_back(std::make_pair(Ty, A)); 1349 1350 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 1351 StringRef Value = A->getValue(); 1352 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) { 1353 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1354 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 1355 } 1356 A->claim(); 1357 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 1358 StringRef Value = A->getValue(); 1359 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) { 1360 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1361 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 1362 } 1363 A->claim(); 1364 } else if (A->getOption().hasFlag(options::LinkerInput)) { 1365 // Just treat as object type, we could make a special type for this if 1366 // necessary. 1367 Inputs.push_back(std::make_pair(types::TY_Object, A)); 1368 1369 } else if (A->getOption().matches(options::OPT_x)) { 1370 InputTypeArg = A; 1371 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 1372 A->claim(); 1373 1374 // Follow gcc behavior and treat as linker input for invalid -x 1375 // options. Its not clear why we shouldn't just revert to unknown; but 1376 // this isn't very important, we might as well be bug compatible. 1377 if (!InputType) { 1378 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 1379 InputType = types::TY_Object; 1380 } 1381 } 1382 } 1383 if (CCCIsCPP() && Inputs.empty()) { 1384 // If called as standalone preprocessor, stdin is processed 1385 // if no other input is present. 1386 Arg *A = MakeInputArg(Args, Opts, "-"); 1387 Inputs.push_back(std::make_pair(types::TY_C, A)); 1388 } 1389 } 1390 1391 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE 1392 // input action and then wraps each in CudaDeviceAction paired with 1393 // appropriate GPU arch name. In case of partial (i.e preprocessing 1394 // only) or device-only compilation, each device action is added to /p 1395 // Actions and /p Current is released. Otherwise the function creates 1396 // and returns a new CudaHostAction which wraps /p Current and device 1397 // side actions. 1398 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args, 1399 const Arg *InputArg, Action *HostAction, 1400 ActionList &Actions) { 1401 Arg *PartialCompilationArg = Args.getLastArg( 1402 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 1403 options::OPT_cuda_compile_host_device); 1404 bool CompileHostOnly = 1405 PartialCompilationArg && 1406 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only); 1407 bool CompileDeviceOnly = 1408 PartialCompilationArg && 1409 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only); 1410 1411 if (CompileHostOnly) { 1412 OffloadAction::HostDependence HDep( 1413 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 1414 /*BoundArch=*/nullptr, Action::OFK_Cuda); 1415 return C.MakeAction<OffloadAction>(HDep); 1416 } 1417 1418 // Collect all cuda_gpu_arch parameters, removing duplicates. 1419 SmallVector<CudaArch, 4> GpuArchList; 1420 llvm::SmallSet<CudaArch, 4> GpuArchs; 1421 for (Arg *A : Args) { 1422 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) 1423 continue; 1424 A->claim(); 1425 1426 const auto &ArchStr = A->getValue(); 1427 CudaArch Arch = StringToCudaArch(ArchStr); 1428 if (Arch == CudaArch::UNKNOWN) 1429 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 1430 else if (GpuArchs.insert(Arch).second) 1431 GpuArchList.push_back(Arch); 1432 } 1433 1434 // Default to sm_20 which is the lowest common denominator for supported GPUs. 1435 // sm_20 code should work correctly, if suboptimally, on all newer GPUs. 1436 if (GpuArchList.empty()) 1437 GpuArchList.push_back(CudaArch::SM_20); 1438 1439 // Replicate inputs for each GPU architecture. 1440 Driver::InputList CudaDeviceInputs; 1441 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1442 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg)); 1443 1444 // Build actions for all device inputs. 1445 ActionList CudaDeviceActions; 1446 C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions); 1447 assert(GpuArchList.size() == CudaDeviceActions.size() && 1448 "Failed to create actions for all devices"); 1449 1450 // Check whether any of device actions stopped before they could generate PTX. 1451 bool PartialCompilation = 1452 llvm::any_of(CudaDeviceActions, [](const Action *a) { 1453 return a->getKind() != Action::AssembleJobClass; 1454 }); 1455 1456 const ToolChain *CudaTC = C.getSingleOffloadToolChain<Action::OFK_Cuda>(); 1457 1458 // Figure out what to do with device actions -- pass them as inputs to the 1459 // host action or run each of them independently. 1460 if (PartialCompilation || CompileDeviceOnly) { 1461 // In case of partial or device-only compilation results of device actions 1462 // are not consumed by the host action device actions have to be added to 1463 // top-level actions list with AtTopLevel=true and run independently. 1464 1465 // -o is ambiguous if we have more than one top-level action. 1466 if (Args.hasArg(options::OPT_o) && 1467 (!CompileDeviceOnly || GpuArchList.size() > 1)) { 1468 C.getDriver().Diag( 1469 clang::diag::err_drv_output_argument_with_multiple_files); 1470 return nullptr; 1471 } 1472 1473 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1474 OffloadAction::DeviceDependences DDep; 1475 DDep.add(*CudaDeviceActions[I], *CudaTC, CudaArchToString(GpuArchList[I]), 1476 Action::OFK_Cuda); 1477 Actions.push_back( 1478 C.MakeAction<OffloadAction>(DDep, CudaDeviceActions[I]->getType())); 1479 } 1480 // Kill host action in case of device-only compilation. 1481 if (CompileDeviceOnly) 1482 return nullptr; 1483 return HostAction; 1484 } 1485 1486 // If we're not a partial or device-only compilation, we compile each arch to 1487 // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device 1488 // "link" action, which uses fatbinary to combine these cubins into one 1489 // fatbin. The fatbin is then an input to the host compilation. 1490 ActionList DeviceActions; 1491 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1492 Action* AssembleAction = CudaDeviceActions[I]; 1493 assert(AssembleAction->getType() == types::TY_Object); 1494 assert(AssembleAction->getInputs().size() == 1); 1495 1496 Action* BackendAction = AssembleAction->getInputs()[0]; 1497 assert(BackendAction->getType() == types::TY_PP_Asm); 1498 1499 for (auto &A : {AssembleAction, BackendAction}) { 1500 OffloadAction::DeviceDependences DDep; 1501 DDep.add(*A, *CudaTC, CudaArchToString(GpuArchList[I]), Action::OFK_Cuda); 1502 DeviceActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType())); 1503 } 1504 } 1505 auto FatbinAction = 1506 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 1507 1508 // Return a new host action that incorporates original host action and all 1509 // device actions. 1510 OffloadAction::HostDependence HDep( 1511 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 1512 /*BoundArch=*/nullptr, Action::OFK_Cuda); 1513 OffloadAction::DeviceDependences DDep; 1514 DDep.add(*FatbinAction, *CudaTC, /*BoundArch=*/nullptr, Action::OFK_Cuda); 1515 return C.MakeAction<OffloadAction>(HDep, DDep); 1516 } 1517 1518 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 1519 const InputList &Inputs, ActionList &Actions) const { 1520 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 1521 1522 if (!SuppressMissingInputWarning && Inputs.empty()) { 1523 Diag(clang::diag::err_drv_no_input_files); 1524 return; 1525 } 1526 1527 Arg *FinalPhaseArg; 1528 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 1529 1530 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) { 1531 Diag(clang::diag::err_drv_emit_llvm_link); 1532 } 1533 1534 // Reject -Z* at the top level, these options should never have been exposed 1535 // by gcc. 1536 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 1537 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 1538 1539 // Diagnose misuse of /Fo. 1540 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 1541 StringRef V = A->getValue(); 1542 if (Inputs.size() > 1 && !V.empty() && 1543 !llvm::sys::path::is_separator(V.back())) { 1544 // Check whether /Fo tries to name an output file for multiple inputs. 1545 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1546 << A->getSpelling() << V; 1547 Args.eraseArg(options::OPT__SLASH_Fo); 1548 } 1549 } 1550 1551 // Diagnose misuse of /Fa. 1552 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 1553 StringRef V = A->getValue(); 1554 if (Inputs.size() > 1 && !V.empty() && 1555 !llvm::sys::path::is_separator(V.back())) { 1556 // Check whether /Fa tries to name an asm file for multiple inputs. 1557 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1558 << A->getSpelling() << V; 1559 Args.eraseArg(options::OPT__SLASH_Fa); 1560 } 1561 } 1562 1563 // Diagnose misuse of /o. 1564 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 1565 if (A->getValue()[0] == '\0') { 1566 // It has to have a value. 1567 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 1568 Args.eraseArg(options::OPT__SLASH_o); 1569 } 1570 } 1571 1572 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if: 1573 // * no filename after it 1574 // * both /Yc and /Yu passed but with different filenames 1575 // * corresponding file not also passed as /FI 1576 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 1577 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 1578 if (YcArg && YcArg->getValue()[0] == '\0') { 1579 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling(); 1580 Args.eraseArg(options::OPT__SLASH_Yc); 1581 YcArg = nullptr; 1582 } 1583 if (YuArg && YuArg->getValue()[0] == '\0') { 1584 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling(); 1585 Args.eraseArg(options::OPT__SLASH_Yu); 1586 YuArg = nullptr; 1587 } 1588 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 1589 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 1590 Args.eraseArg(options::OPT__SLASH_Yc); 1591 Args.eraseArg(options::OPT__SLASH_Yu); 1592 YcArg = YuArg = nullptr; 1593 } 1594 if (YcArg || YuArg) { 1595 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue(); 1596 bool FoundMatchingInclude = false; 1597 for (const Arg *Inc : Args.filtered(options::OPT_include)) { 1598 // FIXME: Do case-insensitive matching and consider / and \ as equal. 1599 if (Inc->getValue() == Val) 1600 FoundMatchingInclude = true; 1601 } 1602 if (!FoundMatchingInclude) { 1603 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl) 1604 << (YcArg ? YcArg : YuArg)->getSpelling(); 1605 Args.eraseArg(options::OPT__SLASH_Yc); 1606 Args.eraseArg(options::OPT__SLASH_Yu); 1607 YcArg = YuArg = nullptr; 1608 } 1609 } 1610 if (YcArg && Inputs.size() > 1) { 1611 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 1612 Args.eraseArg(options::OPT__SLASH_Yc); 1613 YcArg = nullptr; 1614 } 1615 if (Args.hasArg(options::OPT__SLASH_Y_)) { 1616 // /Y- disables all pch handling. Rather than check for it everywhere, 1617 // just remove clang-cl pch-related flags here. 1618 Args.eraseArg(options::OPT__SLASH_Fp); 1619 Args.eraseArg(options::OPT__SLASH_Yc); 1620 Args.eraseArg(options::OPT__SLASH_Yu); 1621 YcArg = YuArg = nullptr; 1622 } 1623 1624 // Track the host offload kinds used on this compilation. 1625 unsigned CompilationActiveOffloadHostKinds = 0u; 1626 1627 // Construct the actions to perform. 1628 ActionList LinkerInputs; 1629 1630 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 1631 for (auto &I : Inputs) { 1632 types::ID InputType = I.first; 1633 const Arg *InputArg = I.second; 1634 1635 PL.clear(); 1636 types::getCompilationPhases(InputType, PL); 1637 1638 // If the first step comes after the final phase we are doing as part of 1639 // this compilation, warn the user about it. 1640 phases::ID InitialPhase = PL[0]; 1641 if (InitialPhase > FinalPhase) { 1642 // Claim here to avoid the more general unused warning. 1643 InputArg->claim(); 1644 1645 // Suppress all unused style warnings with -Qunused-arguments 1646 if (Args.hasArg(options::OPT_Qunused_arguments)) 1647 continue; 1648 1649 // Special case when final phase determined by binary name, rather than 1650 // by a command-line argument with a corresponding Arg. 1651 if (CCCIsCPP()) 1652 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 1653 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 1654 // Special case '-E' warning on a previously preprocessed file to make 1655 // more sense. 1656 else if (InitialPhase == phases::Compile && 1657 FinalPhase == phases::Preprocess && 1658 getPreprocessedType(InputType) == types::TY_INVALID) 1659 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 1660 << InputArg->getAsString(Args) << !!FinalPhaseArg 1661 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1662 else 1663 Diag(clang::diag::warn_drv_input_file_unused) 1664 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 1665 << !!FinalPhaseArg 1666 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1667 continue; 1668 } 1669 1670 if (YcArg) { 1671 // Add a separate precompile phase for the compile phase. 1672 if (FinalPhase >= phases::Compile) { 1673 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL; 1674 types::getCompilationPhases(types::TY_CXXHeader, PCHPL); 1675 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue()); 1676 1677 // Build the pipeline for the pch file. 1678 Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType); 1679 for (phases::ID Phase : PCHPL) 1680 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 1681 assert(ClangClPch); 1682 Actions.push_back(ClangClPch); 1683 // The driver currently exits after the first failed command. This 1684 // relies on that behavior, to make sure if the pch generation fails, 1685 // the main compilation won't run. 1686 } 1687 } 1688 1689 phases::ID CudaInjectionPhase = 1690 (phases::Compile < FinalPhase && 1691 llvm::find(PL, phases::Compile) != PL.end()) 1692 ? phases::Compile 1693 : FinalPhase; 1694 1695 // Track the host offload kinds used on this input. 1696 unsigned InputActiveOffloadHostKinds = 0u; 1697 1698 // Build the pipeline for this file. 1699 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 1700 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end(); 1701 i != e; ++i) { 1702 phases::ID Phase = *i; 1703 1704 // We are done if this step is past what the user requested. 1705 if (Phase > FinalPhase) 1706 break; 1707 1708 // Queue linker inputs. 1709 if (Phase == phases::Link) { 1710 assert((i + 1) == e && "linking must be final compilation step."); 1711 LinkerInputs.push_back(Current); 1712 Current = nullptr; 1713 break; 1714 } 1715 1716 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1717 // encode this in the steps because the intermediate type depends on 1718 // arguments. Just special case here. 1719 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1720 continue; 1721 1722 // Otherwise construct the appropriate action. 1723 Current = ConstructPhaseAction(C, Args, Phase, Current); 1724 1725 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) { 1726 Current = buildCudaActions(C, Args, InputArg, Current, Actions); 1727 if (!Current) 1728 break; 1729 1730 // We produced a CUDA action for this input, so the host has to support 1731 // CUDA. 1732 InputActiveOffloadHostKinds |= Action::OFK_Cuda; 1733 CompilationActiveOffloadHostKinds |= Action::OFK_Cuda; 1734 } 1735 1736 if (Current->getType() == types::TY_Nothing) 1737 break; 1738 } 1739 1740 // If we ended with something, add to the output list. Also, propagate the 1741 // offload information to the top-level host action related with the current 1742 // input. 1743 if (Current) { 1744 if (InputActiveOffloadHostKinds) 1745 Current->propagateHostOffloadInfo(InputActiveOffloadHostKinds, 1746 /*BoundArch=*/nullptr); 1747 Actions.push_back(Current); 1748 } 1749 } 1750 1751 // Add a link action if necessary and propagate the offload information for 1752 // the current compilation. 1753 if (!LinkerInputs.empty()) { 1754 Actions.push_back( 1755 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image)); 1756 Actions.back()->propagateHostOffloadInfo(CompilationActiveOffloadHostKinds, 1757 /*BoundArch=*/nullptr); 1758 } 1759 1760 // If we are linking, claim any options which are obviously only used for 1761 // compilation. 1762 if (FinalPhase == phases::Link && PL.size() == 1) { 1763 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1764 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 1765 } 1766 1767 // Claim ignored clang-cl options. 1768 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 1769 1770 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 1771 // to non-CUDA compilations and should not trigger warnings there. 1772 Args.ClaimAllArgs(options::OPT_cuda_host_only); 1773 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 1774 } 1775 1776 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args, 1777 phases::ID Phase, Action *Input) const { 1778 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1779 // Build the appropriate action. 1780 switch (Phase) { 1781 case phases::Link: 1782 llvm_unreachable("link action invalid here."); 1783 case phases::Preprocess: { 1784 types::ID OutputTy; 1785 // -{M, MM} alter the output type. 1786 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1787 OutputTy = types::TY_Dependencies; 1788 } else { 1789 OutputTy = Input->getType(); 1790 if (!Args.hasFlag(options::OPT_frewrite_includes, 1791 options::OPT_fno_rewrite_includes, false) && 1792 !CCGenDiagnostics) 1793 OutputTy = types::getPreprocessedType(OutputTy); 1794 assert(OutputTy != types::TY_INVALID && 1795 "Cannot preprocess this input type!"); 1796 } 1797 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 1798 } 1799 case phases::Precompile: { 1800 types::ID OutputTy = types::TY_PCH; 1801 if (Args.hasArg(options::OPT_fsyntax_only)) { 1802 // Syntax checks should not emit a PCH file 1803 OutputTy = types::TY_Nothing; 1804 } 1805 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 1806 } 1807 case phases::Compile: { 1808 if (Args.hasArg(options::OPT_fsyntax_only)) 1809 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 1810 if (Args.hasArg(options::OPT_rewrite_objc)) 1811 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 1812 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 1813 return C.MakeAction<CompileJobAction>(Input, 1814 types::TY_RewrittenLegacyObjC); 1815 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) 1816 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 1817 if (Args.hasArg(options::OPT__migrate)) 1818 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 1819 if (Args.hasArg(options::OPT_emit_ast)) 1820 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 1821 if (Args.hasArg(options::OPT_module_file_info)) 1822 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 1823 if (Args.hasArg(options::OPT_verify_pch)) 1824 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 1825 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 1826 } 1827 case phases::Backend: { 1828 if (isUsingLTO()) { 1829 types::ID Output = 1830 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1831 return C.MakeAction<BackendJobAction>(Input, Output); 1832 } 1833 if (Args.hasArg(options::OPT_emit_llvm)) { 1834 types::ID Output = 1835 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 1836 return C.MakeAction<BackendJobAction>(Input, Output); 1837 } 1838 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 1839 } 1840 case phases::Assemble: 1841 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 1842 } 1843 1844 llvm_unreachable("invalid phase in ConstructPhaseAction"); 1845 } 1846 1847 void Driver::BuildJobs(Compilation &C) const { 1848 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1849 1850 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1851 1852 // It is an error to provide a -o option if we are making multiple output 1853 // files. 1854 if (FinalOutput) { 1855 unsigned NumOutputs = 0; 1856 for (const Action *A : C.getActions()) 1857 if (A->getType() != types::TY_Nothing) 1858 ++NumOutputs; 1859 1860 if (NumOutputs > 1) { 1861 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1862 FinalOutput = nullptr; 1863 } 1864 } 1865 1866 // Collect the list of architectures. 1867 llvm::StringSet<> ArchNames; 1868 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) 1869 for (const Arg *A : C.getArgs()) 1870 if (A->getOption().matches(options::OPT_arch)) 1871 ArchNames.insert(A->getValue()); 1872 1873 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 1874 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults; 1875 for (Action *A : C.getActions()) { 1876 // If we are linking an image for multiple archs then the linker wants 1877 // -arch_multiple and -final_output <final image name>. Unfortunately, this 1878 // doesn't fit in cleanly because we have to pass this information down. 1879 // 1880 // FIXME: This is a hack; find a cleaner way to integrate this into the 1881 // process. 1882 const char *LinkingOutput = nullptr; 1883 if (isa<LipoJobAction>(A)) { 1884 if (FinalOutput) 1885 LinkingOutput = FinalOutput->getValue(); 1886 else 1887 LinkingOutput = getDefaultImageName(); 1888 } 1889 1890 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1891 /*BoundArch*/ nullptr, 1892 /*AtTopLevel*/ true, 1893 /*MultipleArchs*/ ArchNames.size() > 1, 1894 /*LinkingOutput*/ LinkingOutput, CachedResults, 1895 /*BuildForOffloadDevice*/ false); 1896 } 1897 1898 // If the user passed -Qunused-arguments or there were errors, don't warn 1899 // about any unused arguments. 1900 if (Diags.hasErrorOccurred() || 1901 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1902 return; 1903 1904 // Claim -### here. 1905 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1906 1907 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 1908 (void)C.getArgs().hasArg(options::OPT_driver_mode); 1909 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 1910 1911 for (Arg *A : C.getArgs()) { 1912 // FIXME: It would be nice to be able to send the argument to the 1913 // DiagnosticsEngine, so that extra values, position, and so on could be 1914 // printed. 1915 if (!A->isClaimed()) { 1916 if (A->getOption().hasFlag(options::NoArgumentUnused)) 1917 continue; 1918 1919 // Suppress the warning automatically if this is just a flag, and it is an 1920 // instance of an argument we already claimed. 1921 const Option &Opt = A->getOption(); 1922 if (Opt.getKind() == Option::FlagClass) { 1923 bool DuplicateClaimed = false; 1924 1925 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 1926 if (AA->isClaimed()) { 1927 DuplicateClaimed = true; 1928 break; 1929 } 1930 } 1931 1932 if (DuplicateClaimed) 1933 continue; 1934 } 1935 1936 // In clang-cl, don't mention unknown arguments here since they have 1937 // already been warned about. 1938 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 1939 Diag(clang::diag::warn_drv_unused_argument) 1940 << A->getAsString(C.getArgs()); 1941 } 1942 } 1943 } 1944 /// Collapse an offloading action looking for a job of the given type. The input 1945 /// action is changed to the input of the collapsed sequence. If we effectively 1946 /// had a collapse return the corresponding offloading action, otherwise return 1947 /// null. 1948 template <typename T> 1949 static OffloadAction *collapseOffloadingAction(Action *&CurAction) { 1950 if (!CurAction) 1951 return nullptr; 1952 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 1953 if (OA->hasHostDependence()) 1954 if (auto *HDep = dyn_cast<T>(OA->getHostDependence())) { 1955 CurAction = HDep; 1956 return OA; 1957 } 1958 if (OA->hasSingleDeviceDependence()) 1959 if (auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) { 1960 CurAction = DDep; 1961 return OA; 1962 } 1963 } 1964 return nullptr; 1965 } 1966 // Returns a Tool for a given JobAction. In case the action and its 1967 // predecessors can be combined, updates Inputs with the inputs of the 1968 // first combined action. If one of the collapsed actions is a 1969 // CudaHostAction, updates CollapsedCHA with the pointer to it so the 1970 // caller can deal with extra handling such action requires. 1971 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps, 1972 bool EmbedBitcode, const ToolChain *TC, 1973 const JobAction *JA, 1974 const ActionList *&Inputs, 1975 ActionList &CollapsedOffloadAction) { 1976 const Tool *ToolForJob = nullptr; 1977 CollapsedOffloadAction.clear(); 1978 1979 // See if we should look for a compiler with an integrated assembler. We match 1980 // bottom up, so what we are actually looking for is an assembler job with a 1981 // compiler input. 1982 1983 // Look through offload actions between assembler and backend actions. 1984 Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1) 1985 ? *Inputs->begin() 1986 : nullptr; 1987 auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA); 1988 1989 if (TC->useIntegratedAs() && !SaveTemps && 1990 !C.getArgs().hasArg(options::OPT_via_file_asm) && 1991 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 1992 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA && 1993 isa<BackendJobAction>(BackendJA)) { 1994 // A BackendJob is always preceded by a CompileJob, and without -save-temps 1995 // or -fembed-bitcode, they will always get combined together, so instead of 1996 // checking the backend tool, check if the tool for the CompileJob has an 1997 // integrated assembler. For -fembed-bitcode, CompileJob is still used to 1998 // look up tools for BackendJob, but they need to match before we can split 1999 // them. 2000 2001 // Look through offload actions between backend and compile actions. 2002 Action *CompileJA = *BackendJA->getInputs().begin(); 2003 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA); 2004 2005 assert(CompileJA && isa<CompileJobAction>(CompileJA) && 2006 "Backend job is not preceeded by compile job."); 2007 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA)); 2008 if (!Compiler) 2009 return nullptr; 2010 // When using -fembed-bitcode, it is required to have the same tool (clang) 2011 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 2012 if (EmbedBitcode) { 2013 JobAction *InputJA = cast<JobAction>(*Inputs->begin()); 2014 const Tool *BackendTool = TC->SelectTool(*InputJA); 2015 if (BackendTool == Compiler) 2016 CompileJA = InputJA; 2017 } 2018 if (Compiler->hasIntegratedAssembler()) { 2019 Inputs = &CompileJA->getInputs(); 2020 ToolForJob = Compiler; 2021 // Save the collapsed offload actions because they may still contain 2022 // device actions. 2023 if (CompileOA) 2024 CollapsedOffloadAction.push_back(CompileOA); 2025 if (BackendOA) 2026 CollapsedOffloadAction.push_back(BackendOA); 2027 } 2028 } 2029 2030 // A backend job should always be combined with the preceding compile job 2031 // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is 2032 // capable of emitting LLVM IR as an intermediate output. 2033 if (isa<BackendJobAction>(JA)) { 2034 // Check if the compiler supports emitting LLVM IR. 2035 assert(Inputs->size() == 1); 2036 2037 // Look through offload actions between backend and compile actions. 2038 Action *CompileJA = *JA->getInputs().begin(); 2039 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA); 2040 2041 assert(CompileJA && isa<CompileJobAction>(CompileJA) && 2042 "Backend job is not preceeded by compile job."); 2043 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA)); 2044 if (!Compiler) 2045 return nullptr; 2046 if (!Compiler->canEmitIR() || 2047 (!SaveTemps && !EmbedBitcode)) { 2048 Inputs = &CompileJA->getInputs(); 2049 ToolForJob = Compiler; 2050 2051 if (CompileOA) 2052 CollapsedOffloadAction.push_back(CompileOA); 2053 } 2054 } 2055 2056 // Otherwise use the tool for the current job. 2057 if (!ToolForJob) 2058 ToolForJob = TC->SelectTool(*JA); 2059 2060 // See if we should use an integrated preprocessor. We do so when we have 2061 // exactly one input, since this is the only use case we care about 2062 // (irrelevant since we don't support combine yet). 2063 2064 // Look through offload actions after preprocessing. 2065 Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() : nullptr; 2066 auto *PreprocessOA = 2067 collapseOffloadingAction<PreprocessJobAction>(PreprocessJA); 2068 2069 if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) && 2070 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 2071 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 2072 !C.getArgs().hasArg(options::OPT_rewrite_objc) && 2073 ToolForJob->hasIntegratedCPP()) { 2074 Inputs = &PreprocessJA->getInputs(); 2075 if (PreprocessOA) 2076 CollapsedOffloadAction.push_back(PreprocessOA); 2077 } 2078 2079 return ToolForJob; 2080 } 2081 2082 InputInfo Driver::BuildJobsForAction( 2083 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 2084 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 2085 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 2086 bool BuildForOffloadDevice) const { 2087 // The bound arch is not necessarily represented in the toolchain's triple -- 2088 // for example, armv7 and armv7s both map to the same triple -- so we need 2089 // both in our map. 2090 std::string TriplePlusArch = TC->getTriple().normalize(); 2091 if (BoundArch) { 2092 TriplePlusArch += "-"; 2093 TriplePlusArch += BoundArch; 2094 } 2095 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch}; 2096 auto CachedResult = CachedResults.find(ActionTC); 2097 if (CachedResult != CachedResults.end()) { 2098 return CachedResult->second; 2099 } 2100 InputInfo Result = BuildJobsForActionNoCache( 2101 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 2102 CachedResults, BuildForOffloadDevice); 2103 CachedResults[ActionTC] = Result; 2104 return Result; 2105 } 2106 2107 InputInfo Driver::BuildJobsForActionNoCache( 2108 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 2109 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 2110 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 2111 bool BuildForOffloadDevice) const { 2112 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 2113 2114 InputInfoList OffloadDependencesInputInfo; 2115 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 2116 // The offload action is expected to be used in four different situations. 2117 // 2118 // a) Set a toolchain/architecture/kind for a host action: 2119 // Host Action 1 -> OffloadAction -> Host Action 2 2120 // 2121 // b) Set a toolchain/architecture/kind for a device action; 2122 // Device Action 1 -> OffloadAction -> Device Action 2 2123 // 2124 // c) Specify a device dependences to a host action; 2125 // Device Action 1 _ 2126 // \ 2127 // Host Action 1 ---> OffloadAction -> Host Action 2 2128 // 2129 // d) Specify a host dependence to a device action. 2130 // Host Action 1 _ 2131 // \ 2132 // Device Action 1 ---> OffloadAction -> Device Action 2 2133 // 2134 // For a) and b), we just return the job generated for the dependence. For 2135 // c) and d) we override the current action with the host/device dependence 2136 // if the current toolchain is host/device and set the offload dependences 2137 // info with the jobs obtained from the device/host dependence(s). 2138 2139 // If there is a single device option, just generate the job for it. 2140 if (OA->hasSingleDeviceDependence()) { 2141 InputInfo DevA; 2142 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 2143 const char *DepBoundArch) { 2144 DevA = 2145 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 2146 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 2147 CachedResults, /*BuildForOffloadDevice=*/true); 2148 }); 2149 return DevA; 2150 } 2151 2152 // If 'Action 2' is host, we generate jobs for the device dependences and 2153 // override the current action with the host dependence. Otherwise, we 2154 // generate the host dependences and override the action with the device 2155 // dependence. The dependences can't therefore be a top-level action. 2156 OA->doOnEachDependence( 2157 /*IsHostDependence=*/BuildForOffloadDevice, 2158 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 2159 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 2160 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 2161 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 2162 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != 2163 Action::OFK_None)); 2164 }); 2165 2166 A = BuildForOffloadDevice 2167 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 2168 : OA->getHostDependence(); 2169 } 2170 2171 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 2172 // FIXME: It would be nice to not claim this here; maybe the old scheme of 2173 // just using Args was better? 2174 const Arg &Input = IA->getInputArg(); 2175 Input.claim(); 2176 if (Input.getOption().matches(options::OPT_INPUT)) { 2177 const char *Name = Input.getValue(); 2178 return InputInfo(A, Name, /* BaseInput = */ Name); 2179 } 2180 return InputInfo(A, &Input, /* BaseInput = */ ""); 2181 } 2182 2183 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 2184 const ToolChain *TC; 2185 const char *ArchName = BAA->getArchName(); 2186 2187 if (ArchName) 2188 TC = &getToolChain(C.getArgs(), 2189 computeTargetTriple(*this, DefaultTargetTriple, 2190 C.getArgs(), ArchName)); 2191 else 2192 TC = &C.getDefaultToolChain(); 2193 2194 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 2195 MultipleArchs, LinkingOutput, CachedResults, 2196 BuildForOffloadDevice); 2197 } 2198 2199 2200 const ActionList *Inputs = &A->getInputs(); 2201 2202 const JobAction *JA = cast<JobAction>(A); 2203 ActionList CollapsedOffloadActions; 2204 2205 const Tool *T = 2206 selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA, 2207 Inputs, CollapsedOffloadActions); 2208 if (!T) 2209 return InputInfo(); 2210 2211 // If we've collapsed action list that contained OffloadAction we 2212 // need to build jobs for host/device-side inputs it may have held. 2213 for (const auto *OA : CollapsedOffloadActions) 2214 cast<OffloadAction>(OA)->doOnEachDependence( 2215 /*IsHostDependence=*/BuildForOffloadDevice, 2216 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 2217 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 2218 C, DepA, DepTC, DepBoundArch, AtTopLevel, 2219 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 2220 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != 2221 Action::OFK_None)); 2222 }); 2223 2224 // Only use pipes when there is exactly one input. 2225 InputInfoList InputInfos; 2226 for (const Action *Input : *Inputs) { 2227 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 2228 // shouldn't get temporary output names. 2229 // FIXME: Clean this up. 2230 bool SubJobAtTopLevel = 2231 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 2232 InputInfos.push_back(BuildJobsForAction( 2233 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 2234 CachedResults, BuildForOffloadDevice)); 2235 } 2236 2237 // Always use the first input as the base input. 2238 const char *BaseInput = InputInfos[0].getBaseInput(); 2239 2240 // ... except dsymutil actions, which use their actual input as the base 2241 // input. 2242 if (JA->getType() == types::TY_dSYM) 2243 BaseInput = InputInfos[0].getFilename(); 2244 2245 // Append outputs of offload device jobs to the input list 2246 if (!OffloadDependencesInputInfo.empty()) 2247 InputInfos.append(OffloadDependencesInputInfo.begin(), 2248 OffloadDependencesInputInfo.end()); 2249 2250 // Determine the place to write output to, if any. 2251 InputInfo Result; 2252 if (JA->getType() == types::TY_Nothing) 2253 Result = InputInfo(A, BaseInput); 2254 else 2255 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 2256 AtTopLevel, MultipleArchs, 2257 TC->getTriple().normalize()), 2258 BaseInput); 2259 2260 if (CCCPrintBindings && !CCGenDiagnostics) { 2261 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 2262 << " - \"" << T->getName() << "\", inputs: ["; 2263 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 2264 llvm::errs() << InputInfos[i].getAsString(); 2265 if (i + 1 != e) 2266 llvm::errs() << ", "; 2267 } 2268 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 2269 } else { 2270 T->ConstructJob(C, *JA, Result, InputInfos, 2271 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 2272 } 2273 return Result; 2274 } 2275 2276 const char *Driver::getDefaultImageName() const { 2277 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 2278 return Target.isOSWindows() ? "a.exe" : "a.out"; 2279 } 2280 2281 /// \brief Create output filename based on ArgValue, which could either be a 2282 /// full filename, filename without extension, or a directory. If ArgValue 2283 /// does not provide a filename, then use BaseName, and use the extension 2284 /// suitable for FileType. 2285 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 2286 StringRef BaseName, 2287 types::ID FileType) { 2288 SmallString<128> Filename = ArgValue; 2289 2290 if (ArgValue.empty()) { 2291 // If the argument is empty, output to BaseName in the current dir. 2292 Filename = BaseName; 2293 } else if (llvm::sys::path::is_separator(Filename.back())) { 2294 // If the argument is a directory, output to BaseName in that dir. 2295 llvm::sys::path::append(Filename, BaseName); 2296 } 2297 2298 if (!llvm::sys::path::has_extension(ArgValue)) { 2299 // If the argument didn't provide an extension, then set it. 2300 const char *Extension = types::getTypeTempSuffix(FileType, true); 2301 2302 if (FileType == types::TY_Image && 2303 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 2304 // The output file is a dll. 2305 Extension = "dll"; 2306 } 2307 2308 llvm::sys::path::replace_extension(Filename, Extension); 2309 } 2310 2311 return Args.MakeArgString(Filename.c_str()); 2312 } 2313 2314 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 2315 const char *BaseInput, 2316 const char *BoundArch, bool AtTopLevel, 2317 bool MultipleArchs, 2318 StringRef NormalizedTriple) const { 2319 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 2320 // Output to a user requested destination? 2321 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 2322 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 2323 return C.addResultFile(FinalOutput->getValue(), &JA); 2324 } 2325 2326 // For /P, preprocess to file named after BaseInput. 2327 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 2328 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 2329 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2330 StringRef NameArg; 2331 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 2332 NameArg = A->getValue(); 2333 return C.addResultFile( 2334 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 2335 &JA); 2336 } 2337 2338 // Default to writing to stdout? 2339 if (AtTopLevel && !CCGenDiagnostics && 2340 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 2341 return "-"; 2342 2343 // Is this the assembly listing for /FA? 2344 if (JA.getType() == types::TY_PP_Asm && 2345 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 2346 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 2347 // Use /Fa and the input filename to determine the asm file name. 2348 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2349 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 2350 return C.addResultFile( 2351 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 2352 &JA); 2353 } 2354 2355 // Output to a temporary file? 2356 if ((!AtTopLevel && !isSaveTempsEnabled() && 2357 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 2358 CCGenDiagnostics) { 2359 StringRef Name = llvm::sys::path::filename(BaseInput); 2360 std::pair<StringRef, StringRef> Split = Name.split('.'); 2361 std::string TmpName = GetTemporaryPath( 2362 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2363 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2364 } 2365 2366 SmallString<128> BasePath(BaseInput); 2367 StringRef BaseName; 2368 2369 // Dsymutil actions should use the full path. 2370 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 2371 BaseName = BasePath; 2372 else 2373 BaseName = llvm::sys::path::filename(BasePath); 2374 2375 // Determine what the derived output name should be. 2376 const char *NamedOutput; 2377 2378 if (JA.getType() == types::TY_Object && 2379 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 2380 // The /Fo or /o flag decides the object filename. 2381 StringRef Val = 2382 C.getArgs() 2383 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 2384 ->getValue(); 2385 NamedOutput = 2386 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 2387 } else if (JA.getType() == types::TY_Image && 2388 C.getArgs().hasArg(options::OPT__SLASH_Fe, 2389 options::OPT__SLASH_o)) { 2390 // The /Fe or /o flag names the linked file. 2391 StringRef Val = 2392 C.getArgs() 2393 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 2394 ->getValue(); 2395 NamedOutput = 2396 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 2397 } else if (JA.getType() == types::TY_Image) { 2398 if (IsCLMode()) { 2399 // clang-cl uses BaseName for the executable name. 2400 NamedOutput = 2401 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 2402 } else if (MultipleArchs && BoundArch) { 2403 SmallString<128> Output(getDefaultImageName()); 2404 Output += JA.getOffloadingFileNamePrefix(NormalizedTriple); 2405 Output += "-"; 2406 Output.append(BoundArch); 2407 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 2408 } else { 2409 NamedOutput = getDefaultImageName(); 2410 } 2411 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 2412 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str()); 2413 } else { 2414 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 2415 assert(Suffix && "All types used for output should have a suffix."); 2416 2417 std::string::size_type End = std::string::npos; 2418 if (!types::appendSuffixForType(JA.getType())) 2419 End = BaseName.rfind('.'); 2420 SmallString<128> Suffixed(BaseName.substr(0, End)); 2421 Suffixed += JA.getOffloadingFileNamePrefix(NormalizedTriple); 2422 if (MultipleArchs && BoundArch) { 2423 Suffixed += "-"; 2424 Suffixed.append(BoundArch); 2425 } 2426 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 2427 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 2428 // optimized bitcode output. 2429 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) && 2430 JA.getType() == types::TY_LLVM_BC) 2431 Suffixed += ".tmp"; 2432 Suffixed += '.'; 2433 Suffixed += Suffix; 2434 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 2435 } 2436 2437 // Prepend object file path if -save-temps=obj 2438 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 2439 JA.getType() != types::TY_PCH) { 2440 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 2441 SmallString<128> TempPath(FinalOutput->getValue()); 2442 llvm::sys::path::remove_filename(TempPath); 2443 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 2444 llvm::sys::path::append(TempPath, OutputFileName); 2445 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 2446 } 2447 2448 // If we're saving temps and the temp file conflicts with the input file, 2449 // then avoid overwriting input file. 2450 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 2451 bool SameFile = false; 2452 SmallString<256> Result; 2453 llvm::sys::fs::current_path(Result); 2454 llvm::sys::path::append(Result, BaseName); 2455 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 2456 // Must share the same path to conflict. 2457 if (SameFile) { 2458 StringRef Name = llvm::sys::path::filename(BaseInput); 2459 std::pair<StringRef, StringRef> Split = Name.split('.'); 2460 std::string TmpName = GetTemporaryPath( 2461 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2462 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2463 } 2464 } 2465 2466 // As an annoying special case, PCH generation doesn't strip the pathname. 2467 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 2468 llvm::sys::path::remove_filename(BasePath); 2469 if (BasePath.empty()) 2470 BasePath = NamedOutput; 2471 else 2472 llvm::sys::path::append(BasePath, NamedOutput); 2473 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 2474 } else { 2475 return C.addResultFile(NamedOutput, &JA); 2476 } 2477 } 2478 2479 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 2480 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2481 // attempting to use this prefix when looking for file paths. 2482 for (const std::string &Dir : PrefixDirs) { 2483 if (Dir.empty()) 2484 continue; 2485 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2486 llvm::sys::path::append(P, Name); 2487 if (llvm::sys::fs::exists(Twine(P))) 2488 return P.str(); 2489 } 2490 2491 SmallString<128> P(ResourceDir); 2492 llvm::sys::path::append(P, Name); 2493 if (llvm::sys::fs::exists(Twine(P))) 2494 return P.str(); 2495 2496 for (const std::string &Dir : TC.getFilePaths()) { 2497 if (Dir.empty()) 2498 continue; 2499 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2500 llvm::sys::path::append(P, Name); 2501 if (llvm::sys::fs::exists(Twine(P))) 2502 return P.str(); 2503 } 2504 2505 return Name; 2506 } 2507 2508 void Driver::generatePrefixedToolNames( 2509 const char *Tool, const ToolChain &TC, 2510 SmallVectorImpl<std::string> &Names) const { 2511 // FIXME: Needs a better variable than DefaultTargetTriple 2512 Names.emplace_back(DefaultTargetTriple + "-" + Tool); 2513 Names.emplace_back(Tool); 2514 2515 // Allow the discovery of tools prefixed with LLVM's default target triple. 2516 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple(); 2517 if (LLVMDefaultTargetTriple != DefaultTargetTriple) 2518 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool); 2519 } 2520 2521 static bool ScanDirForExecutable(SmallString<128> &Dir, 2522 ArrayRef<std::string> Names) { 2523 for (const auto &Name : Names) { 2524 llvm::sys::path::append(Dir, Name); 2525 if (llvm::sys::fs::can_execute(Twine(Dir))) 2526 return true; 2527 llvm::sys::path::remove_filename(Dir); 2528 } 2529 return false; 2530 } 2531 2532 std::string Driver::GetProgramPath(const char *Name, 2533 const ToolChain &TC) const { 2534 SmallVector<std::string, 2> TargetSpecificExecutables; 2535 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 2536 2537 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2538 // attempting to use this prefix when looking for program paths. 2539 for (const auto &PrefixDir : PrefixDirs) { 2540 if (llvm::sys::fs::is_directory(PrefixDir)) { 2541 SmallString<128> P(PrefixDir); 2542 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2543 return P.str(); 2544 } else { 2545 SmallString<128> P(PrefixDir + Name); 2546 if (llvm::sys::fs::can_execute(Twine(P))) 2547 return P.str(); 2548 } 2549 } 2550 2551 const ToolChain::path_list &List = TC.getProgramPaths(); 2552 for (const auto &Path : List) { 2553 SmallString<128> P(Path); 2554 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2555 return P.str(); 2556 } 2557 2558 // If all else failed, search the path. 2559 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) 2560 if (llvm::ErrorOr<std::string> P = 2561 llvm::sys::findProgramByName(TargetSpecificExecutable)) 2562 return *P; 2563 2564 return Name; 2565 } 2566 2567 std::string Driver::GetTemporaryPath(StringRef Prefix, 2568 const char *Suffix) const { 2569 SmallString<128> Path; 2570 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 2571 if (EC) { 2572 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 2573 return ""; 2574 } 2575 2576 return Path.str(); 2577 } 2578 2579 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 2580 SmallString<128> Output; 2581 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 2582 // FIXME: If anybody needs it, implement this obscure rule: 2583 // "If you specify a directory without a file name, the default file name 2584 // is VCx0.pch., where x is the major version of Visual C++ in use." 2585 Output = FpArg->getValue(); 2586 2587 // "If you do not specify an extension as part of the path name, an 2588 // extension of .pch is assumed. " 2589 if (!llvm::sys::path::has_extension(Output)) 2590 Output += ".pch"; 2591 } else { 2592 Output = BaseName; 2593 llvm::sys::path::replace_extension(Output, ".pch"); 2594 } 2595 return Output.str(); 2596 } 2597 2598 const ToolChain &Driver::getToolChain(const ArgList &Args, 2599 const llvm::Triple &Target) const { 2600 2601 ToolChain *&TC = ToolChains[Target.str()]; 2602 if (!TC) { 2603 switch (Target.getOS()) { 2604 case llvm::Triple::Haiku: 2605 TC = new toolchains::Haiku(*this, Target, Args); 2606 break; 2607 case llvm::Triple::CloudABI: 2608 TC = new toolchains::CloudABI(*this, Target, Args); 2609 break; 2610 case llvm::Triple::Darwin: 2611 case llvm::Triple::MacOSX: 2612 case llvm::Triple::IOS: 2613 case llvm::Triple::TvOS: 2614 case llvm::Triple::WatchOS: 2615 TC = new toolchains::DarwinClang(*this, Target, Args); 2616 break; 2617 case llvm::Triple::DragonFly: 2618 TC = new toolchains::DragonFly(*this, Target, Args); 2619 break; 2620 case llvm::Triple::OpenBSD: 2621 TC = new toolchains::OpenBSD(*this, Target, Args); 2622 break; 2623 case llvm::Triple::Bitrig: 2624 TC = new toolchains::Bitrig(*this, Target, Args); 2625 break; 2626 case llvm::Triple::NetBSD: 2627 TC = new toolchains::NetBSD(*this, Target, Args); 2628 break; 2629 case llvm::Triple::FreeBSD: 2630 TC = new toolchains::FreeBSD(*this, Target, Args); 2631 break; 2632 case llvm::Triple::Minix: 2633 TC = new toolchains::Minix(*this, Target, Args); 2634 break; 2635 case llvm::Triple::Linux: 2636 case llvm::Triple::ELFIAMCU: 2637 if (Target.getArch() == llvm::Triple::hexagon) 2638 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2639 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 2640 !Target.hasEnvironment()) 2641 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args); 2642 else 2643 TC = new toolchains::Linux(*this, Target, Args); 2644 break; 2645 case llvm::Triple::NaCl: 2646 TC = new toolchains::NaClToolChain(*this, Target, Args); 2647 break; 2648 case llvm::Triple::Solaris: 2649 TC = new toolchains::Solaris(*this, Target, Args); 2650 break; 2651 case llvm::Triple::AMDHSA: 2652 TC = new toolchains::AMDGPUToolChain(*this, Target, Args); 2653 break; 2654 case llvm::Triple::Win32: 2655 switch (Target.getEnvironment()) { 2656 default: 2657 if (Target.isOSBinFormatELF()) 2658 TC = new toolchains::Generic_ELF(*this, Target, Args); 2659 else if (Target.isOSBinFormatMachO()) 2660 TC = new toolchains::MachO(*this, Target, Args); 2661 else 2662 TC = new toolchains::Generic_GCC(*this, Target, Args); 2663 break; 2664 case llvm::Triple::GNU: 2665 TC = new toolchains::MinGW(*this, Target, Args); 2666 break; 2667 case llvm::Triple::Itanium: 2668 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args); 2669 break; 2670 case llvm::Triple::MSVC: 2671 case llvm::Triple::UnknownEnvironment: 2672 TC = new toolchains::MSVCToolChain(*this, Target, Args); 2673 break; 2674 } 2675 break; 2676 case llvm::Triple::CUDA: 2677 TC = new toolchains::CudaToolChain(*this, Target, Args); 2678 break; 2679 case llvm::Triple::PS4: 2680 TC = new toolchains::PS4CPU(*this, Target, Args); 2681 break; 2682 default: 2683 // Of these targets, Hexagon is the only one that might have 2684 // an OS of Linux, in which case it got handled above already. 2685 switch (Target.getArch()) { 2686 case llvm::Triple::tce: 2687 TC = new toolchains::TCEToolChain(*this, Target, Args); 2688 break; 2689 case llvm::Triple::hexagon: 2690 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2691 break; 2692 case llvm::Triple::lanai: 2693 TC = new toolchains::LanaiToolChain(*this, Target, Args); 2694 break; 2695 case llvm::Triple::xcore: 2696 TC = new toolchains::XCoreToolChain(*this, Target, Args); 2697 break; 2698 case llvm::Triple::wasm32: 2699 case llvm::Triple::wasm64: 2700 TC = new toolchains::WebAssembly(*this, Target, Args); 2701 break; 2702 default: 2703 if (Target.getVendor() == llvm::Triple::Myriad) 2704 TC = new toolchains::MyriadToolChain(*this, Target, Args); 2705 else if (Target.isOSBinFormatELF()) 2706 TC = new toolchains::Generic_ELF(*this, Target, Args); 2707 else if (Target.isOSBinFormatMachO()) 2708 TC = new toolchains::MachO(*this, Target, Args); 2709 else 2710 TC = new toolchains::Generic_GCC(*this, Target, Args); 2711 } 2712 } 2713 } 2714 return *TC; 2715 } 2716 2717 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 2718 // Say "no" if there is not exactly one input of a type clang understands. 2719 if (JA.size() != 1 || 2720 !types::isAcceptedByClang((*JA.input_begin())->getType())) 2721 return false; 2722 2723 // And say "no" if this is not a kind of action clang understands. 2724 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 2725 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 2726 return false; 2727 2728 return true; 2729 } 2730 2731 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 2732 /// grouped values as integers. Numbers which are not provided are set to 0. 2733 /// 2734 /// \return True if the entire string was parsed (9.2), or all groups were 2735 /// parsed (10.3.5extrastuff). 2736 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 2737 unsigned &Minor, unsigned &Micro, 2738 bool &HadExtra) { 2739 HadExtra = false; 2740 2741 Major = Minor = Micro = 0; 2742 if (*Str == '\0') 2743 return false; 2744 2745 char *End; 2746 Major = (unsigned)strtol(Str, &End, 10); 2747 if (*Str != '\0' && *End == '\0') 2748 return true; 2749 if (*End != '.') 2750 return false; 2751 2752 Str = End + 1; 2753 Minor = (unsigned)strtol(Str, &End, 10); 2754 if (*Str != '\0' && *End == '\0') 2755 return true; 2756 if (*End != '.') 2757 return false; 2758 2759 Str = End + 1; 2760 Micro = (unsigned)strtol(Str, &End, 10); 2761 if (*Str != '\0' && *End == '\0') 2762 return true; 2763 if (Str == End) 2764 return false; 2765 HadExtra = true; 2766 return true; 2767 } 2768 2769 /// Parse digits from a string \p Str and fulfill \p Digits with 2770 /// the parsed numbers. This method assumes that the max number of 2771 /// digits to look for is equal to Digits.size(). 2772 /// 2773 /// \return True if the entire string was parsed and there are 2774 /// no extra characters remaining at the end. 2775 bool Driver::GetReleaseVersion(const char *Str, 2776 MutableArrayRef<unsigned> Digits) { 2777 if (*Str == '\0') 2778 return false; 2779 2780 char *End; 2781 unsigned CurDigit = 0; 2782 while (CurDigit < Digits.size()) { 2783 unsigned Digit = (unsigned)strtol(Str, &End, 10); 2784 Digits[CurDigit] = Digit; 2785 if (*Str != '\0' && *End == '\0') 2786 return true; 2787 if (*End != '.' || Str == End) 2788 return false; 2789 Str = End + 1; 2790 CurDigit++; 2791 } 2792 2793 // More digits than requested, bail out... 2794 return false; 2795 } 2796 2797 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const { 2798 unsigned IncludedFlagsBitmask = 0; 2799 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 2800 2801 if (Mode == CLMode) { 2802 // Include CL and Core options. 2803 IncludedFlagsBitmask |= options::CLOption; 2804 IncludedFlagsBitmask |= options::CoreOption; 2805 } else { 2806 ExcludedFlagsBitmask |= options::CLOption; 2807 } 2808 2809 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 2810 } 2811 2812 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 2813 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 2814 } 2815