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