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