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