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