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