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