Driver.cpp revision 41ee7a371780d45f43251ee68542b8a9f0cd0fba
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#ifdef HAVE_CLANG_CONFIG_H 11# include "clang/Config/config.h" 12#endif 13 14#include "clang/Driver/Driver.h" 15 16#include "clang/Driver/Action.h" 17#include "clang/Driver/Arg.h" 18#include "clang/Driver/ArgList.h" 19#include "clang/Driver/Compilation.h" 20#include "clang/Driver/DriverDiagnostic.h" 21#include "clang/Driver/HostInfo.h" 22#include "clang/Driver/Job.h" 23#include "clang/Driver/OptTable.h" 24#include "clang/Driver/Option.h" 25#include "clang/Driver/Options.h" 26#include "clang/Driver/Tool.h" 27#include "clang/Driver/ToolChain.h" 28 29#include "clang/Basic/Version.h" 30 31#include "llvm/Config/config.h" 32#include "llvm/ADT/ArrayRef.h" 33#include "llvm/ADT/StringSet.h" 34#include "llvm/ADT/OwningPtr.h" 35#include "llvm/Support/PrettyStackTrace.h" 36#include "llvm/Support/raw_ostream.h" 37#include "llvm/Support/FileSystem.h" 38#include "llvm/Support/Path.h" 39#include "llvm/Support/Program.h" 40 41#include "InputInfo.h" 42 43#include <map> 44 45using namespace clang::driver; 46using namespace clang; 47 48Driver::Driver(StringRef ClangExecutable, 49 StringRef DefaultHostTriple, 50 StringRef DefaultImageName, 51 bool IsProduction, bool CXXIsProduction, 52 Diagnostic &Diags) 53 : Opts(createDriverOptTable()), Diags(Diags), 54 ClangExecutable(ClangExecutable), UseStdLib(true), 55 DefaultHostTriple(DefaultHostTriple), DefaultImageName(DefaultImageName), 56 DriverTitle("clang \"gcc-compatible\" driver"), 57 Host(0), 58 CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), 59 CCLogDiagnosticsFilename(0), CCCIsCXX(false), 60 CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false), 61 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), 62 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 63 CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true), 64 CCCUsePCH(true), SuppressMissingInputWarning(false) { 65 if (IsProduction) { 66 // In a "production" build, only use clang on architectures we expect to 67 // work, and don't use clang C++. 68 // 69 // During development its more convenient to always have the driver use 70 // clang, but we don't want users to be confused when things don't work, or 71 // to file bugs for things we don't support. 72 CCCClangArchs.insert(llvm::Triple::x86); 73 CCCClangArchs.insert(llvm::Triple::x86_64); 74 CCCClangArchs.insert(llvm::Triple::arm); 75 76 if (!CXXIsProduction) 77 CCCUseClangCXX = false; 78 } 79 80 Name = llvm::sys::path::stem(ClangExecutable); 81 Dir = llvm::sys::path::parent_path(ClangExecutable); 82 83 // Compute the path to the resource directory. 84 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 85 llvm::SmallString<128> P(Dir); 86 if (ClangResourceDir != "") 87 llvm::sys::path::append(P, ClangResourceDir); 88 else 89 llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); 90 ResourceDir = P.str(); 91} 92 93Driver::~Driver() { 94 delete Opts; 95 delete Host; 96} 97 98InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) { 99 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 100 unsigned MissingArgIndex, MissingArgCount; 101 InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(), 102 MissingArgIndex, MissingArgCount); 103 104 // Check for missing argument error. 105 if (MissingArgCount) 106 Diag(clang::diag::err_drv_missing_argument) 107 << Args->getArgString(MissingArgIndex) << MissingArgCount; 108 109 // Check for unsupported options. 110 for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 111 it != ie; ++it) { 112 Arg *A = *it; 113 if (A->getOption().isUnsupported()) { 114 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 115 continue; 116 } 117 } 118 119 return Args; 120} 121 122// Determine which compilation mode we are in. We look for options which 123// affect the phase, starting with the earliest phases, and record which 124// option we used to determine the final phase. 125phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) 126const { 127 Arg *PhaseArg = 0; 128 phases::ID FinalPhase; 129 130 // -{E,M,MM} only run the preprocessor. 131 if (CCCIsCPP || 132 (PhaseArg = DAL.getLastArg(options::OPT_E)) || 133 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) { 134 FinalPhase = phases::Preprocess; 135 136 // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. 137 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 138 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 139 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 140 options::OPT__analyze_auto)) || 141 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || 142 (PhaseArg = DAL.getLastArg(options::OPT_S))) { 143 FinalPhase = phases::Compile; 144 145 // -c only runs up to the assembler. 146 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 147 FinalPhase = phases::Assemble; 148 149 // Otherwise do everything. 150 } else 151 FinalPhase = phases::Link; 152 153 if (FinalPhaseArg) 154 *FinalPhaseArg = PhaseArg; 155 156 return FinalPhase; 157} 158 159DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 160 DerivedArgList *DAL = new DerivedArgList(Args); 161 162 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 163 for (ArgList::const_iterator it = Args.begin(), 164 ie = Args.end(); it != ie; ++it) { 165 const Arg *A = *it; 166 167 // Unfortunately, we have to parse some forwarding options (-Xassembler, 168 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 169 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 170 171 // Rewrite linker options, to replace --no-demangle with a custom internal 172 // option. 173 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 174 A->getOption().matches(options::OPT_Xlinker)) && 175 A->containsValue("--no-demangle")) { 176 // Add the rewritten no-demangle argument. 177 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 178 179 // Add the remaining values as Xlinker arguments. 180 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 181 if (StringRef(A->getValue(Args, i)) != "--no-demangle") 182 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), 183 A->getValue(Args, i)); 184 185 continue; 186 } 187 188 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 189 // some build systems. We don't try to be complete here because we don't 190 // care to encourage this usage model. 191 if (A->getOption().matches(options::OPT_Wp_COMMA) && 192 A->getNumValues() == 2 && 193 (A->getValue(Args, 0) == StringRef("-MD") || 194 A->getValue(Args, 0) == StringRef("-MMD"))) { 195 // Rewrite to -MD/-MMD along with -MF. 196 if (A->getValue(Args, 0) == StringRef("-MD")) 197 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 198 else 199 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 200 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 201 A->getValue(Args, 1)); 202 continue; 203 } 204 205 // Rewrite reserved library names. 206 if (A->getOption().matches(options::OPT_l)) { 207 StringRef Value = A->getValue(Args); 208 209 // Rewrite unless -nostdlib is present. 210 if (!HasNostdlib && Value == "stdc++") { 211 DAL->AddFlagArg(A, Opts->getOption( 212 options::OPT_Z_reserved_lib_stdcxx)); 213 continue; 214 } 215 216 // Rewrite unconditionally. 217 if (Value == "cc_kext") { 218 DAL->AddFlagArg(A, Opts->getOption( 219 options::OPT_Z_reserved_lib_cckext)); 220 continue; 221 } 222 } 223 224 DAL->append(*it); 225 } 226 227 // Add a default value of -mlinker-version=, if one was given and the user 228 // didn't specify one. 229#if defined(HOST_LINK_VERSION) 230 if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { 231 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 232 HOST_LINK_VERSION); 233 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 234 } 235#endif 236 237 return DAL; 238} 239 240Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 241 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 242 243 // FIXME: Handle environment options which affect driver behavior, somewhere 244 // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH, 245 // CC_PRINT_OPTIONS. 246 247 // FIXME: What are we going to do with -V and -b? 248 249 // FIXME: This stuff needs to go into the Compilation, not the driver. 250 bool CCCPrintOptions = false, CCCPrintActions = false; 251 252 InputArgList *Args = ParseArgStrings(ArgList.slice(1)); 253 254 // -no-canonical-prefixes is used very early in main. 255 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); 256 257 // Ignore -pipe. 258 Args->ClaimAllArgs(options::OPT_pipe); 259 260 // Extract -ccc args. 261 // 262 // FIXME: We need to figure out where this behavior should live. Most of it 263 // should be outside in the client; the parts that aren't should have proper 264 // options, either by introducing new ones or by overloading gcc ones like -V 265 // or -b. 266 CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options); 267 CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); 268 CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); 269 CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX; 270 CCCEcho = Args->hasArg(options::OPT_ccc_echo); 271 if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) 272 CCCGenericGCCName = A->getValue(*Args); 273 CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx, 274 options::OPT_ccc_no_clang_cxx, 275 CCCUseClangCXX); 276 CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, 277 options::OPT_ccc_pch_is_pth); 278 CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang); 279 CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp); 280 if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) { 281 StringRef Cur = A->getValue(*Args); 282 283 CCCClangArchs.clear(); 284 while (!Cur.empty()) { 285 std::pair<StringRef, StringRef> Split = Cur.split(','); 286 287 if (!Split.first.empty()) { 288 llvm::Triple::ArchType Arch = 289 llvm::Triple(Split.first, "", "").getArch(); 290 291 if (Arch == llvm::Triple::UnknownArch) 292 Diag(clang::diag::err_drv_invalid_arch_name) << Split.first; 293 294 CCCClangArchs.insert(Arch); 295 } 296 297 Cur = Split.second; 298 } 299 } 300 // FIXME: We shouldn't overwrite the default host triple here, but we have 301 // nowhere else to put this currently. 302 if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple)) 303 DefaultHostTriple = A->getValue(*Args); 304 if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) 305 Dir = InstalledDir = A->getValue(*Args); 306 for (arg_iterator it = Args->filtered_begin(options::OPT_B), 307 ie = Args->filtered_end(); it != ie; ++it) { 308 const Arg *A = *it; 309 A->claim(); 310 PrefixDirs.push_back(A->getValue(*Args, 0)); 311 } 312 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) 313 SysRoot = A->getValue(*Args); 314 if (Args->hasArg(options::OPT_nostdlib)) 315 UseStdLib = false; 316 317 Host = GetHostInfo(DefaultHostTriple.c_str()); 318 319 // Perform the default argument translations. 320 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); 321 322 // The compilation takes ownership of Args. 323 Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args, 324 TranslatedArgs); 325 326 // FIXME: This behavior shouldn't be here. 327 if (CCCPrintOptions) { 328 PrintOptions(C->getInputArgs()); 329 return C; 330 } 331 332 if (!HandleImmediateArgs(*C)) 333 return C; 334 335 // Construct the list of inputs. 336 InputList Inputs; 337 BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs); 338 339 // Construct the list of abstract actions to perform for this compilation. 340 if (Host->useDriverDriver()) 341 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), 342 Inputs, C->getActions()); 343 else 344 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, 345 C->getActions()); 346 347 if (CCCPrintActions) { 348 PrintActions(*C); 349 return C; 350 } 351 352 BuildJobs(*C); 353 354 return C; 355} 356 357// When clang crashes, produce diagnostic information including the fully 358// preprocessed source file(s). Request that the developer attach the 359// diagnostic information to a bug report. 360void Driver::generateCompilationDiagnostics(Compilation &C, 361 const Command *FailingCommand) { 362 Diag(clang::diag::note_drv_command_failed_diag_msg) 363 << "Please submit a bug report to " BUG_REPORT_URL " and include command" 364 " line arguments and all diagnostic information."; 365 366 // Suppress driver output and emit preprocessor output to temp file. 367 CCCIsCPP = true; 368 CCGenDiagnostics = true; 369 370 // Clear stale state and suppress tool output. 371 C.initCompilationForDiagnostics(); 372 Diags.Reset(); 373 374 // Construct the list of inputs. 375 InputList Inputs; 376 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 377 378 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 379 bool IgnoreInput = false; 380 381 // Ignore input from stdin or any inputs that cannot be preprocessed. 382 if (!strcmp(it->second->getValue(C.getArgs()), "-")) { 383 Diag(clang::diag::note_drv_command_failed_diag_msg) 384 << "Error generating preprocessed source(s) - ignoring input from stdin" 385 "."; 386 IgnoreInput = true; 387 } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 388 IgnoreInput = true; 389 } 390 391 if (IgnoreInput) { 392 it = Inputs.erase(it); 393 ie = Inputs.end(); 394 } else { 395 ++it; 396 } 397 } 398 399 if (Inputs.empty()) { 400 Diag(clang::diag::note_drv_command_failed_diag_msg) 401 << "Error generating preprocessed source(s) - no preprocessable inputs."; 402 return; 403 } 404 405 // Construct the list of abstract actions to perform for this compilation. 406 if (Host->useDriverDriver()) 407 BuildUniversalActions(C.getDefaultToolChain(), C.getArgs(), 408 Inputs, C.getActions()); 409 else 410 BuildActions(C.getDefaultToolChain(), C.getArgs(), Inputs, 411 C.getActions()); 412 413 BuildJobs(C); 414 415 // If there were errors building the compilation, quit now. 416 if (Diags.hasErrorOccurred()) { 417 Diag(clang::diag::note_drv_command_failed_diag_msg) 418 << "Error generating preprocessed source(s)."; 419 return; 420 } 421 422 // Generate preprocessed output. 423 FailingCommand = 0; 424 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 425 426 // If the command succeeded, we are done. 427 if (Res == 0) { 428 Diag(clang::diag::note_drv_command_failed_diag_msg) 429 << "Preprocessed source(s) are located at:"; 430 ArgStringList Files = C.getTempFiles(); 431 for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); 432 it != ie; ++it) 433 Diag(clang::diag::note_drv_command_failed_diag_msg) << *it; 434 } else { 435 // Failure, remove preprocessed files. 436 if (!C.getArgs().hasArg(options::OPT_save_temps)) 437 C.CleanupFileList(C.getTempFiles(), true); 438 439 Diag(clang::diag::note_drv_command_failed_diag_msg) 440 << "Error generating preprocessed source(s)."; 441 } 442} 443 444int Driver::ExecuteCompilation(const Compilation &C, 445 const Command *&FailingCommand) const { 446 // Just print if -### was present. 447 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 448 C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); 449 return 0; 450 } 451 452 // If there were errors building the compilation, quit now. 453 if (Diags.hasErrorOccurred()) 454 return 1; 455 456 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 457 458 // Remove temp files. 459 C.CleanupFileList(C.getTempFiles()); 460 461 // If the command succeeded, we are done. 462 if (Res == 0) 463 return Res; 464 465 // Otherwise, remove result files as well. 466 if (!C.getArgs().hasArg(options::OPT_save_temps)) 467 C.CleanupFileList(C.getResultFiles(), true); 468 469 // Print extra information about abnormal failures, if possible. 470 // 471 // This is ad-hoc, but we don't want to be excessively noisy. If the result 472 // status was 1, assume the command failed normally. In particular, if it was 473 // the compiler then assume it gave a reasonable error code. Failures in other 474 // tools are less common, and they generally have worse diagnostics, so always 475 // print the diagnostic there. 476 const Tool &FailingTool = FailingCommand->getCreator(); 477 478 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 479 // FIXME: See FIXME above regarding result code interpretation. 480 if (Res < 0) 481 Diag(clang::diag::err_drv_command_signalled) 482 << FailingTool.getShortName() << -Res; 483 else 484 Diag(clang::diag::err_drv_command_failed) 485 << FailingTool.getShortName() << Res; 486 } 487 488 return Res; 489} 490 491void Driver::PrintOptions(const ArgList &Args) const { 492 unsigned i = 0; 493 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 494 it != ie; ++it, ++i) { 495 Arg *A = *it; 496 llvm::errs() << "Option " << i << " - " 497 << "Name: \"" << A->getOption().getName() << "\", " 498 << "Values: {"; 499 for (unsigned j = 0; j < A->getNumValues(); ++j) { 500 if (j) 501 llvm::errs() << ", "; 502 llvm::errs() << '"' << A->getValue(Args, j) << '"'; 503 } 504 llvm::errs() << "}\n"; 505 } 506} 507 508void Driver::PrintHelp(bool ShowHidden) const { 509 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 510 ShowHidden); 511} 512 513void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 514 // FIXME: The following handlers should use a callback mechanism, we don't 515 // know what the client would like to do. 516 OS << getClangFullVersion() << '\n'; 517 const ToolChain &TC = C.getDefaultToolChain(); 518 OS << "Target: " << TC.getTripleString() << '\n'; 519 520 // Print the threading model. 521 // 522 // FIXME: Implement correctly. 523 OS << "Thread model: " << "posix" << '\n'; 524} 525 526/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 527/// option. 528static void PrintDiagnosticCategories(raw_ostream &OS) { 529 // Skip the empty category. 530 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); 531 i != max; ++i) 532 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 533} 534 535bool Driver::HandleImmediateArgs(const Compilation &C) { 536 // The order these options are handled in gcc is all over the place, but we 537 // don't expect inconsistencies w.r.t. that to matter in practice. 538 539 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 540 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 541 return false; 542 } 543 544 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 545 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 546 // return an answer which matches our definition of __VERSION__. 547 // 548 // If we want to return a more correct answer some day, then we should 549 // introduce a non-pedantically GCC compatible mode to Clang in which we 550 // provide sensible definitions for -dumpversion, __VERSION__, etc. 551 llvm::outs() << "4.2.1\n"; 552 return false; 553 } 554 555 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 556 PrintDiagnosticCategories(llvm::outs()); 557 return false; 558 } 559 560 if (C.getArgs().hasArg(options::OPT__help) || 561 C.getArgs().hasArg(options::OPT__help_hidden)) { 562 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 563 return false; 564 } 565 566 if (C.getArgs().hasArg(options::OPT__version)) { 567 // Follow gcc behavior and use stdout for --version and stderr for -v. 568 PrintVersion(C, llvm::outs()); 569 return false; 570 } 571 572 if (C.getArgs().hasArg(options::OPT_v) || 573 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 574 PrintVersion(C, llvm::errs()); 575 SuppressMissingInputWarning = true; 576 } 577 578 const ToolChain &TC = C.getDefaultToolChain(); 579 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 580 llvm::outs() << "programs: ="; 581 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 582 ie = TC.getProgramPaths().end(); it != ie; ++it) { 583 if (it != TC.getProgramPaths().begin()) 584 llvm::outs() << ':'; 585 llvm::outs() << *it; 586 } 587 llvm::outs() << "\n"; 588 llvm::outs() << "libraries: =" << ResourceDir; 589 590 std::string sysroot; 591 if (Arg *A = C.getArgs().getLastArg(options::OPT__sysroot_EQ)) 592 sysroot = A->getValue(C.getArgs()); 593 594 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 595 ie = TC.getFilePaths().end(); it != ie; ++it) { 596 llvm::outs() << ':'; 597 const char *path = it->c_str(); 598 if (path[0] == '=') 599 llvm::outs() << sysroot << path + 1; 600 else 601 llvm::outs() << path; 602 } 603 llvm::outs() << "\n"; 604 return false; 605 } 606 607 // FIXME: The following handlers should use a callback mechanism, we don't 608 // know what the client would like to do. 609 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 610 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n"; 611 return false; 612 } 613 614 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 615 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n"; 616 return false; 617 } 618 619 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 620 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 621 return false; 622 } 623 624 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 625 // FIXME: We need tool chain support for this. 626 llvm::outs() << ".;\n"; 627 628 switch (C.getDefaultToolChain().getTriple().getArch()) { 629 default: 630 break; 631 632 case llvm::Triple::x86_64: 633 llvm::outs() << "x86_64;@m64" << "\n"; 634 break; 635 636 case llvm::Triple::ppc64: 637 llvm::outs() << "ppc64;@m64" << "\n"; 638 break; 639 } 640 return false; 641 } 642 643 // FIXME: What is the difference between print-multi-directory and 644 // print-multi-os-directory? 645 if (C.getArgs().hasArg(options::OPT_print_multi_directory) || 646 C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 647 switch (C.getDefaultToolChain().getTriple().getArch()) { 648 default: 649 case llvm::Triple::x86: 650 case llvm::Triple::ppc: 651 llvm::outs() << "." << "\n"; 652 break; 653 654 case llvm::Triple::x86_64: 655 llvm::outs() << "x86_64" << "\n"; 656 break; 657 658 case llvm::Triple::ppc64: 659 llvm::outs() << "ppc64" << "\n"; 660 break; 661 } 662 return false; 663 } 664 665 return true; 666} 667 668static unsigned PrintActions1(const Compilation &C, Action *A, 669 std::map<Action*, unsigned> &Ids) { 670 if (Ids.count(A)) 671 return Ids[A]; 672 673 std::string str; 674 llvm::raw_string_ostream os(str); 675 676 os << Action::getClassName(A->getKind()) << ", "; 677 if (InputAction *IA = dyn_cast<InputAction>(A)) { 678 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; 679 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 680 os << '"' << (BIA->getArchName() ? BIA->getArchName() : 681 C.getDefaultToolChain().getArchName()) << '"' 682 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 683 } else { 684 os << "{"; 685 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 686 os << PrintActions1(C, *it, Ids); 687 ++it; 688 if (it != ie) 689 os << ", "; 690 } 691 os << "}"; 692 } 693 694 unsigned Id = Ids.size(); 695 Ids[A] = Id; 696 llvm::errs() << Id << ": " << os.str() << ", " 697 << types::getTypeName(A->getType()) << "\n"; 698 699 return Id; 700} 701 702void Driver::PrintActions(const Compilation &C) const { 703 std::map<Action*, unsigned> Ids; 704 for (ActionList::const_iterator it = C.getActions().begin(), 705 ie = C.getActions().end(); it != ie; ++it) 706 PrintActions1(C, *it, Ids); 707} 708 709/// \brief Check whether the given input tree contains any compilation or 710/// assembly actions. 711static bool ContainsCompileOrAssembleAction(const Action *A) { 712 if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) 713 return true; 714 715 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) 716 if (ContainsCompileOrAssembleAction(*it)) 717 return true; 718 719 return false; 720} 721 722void Driver::BuildUniversalActions(const ToolChain &TC, 723 const DerivedArgList &Args, 724 const InputList &BAInputs, 725 ActionList &Actions) const { 726 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 727 // Collect the list of architectures. Duplicates are allowed, but should only 728 // be handled once (in the order seen). 729 llvm::StringSet<> ArchNames; 730 SmallVector<const char *, 4> Archs; 731 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 732 it != ie; ++it) { 733 Arg *A = *it; 734 735 if (A->getOption().matches(options::OPT_arch)) { 736 // Validate the option here; we don't save the type here because its 737 // particular spelling may participate in other driver choices. 738 llvm::Triple::ArchType Arch = 739 llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); 740 if (Arch == llvm::Triple::UnknownArch) { 741 Diag(clang::diag::err_drv_invalid_arch_name) 742 << A->getAsString(Args); 743 continue; 744 } 745 746 A->claim(); 747 if (ArchNames.insert(A->getValue(Args))) 748 Archs.push_back(A->getValue(Args)); 749 } 750 } 751 752 // When there is no explicit arch for this platform, make sure we still bind 753 // the architecture (to the default) so that -Xarch_ is handled correctly. 754 if (!Archs.size()) 755 Archs.push_back(0); 756 757 // FIXME: We killed off some others but these aren't yet detected in a 758 // functional manner. If we added information to jobs about which "auxiliary" 759 // files they wrote then we could detect the conflict these cause downstream. 760 if (Archs.size() > 1) { 761 // No recovery needed, the point of this is just to prevent 762 // overwriting the same files. 763 if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 764 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 765 << A->getAsString(Args); 766 } 767 768 ActionList SingleActions; 769 BuildActions(TC, Args, BAInputs, SingleActions); 770 771 // Add in arch bindings for every top level action, as well as lipo and 772 // dsymutil steps if needed. 773 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 774 Action *Act = SingleActions[i]; 775 776 // Make sure we can lipo this kind of output. If not (and it is an actual 777 // output) then we disallow, since we can't create an output file with the 778 // right name without overwriting it. We could remove this oddity by just 779 // changing the output names to include the arch, which would also fix 780 // -save-temps. Compatibility wins for now. 781 782 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 783 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 784 << types::getTypeName(Act->getType()); 785 786 ActionList Inputs; 787 for (unsigned i = 0, e = Archs.size(); i != e; ++i) { 788 Inputs.push_back(new BindArchAction(Act, Archs[i])); 789 if (i != 0) 790 Inputs.back()->setOwnsInputs(false); 791 } 792 793 // Lipo if necessary, we do it this way because we need to set the arch flag 794 // so that -Xarch_ gets overwritten. 795 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 796 Actions.append(Inputs.begin(), Inputs.end()); 797 else 798 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 799 800 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 801 // have a compile input. We need to run 'dsymutil' ourselves in such cases 802 // because the debug info will refer to a temporary object file which is 803 // will be removed at the end of the compilation process. 804 if (Act->getType() == types::TY_Image) { 805 Arg *A = Args.getLastArg(options::OPT_g_Group); 806 if (A && !A->getOption().matches(options::OPT_g0) && 807 !A->getOption().matches(options::OPT_gstabs) && 808 ContainsCompileOrAssembleAction(Actions.back())) { 809 ActionList Inputs; 810 Inputs.push_back(Actions.back()); 811 Actions.pop_back(); 812 813 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); 814 815 // Verify the debug output if we're in assert mode. 816 // TODO: The verifier is noisy by default so put this under an 817 // option for now. 818 #ifndef NDEBUG 819 if (Args.hasArg(options::OPT_verify)) { 820 ActionList VerifyInputs; 821 VerifyInputs.push_back(Actions.back()); 822 Actions.pop_back(); 823 Actions.push_back(new VerifyJobAction(VerifyInputs, 824 types::TY_Nothing)); 825 } 826 #endif 827 } 828 } 829 } 830} 831 832// Construct a the list of inputs and their types. 833void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 834 InputList &Inputs) const { 835 // Track the current user specified (-x) input. We also explicitly track the 836 // argument used to set the type; we only want to claim the type when we 837 // actually use it, so we warn about unused -x arguments. 838 types::ID InputType = types::TY_Nothing; 839 Arg *InputTypeArg = 0; 840 841 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 842 it != ie; ++it) { 843 Arg *A = *it; 844 845 if (isa<InputOption>(A->getOption())) { 846 const char *Value = A->getValue(Args); 847 types::ID Ty = types::TY_INVALID; 848 849 // Infer the input type if necessary. 850 if (InputType == types::TY_Nothing) { 851 // If there was an explicit arg for this, claim it. 852 if (InputTypeArg) 853 InputTypeArg->claim(); 854 855 // stdin must be handled specially. 856 if (memcmp(Value, "-", 2) == 0) { 857 // If running with -E, treat as a C input (this changes the builtin 858 // macros, for example). This may be overridden by -ObjC below. 859 // 860 // Otherwise emit an error but still use a valid type to avoid 861 // spurious errors (e.g., no inputs). 862 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP) 863 Diag(clang::diag::err_drv_unknown_stdin_type); 864 Ty = types::TY_C; 865 } else { 866 // Otherwise lookup by extension. 867 // Fallback is C if invoked as C preprocessor or Object otherwise. 868 // We use a host hook here because Darwin at least has its own 869 // idea of what .s is. 870 if (const char *Ext = strrchr(Value, '.')) 871 Ty = TC.LookupTypeForExtension(Ext + 1); 872 873 if (Ty == types::TY_INVALID) { 874 if (CCCIsCPP) 875 Ty = types::TY_C; 876 else 877 Ty = types::TY_Object; 878 } 879 880 // If the driver is invoked as C++ compiler (like clang++ or c++) it 881 // should autodetect some input files as C++ for g++ compatibility. 882 if (CCCIsCXX) { 883 types::ID OldTy = Ty; 884 Ty = types::lookupCXXTypeForCType(Ty); 885 886 if (Ty != OldTy) 887 Diag(clang::diag::warn_drv_treating_input_as_cxx) 888 << getTypeName(OldTy) << getTypeName(Ty); 889 } 890 } 891 892 // -ObjC and -ObjC++ override the default language, but only for "source 893 // files". We just treat everything that isn't a linker input as a 894 // source file. 895 // 896 // FIXME: Clean this up if we move the phase sequence into the type. 897 if (Ty != types::TY_Object) { 898 if (Args.hasArg(options::OPT_ObjC)) 899 Ty = types::TY_ObjC; 900 else if (Args.hasArg(options::OPT_ObjCXX)) 901 Ty = types::TY_ObjCXX; 902 } 903 } else { 904 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 905 InputTypeArg->claim(); 906 Ty = InputType; 907 } 908 909 // Check that the file exists, if enabled. 910 if (CheckInputsExist && memcmp(Value, "-", 2) != 0) { 911 llvm::SmallString<64> Path(Value); 912 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) 913 if (llvm::sys::path::is_absolute(Path.str())) { 914 Path = WorkDir->getValue(Args); 915 llvm::sys::path::append(Path, Value); 916 } 917 918 bool exists = false; 919 if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists) 920 Diag(clang::diag::err_drv_no_such_file) << Path.str(); 921 else 922 Inputs.push_back(std::make_pair(Ty, A)); 923 } else 924 Inputs.push_back(std::make_pair(Ty, A)); 925 926 } else if (A->getOption().isLinkerInput()) { 927 // Just treat as object type, we could make a special type for this if 928 // necessary. 929 Inputs.push_back(std::make_pair(types::TY_Object, A)); 930 931 } else if (A->getOption().matches(options::OPT_x)) { 932 InputTypeArg = A; 933 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); 934 935 // Follow gcc behavior and treat as linker input for invalid -x 936 // options. Its not clear why we shouldn't just revert to unknown; but 937 // this isn't very important, we might as well be bug compatible. 938 if (!InputType) { 939 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); 940 InputType = types::TY_Object; 941 } 942 } 943 } 944 if (CCCIsCPP && Inputs.empty()) { 945 // If called as standalone preprocessor, stdin is processed 946 // if no other input is present. 947 unsigned Index = Args.getBaseArgs().MakeIndex("-"); 948 Arg *A = Opts->ParseOneArg(Args, Index); 949 A->claim(); 950 Inputs.push_back(std::make_pair(types::TY_C, A)); 951 } 952} 953 954void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args, 955 const InputList &Inputs, ActionList &Actions) const { 956 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 957 958 if (!SuppressMissingInputWarning && Inputs.empty()) { 959 Diag(clang::diag::err_drv_no_input_files); 960 return; 961 } 962 963 Arg *FinalPhaseArg; 964 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 965 966 // Reject -Z* at the top level, these options should never have been exposed 967 // by gcc. 968 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 969 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 970 971 // Construct the actions to perform. 972 ActionList LinkerInputs; 973 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 974 types::ID InputType = Inputs[i].first; 975 const Arg *InputArg = Inputs[i].second; 976 977 unsigned NumSteps = types::getNumCompilationPhases(InputType); 978 assert(NumSteps && "Invalid number of steps!"); 979 980 // If the first step comes after the final phase we are doing as part of 981 // this compilation, warn the user about it. 982 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); 983 if (InitialPhase > FinalPhase) { 984 // Claim here to avoid the more general unused warning. 985 InputArg->claim(); 986 987 // Suppress all unused style warnings with -Qunused-arguments 988 if (Args.hasArg(options::OPT_Qunused_arguments)) 989 continue; 990 991 // Special case '-E' warning on a previously preprocessed file to make 992 // more sense. 993 if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess && 994 getPreprocessedType(InputType) == types::TY_INVALID) 995 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 996 << InputArg->getAsString(Args) 997 << FinalPhaseArg->getOption().getName(); 998 else 999 Diag(clang::diag::warn_drv_input_file_unused) 1000 << InputArg->getAsString(Args) 1001 << getPhaseName(InitialPhase) 1002 << FinalPhaseArg->getOption().getName(); 1003 continue; 1004 } 1005 1006 // Build the pipeline for this file. 1007 llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); 1008 for (unsigned i = 0; i != NumSteps; ++i) { 1009 phases::ID Phase = types::getCompilationPhase(InputType, i); 1010 1011 // We are done if this step is past what the user requested. 1012 if (Phase > FinalPhase) 1013 break; 1014 1015 // Queue linker inputs. 1016 if (Phase == phases::Link) { 1017 assert(i + 1 == NumSteps && "linking must be final compilation step."); 1018 LinkerInputs.push_back(Current.take()); 1019 break; 1020 } 1021 1022 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1023 // encode this in the steps because the intermediate type depends on 1024 // arguments. Just special case here. 1025 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1026 continue; 1027 1028 // Otherwise construct the appropriate action. 1029 Current.reset(ConstructPhaseAction(Args, Phase, Current.take())); 1030 if (Current->getType() == types::TY_Nothing) 1031 break; 1032 } 1033 1034 // If we ended with something, add to the output list. 1035 if (Current) 1036 Actions.push_back(Current.take()); 1037 } 1038 1039 // Add a link action if necessary. 1040 if (!LinkerInputs.empty()) 1041 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 1042 1043 // If we are linking, claim any options which are obviously only used for 1044 // compilation. 1045 if (FinalPhase == phases::Link) 1046 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1047} 1048 1049Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 1050 Action *Input) const { 1051 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1052 // Build the appropriate action. 1053 switch (Phase) { 1054 case phases::Link: assert(0 && "link action invalid here."); 1055 case phases::Preprocess: { 1056 types::ID OutputTy; 1057 // -{M, MM} alter the output type. 1058 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1059 OutputTy = types::TY_Dependencies; 1060 } else { 1061 OutputTy = types::getPreprocessedType(Input->getType()); 1062 assert(OutputTy != types::TY_INVALID && 1063 "Cannot preprocess this input type!"); 1064 } 1065 return new PreprocessJobAction(Input, OutputTy); 1066 } 1067 case phases::Precompile: 1068 return new PrecompileJobAction(Input, types::TY_PCH); 1069 case phases::Compile: { 1070 if (Args.hasArg(options::OPT_fsyntax_only)) { 1071 return new CompileJobAction(Input, types::TY_Nothing); 1072 } else if (Args.hasArg(options::OPT_rewrite_objc)) { 1073 return new CompileJobAction(Input, types::TY_RewrittenObjC); 1074 } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { 1075 return new AnalyzeJobAction(Input, types::TY_Plist); 1076 } else if (Args.hasArg(options::OPT_emit_ast)) { 1077 return new CompileJobAction(Input, types::TY_AST); 1078 } else if (IsUsingLTO(Args)) { 1079 types::ID Output = 1080 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1081 return new CompileJobAction(Input, Output); 1082 } else { 1083 return new CompileJobAction(Input, types::TY_PP_Asm); 1084 } 1085 } 1086 case phases::Assemble: 1087 return new AssembleJobAction(Input, types::TY_Object); 1088 } 1089 1090 assert(0 && "invalid phase in ConstructPhaseAction"); 1091 return 0; 1092} 1093 1094bool Driver::IsUsingLTO(const ArgList &Args) const { 1095 // Check for -emit-llvm or -flto. 1096 if (Args.hasArg(options::OPT_emit_llvm) || 1097 Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) 1098 return true; 1099 1100 // Check for -O4. 1101 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) 1102 return A->getOption().matches(options::OPT_O4); 1103 1104 return false; 1105} 1106 1107void Driver::BuildJobs(Compilation &C) const { 1108 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1109 1110 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1111 1112 // It is an error to provide a -o option if we are making multiple output 1113 // files. 1114 if (FinalOutput) { 1115 unsigned NumOutputs = 0; 1116 for (ActionList::const_iterator it = C.getActions().begin(), 1117 ie = C.getActions().end(); it != ie; ++it) 1118 if ((*it)->getType() != types::TY_Nothing) 1119 ++NumOutputs; 1120 1121 if (NumOutputs > 1) { 1122 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1123 FinalOutput = 0; 1124 } 1125 } 1126 1127 for (ActionList::const_iterator it = C.getActions().begin(), 1128 ie = C.getActions().end(); it != ie; ++it) { 1129 Action *A = *it; 1130 1131 // If we are linking an image for multiple archs then the linker wants 1132 // -arch_multiple and -final_output <final image name>. Unfortunately, this 1133 // doesn't fit in cleanly because we have to pass this information down. 1134 // 1135 // FIXME: This is a hack; find a cleaner way to integrate this into the 1136 // process. 1137 const char *LinkingOutput = 0; 1138 if (isa<LipoJobAction>(A)) { 1139 if (FinalOutput) 1140 LinkingOutput = FinalOutput->getValue(C.getArgs()); 1141 else 1142 LinkingOutput = DefaultImageName.c_str(); 1143 } 1144 1145 InputInfo II; 1146 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1147 /*BoundArch*/0, 1148 /*AtTopLevel*/ true, 1149 /*LinkingOutput*/ LinkingOutput, 1150 II); 1151 } 1152 1153 // If the user passed -Qunused-arguments or there were errors, don't warn 1154 // about any unused arguments. 1155 if (Diags.hasErrorOccurred() || 1156 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1157 return; 1158 1159 // Claim -### here. 1160 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1161 1162 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 1163 it != ie; ++it) { 1164 Arg *A = *it; 1165 1166 // FIXME: It would be nice to be able to send the argument to the 1167 // Diagnostic, so that extra values, position, and so on could be printed. 1168 if (!A->isClaimed()) { 1169 if (A->getOption().hasNoArgumentUnused()) 1170 continue; 1171 1172 // Suppress the warning automatically if this is just a flag, and it is an 1173 // instance of an argument we already claimed. 1174 const Option &Opt = A->getOption(); 1175 if (isa<FlagOption>(Opt)) { 1176 bool DuplicateClaimed = false; 1177 1178 for (arg_iterator it = C.getArgs().filtered_begin(&Opt), 1179 ie = C.getArgs().filtered_end(); it != ie; ++it) { 1180 if ((*it)->isClaimed()) { 1181 DuplicateClaimed = true; 1182 break; 1183 } 1184 } 1185 1186 if (DuplicateClaimed) 1187 continue; 1188 } 1189 1190 Diag(clang::diag::warn_drv_unused_argument) 1191 << A->getAsString(C.getArgs()); 1192 } 1193 } 1194} 1195 1196static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC, 1197 const JobAction *JA, 1198 const ActionList *&Inputs) { 1199 const Tool *ToolForJob = 0; 1200 1201 // See if we should look for a compiler with an integrated assembler. We match 1202 // bottom up, so what we are actually looking for is an assembler job with a 1203 // compiler input. 1204 1205 // FIXME: This doesn't belong here, but ideally we will support static soon 1206 // anyway. 1207 bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) || 1208 C.getArgs().hasArg(options::OPT_static) || 1209 C.getArgs().hasArg(options::OPT_fapple_kext)); 1210 bool IsDarwin = TC->getTriple().getOS() == llvm::Triple::Darwin; 1211 bool IsIADefault = TC->IsIntegratedAssemblerDefault() && 1212 !(HasStatic && IsDarwin); 1213 if (C.getArgs().hasFlag(options::OPT_integrated_as, 1214 options::OPT_no_integrated_as, 1215 IsIADefault) && 1216 !C.getArgs().hasArg(options::OPT_save_temps) && 1217 isa<AssembleJobAction>(JA) && 1218 Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { 1219 const Tool &Compiler = TC->SelectTool( 1220 C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs()); 1221 if (Compiler.hasIntegratedAssembler()) { 1222 Inputs = &(*Inputs)[0]->getInputs(); 1223 ToolForJob = &Compiler; 1224 } 1225 } 1226 1227 // Otherwise use the tool for the current job. 1228 if (!ToolForJob) 1229 ToolForJob = &TC->SelectTool(C, *JA, *Inputs); 1230 1231 // See if we should use an integrated preprocessor. We do so when we have 1232 // exactly one input, since this is the only use case we care about 1233 // (irrelevant since we don't support combine yet). 1234 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 1235 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 1236 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 1237 !C.getArgs().hasArg(options::OPT_save_temps) && 1238 ToolForJob->hasIntegratedCPP()) 1239 Inputs = &(*Inputs)[0]->getInputs(); 1240 1241 return *ToolForJob; 1242} 1243 1244void Driver::BuildJobsForAction(Compilation &C, 1245 const Action *A, 1246 const ToolChain *TC, 1247 const char *BoundArch, 1248 bool AtTopLevel, 1249 const char *LinkingOutput, 1250 InputInfo &Result) const { 1251 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1252 1253 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 1254 // FIXME: It would be nice to not claim this here; maybe the old scheme of 1255 // just using Args was better? 1256 const Arg &Input = IA->getInputArg(); 1257 Input.claim(); 1258 if (Input.getOption().matches(options::OPT_INPUT)) { 1259 const char *Name = Input.getValue(C.getArgs()); 1260 Result = InputInfo(Name, A->getType(), Name); 1261 } else 1262 Result = InputInfo(&Input, A->getType(), ""); 1263 return; 1264 } 1265 1266 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 1267 const ToolChain *TC = &C.getDefaultToolChain(); 1268 1269 std::string Arch; 1270 if (BAA->getArchName()) 1271 TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName()); 1272 1273 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), 1274 AtTopLevel, LinkingOutput, Result); 1275 return; 1276 } 1277 1278 const ActionList *Inputs = &A->getInputs(); 1279 1280 const JobAction *JA = cast<JobAction>(A); 1281 const Tool &T = SelectToolForJob(C, TC, JA, Inputs); 1282 1283 // Only use pipes when there is exactly one input. 1284 InputInfoList InputInfos; 1285 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 1286 it != ie; ++it) { 1287 // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get 1288 // temporary output names. 1289 // 1290 // FIXME: Clean this up. 1291 bool SubJobAtTopLevel = false; 1292 if (AtTopLevel && isa<DsymutilJobAction>(A)) 1293 SubJobAtTopLevel = true; 1294 1295 // Also treat verify sub-jobs as being at the top-level. They don't 1296 // produce any output and so don't need temporary output names. 1297 if (AtTopLevel && isa<VerifyJobAction>(A)) 1298 SubJobAtTopLevel = true; 1299 1300 InputInfo II; 1301 BuildJobsForAction(C, *it, TC, BoundArch, 1302 SubJobAtTopLevel, LinkingOutput, II); 1303 InputInfos.push_back(II); 1304 } 1305 1306 // Always use the first input as the base input. 1307 const char *BaseInput = InputInfos[0].getBaseInput(); 1308 1309 // ... except dsymutil actions, which use their actual input as the base 1310 // input. 1311 if (JA->getType() == types::TY_dSYM) 1312 BaseInput = InputInfos[0].getFilename(); 1313 1314 // Determine the place to write output to, if any. 1315 if (JA->getType() == types::TY_Nothing) { 1316 Result = InputInfo(A->getType(), BaseInput); 1317 } else { 1318 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 1319 A->getType(), BaseInput); 1320 } 1321 1322 if (CCCPrintBindings && !CCGenDiagnostics) { 1323 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' 1324 << " - \"" << T.getName() << "\", inputs: ["; 1325 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 1326 llvm::errs() << InputInfos[i].getAsString(); 1327 if (i + 1 != e) 1328 llvm::errs() << ", "; 1329 } 1330 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 1331 } else { 1332 T.ConstructJob(C, *JA, Result, InputInfos, 1333 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 1334 } 1335} 1336 1337const char *Driver::GetNamedOutputPath(Compilation &C, 1338 const JobAction &JA, 1339 const char *BaseInput, 1340 bool AtTopLevel) const { 1341 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 1342 // Output to a user requested destination? 1343 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && 1344 !isa<VerifyJobAction>(JA)) { 1345 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 1346 return C.addResultFile(FinalOutput->getValue(C.getArgs())); 1347 } 1348 1349 // Default to writing to stdout? 1350 if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics) 1351 return "-"; 1352 1353 // Output to a temporary file? 1354 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) || 1355 CCGenDiagnostics) { 1356 StringRef Name = llvm::sys::path::filename(BaseInput); 1357 std::pair<StringRef, StringRef> Split = Name.split('.'); 1358 std::string TmpName = 1359 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1360 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1361 } 1362 1363 llvm::SmallString<128> BasePath(BaseInput); 1364 StringRef BaseName; 1365 1366 // Dsymutil actions should use the full path. 1367 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 1368 BaseName = BasePath; 1369 else 1370 BaseName = llvm::sys::path::filename(BasePath); 1371 1372 // Determine what the derived output name should be. 1373 const char *NamedOutput; 1374 if (JA.getType() == types::TY_Image) { 1375 NamedOutput = DefaultImageName.c_str(); 1376 } else { 1377 const char *Suffix = types::getTypeTempSuffix(JA.getType()); 1378 assert(Suffix && "All types used for output should have a suffix."); 1379 1380 std::string::size_type End = std::string::npos; 1381 if (!types::appendSuffixForType(JA.getType())) 1382 End = BaseName.rfind('.'); 1383 std::string Suffixed(BaseName.substr(0, End)); 1384 Suffixed += '.'; 1385 Suffixed += Suffix; 1386 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 1387 } 1388 1389 // If we're saving temps and the temp filename conflicts with the input 1390 // filename, then avoid overwriting input file. 1391 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && 1392 NamedOutput == BaseName) { 1393 StringRef Name = llvm::sys::path::filename(BaseInput); 1394 std::pair<StringRef, StringRef> Split = Name.split('.'); 1395 std::string TmpName = 1396 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1397 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1398 } 1399 1400 // As an annoying special case, PCH generation doesn't strip the pathname. 1401 if (JA.getType() == types::TY_PCH) { 1402 llvm::sys::path::remove_filename(BasePath); 1403 if (BasePath.empty()) 1404 BasePath = NamedOutput; 1405 else 1406 llvm::sys::path::append(BasePath, NamedOutput); 1407 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); 1408 } else { 1409 return C.addResultFile(NamedOutput); 1410 } 1411} 1412 1413std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 1414 // Respect a limited subset of the '-Bprefix' functionality in GCC by 1415 // attempting to use this prefix when lokup up program paths. 1416 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1417 ie = PrefixDirs.end(); it != ie; ++it) { 1418 std::string Dir(*it); 1419 if (Dir.empty()) 1420 continue; 1421 if (Dir[0] == '=') 1422 Dir = SysRoot + Dir.substr(1); 1423 llvm::sys::Path P(Dir); 1424 P.appendComponent(Name); 1425 bool Exists; 1426 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1427 return P.str(); 1428 } 1429 1430 llvm::sys::Path P(ResourceDir); 1431 P.appendComponent(Name); 1432 bool Exists; 1433 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1434 return P.str(); 1435 1436 const ToolChain::path_list &List = TC.getFilePaths(); 1437 for (ToolChain::path_list::const_iterator 1438 it = List.begin(), ie = List.end(); it != ie; ++it) { 1439 std::string Dir(*it); 1440 if (Dir.empty()) 1441 continue; 1442 if (Dir[0] == '=') 1443 Dir = SysRoot + Dir.substr(1); 1444 llvm::sys::Path P(Dir); 1445 P.appendComponent(Name); 1446 bool Exists; 1447 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1448 return P.str(); 1449 } 1450 1451 return Name; 1452} 1453 1454std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC, 1455 bool WantFile) const { 1456 // Respect a limited subset of the '-Bprefix' functionality in GCC by 1457 // attempting to use this prefix when lokup up program paths. 1458 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1459 ie = PrefixDirs.end(); it != ie; ++it) { 1460 llvm::sys::Path P(*it); 1461 P.appendComponent(Name); 1462 bool Exists; 1463 if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists 1464 : P.canExecute()) 1465 return P.str(); 1466 } 1467 1468 const ToolChain::path_list &List = TC.getProgramPaths(); 1469 for (ToolChain::path_list::const_iterator 1470 it = List.begin(), ie = List.end(); it != ie; ++it) { 1471 llvm::sys::Path P(*it); 1472 P.appendComponent(Name); 1473 bool Exists; 1474 if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists 1475 : P.canExecute()) 1476 return P.str(); 1477 } 1478 1479 // If all else failed, search the path. 1480 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name)); 1481 if (!P.empty()) 1482 return P.str(); 1483 1484 return Name; 1485} 1486 1487std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) 1488 const { 1489 // FIXME: This is lame; sys::Path should provide this function (in particular, 1490 // it should know how to find the temporary files dir). 1491 std::string Error; 1492 const char *TmpDir = ::getenv("TMPDIR"); 1493 if (!TmpDir) 1494 TmpDir = ::getenv("TEMP"); 1495 if (!TmpDir) 1496 TmpDir = ::getenv("TMP"); 1497 if (!TmpDir) 1498 TmpDir = "/tmp"; 1499 llvm::sys::Path P(TmpDir); 1500 P.appendComponent(Prefix); 1501 if (P.makeUnique(false, &Error)) { 1502 Diag(clang::diag::err_drv_unable_to_make_temp) << Error; 1503 return ""; 1504 } 1505 1506 // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. 1507 P.eraseFromDisk(false, 0); 1508 1509 P.appendSuffix(Suffix); 1510 return P.str(); 1511} 1512 1513const HostInfo *Driver::GetHostInfo(const char *TripleStr) const { 1514 llvm::PrettyStackTraceString CrashInfo("Constructing host"); 1515 llvm::Triple Triple(llvm::Triple::normalize(TripleStr).c_str()); 1516 1517 // TCE is an osless target 1518 if (Triple.getArchName() == "tce") 1519 return createTCEHostInfo(*this, Triple); 1520 1521 switch (Triple.getOS()) { 1522 case llvm::Triple::AuroraUX: 1523 return createAuroraUXHostInfo(*this, Triple); 1524 case llvm::Triple::Darwin: 1525 return createDarwinHostInfo(*this, Triple); 1526 case llvm::Triple::DragonFly: 1527 return createDragonFlyHostInfo(*this, Triple); 1528 case llvm::Triple::OpenBSD: 1529 return createOpenBSDHostInfo(*this, Triple); 1530 case llvm::Triple::NetBSD: 1531 return createNetBSDHostInfo(*this, Triple); 1532 case llvm::Triple::FreeBSD: 1533 return createFreeBSDHostInfo(*this, Triple); 1534 case llvm::Triple::Minix: 1535 return createMinixHostInfo(*this, Triple); 1536 case llvm::Triple::Linux: 1537 return createLinuxHostInfo(*this, Triple); 1538 case llvm::Triple::Win32: 1539 return createWindowsHostInfo(*this, Triple); 1540 case llvm::Triple::MinGW32: 1541 return createMinGWHostInfo(*this, Triple); 1542 default: 1543 return createUnknownHostInfo(*this, Triple); 1544 } 1545} 1546 1547bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, 1548 const llvm::Triple &Triple) const { 1549 // Check if user requested no clang, or clang doesn't understand this type (we 1550 // only handle single inputs for now). 1551 if (!CCCUseClang || JA.size() != 1 || 1552 !types::isAcceptedByClang((*JA.begin())->getType())) 1553 return false; 1554 1555 // Otherwise make sure this is an action clang understands. 1556 if (isa<PreprocessJobAction>(JA)) { 1557 if (!CCCUseClangCPP) { 1558 Diag(clang::diag::warn_drv_not_using_clang_cpp); 1559 return false; 1560 } 1561 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) 1562 return false; 1563 1564 // Use clang for C++? 1565 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { 1566 Diag(clang::diag::warn_drv_not_using_clang_cxx); 1567 return false; 1568 } 1569 1570 // Always use clang for precompiling, AST generation, and rewriting, 1571 // regardless of archs. 1572 if (isa<PrecompileJobAction>(JA) || 1573 types::isOnlyAcceptedByClang(JA.getType())) 1574 return true; 1575 1576 // Finally, don't use clang if this isn't one of the user specified archs to 1577 // build. 1578 if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) { 1579 Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName(); 1580 return false; 1581 } 1582 1583 return true; 1584} 1585 1586/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 1587/// grouped values as integers. Numbers which are not provided are set to 0. 1588/// 1589/// \return True if the entire string was parsed (9.2), or all groups were 1590/// parsed (10.3.5extrastuff). 1591bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 1592 unsigned &Minor, unsigned &Micro, 1593 bool &HadExtra) { 1594 HadExtra = false; 1595 1596 Major = Minor = Micro = 0; 1597 if (*Str == '\0') 1598 return true; 1599 1600 char *End; 1601 Major = (unsigned) strtol(Str, &End, 10); 1602 if (*Str != '\0' && *End == '\0') 1603 return true; 1604 if (*End != '.') 1605 return false; 1606 1607 Str = End+1; 1608 Minor = (unsigned) strtol(Str, &End, 10); 1609 if (*Str != '\0' && *End == '\0') 1610 return true; 1611 if (*End != '.') 1612 return false; 1613 1614 Str = End+1; 1615 Micro = (unsigned) strtol(Str, &End, 10); 1616 if (*Str != '\0' && *End == '\0') 1617 return true; 1618 if (Str == End) 1619 return false; 1620 HadExtra = true; 1621 return true; 1622} 1623