Driver.cpp revision 249423
1218893Sdim//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed 10193326Sed#include "clang/Driver/Driver.h" 11249423Sdim#include "InputInfo.h" 12249423Sdim#include "ToolChains.h" 13249423Sdim#include "clang/Basic/Version.h" 14193326Sed#include "clang/Driver/Action.h" 15193326Sed#include "clang/Driver/Arg.h" 16193326Sed#include "clang/Driver/ArgList.h" 17193326Sed#include "clang/Driver/Compilation.h" 18193326Sed#include "clang/Driver/DriverDiagnostic.h" 19193326Sed#include "clang/Driver/Job.h" 20199512Srdivacky#include "clang/Driver/OptTable.h" 21193326Sed#include "clang/Driver/Option.h" 22193326Sed#include "clang/Driver/Options.h" 23193326Sed#include "clang/Driver/Tool.h" 24193326Sed#include "clang/Driver/ToolChain.h" 25221345Sdim#include "llvm/ADT/ArrayRef.h" 26249423Sdim#include "llvm/ADT/OwningPtr.h" 27193326Sed#include "llvm/ADT/StringSet.h" 28249423Sdim#include "llvm/Support/Debug.h" 29226633Sdim#include "llvm/Support/ErrorHandling.h" 30218893Sdim#include "llvm/Support/FileSystem.h" 31218893Sdim#include "llvm/Support/Path.h" 32249423Sdim#include "llvm/Support/PrettyStackTrace.h" 33218893Sdim#include "llvm/Support/Program.h" 34249423Sdim#include "llvm/Support/raw_ostream.h" 35193326Sed#include <map> 36193326Sed 37249423Sdim// FIXME: It would prevent us from including llvm-config.h 38249423Sdim// if config.h were included before system_error.h. 39234353Sdim#include "clang/Config/config.h" 40234353Sdim 41193326Sedusing namespace clang::driver; 42193326Sedusing namespace clang; 43193326Sed 44226633SdimDriver::Driver(StringRef ClangExecutable, 45234353Sdim StringRef DefaultTargetTriple, 46226633Sdim StringRef DefaultImageName, 47226633Sdim DiagnosticsEngine &Diags) 48223017Sdim : Opts(createDriverOptTable()), Diags(Diags), 49234982Sdim ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), 50234982Sdim UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple), 51234353Sdim DefaultImageName(DefaultImageName), 52243830Sdim DriverTitle("clang LLVM compiler"), 53221345Sdim CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), 54221345Sdim CCLogDiagnosticsFilename(0), CCCIsCXX(false), 55221345Sdim CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false), 56221345Sdim CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), 57226633Sdim CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 58243830Sdim CCCUsePCH(true), SuppressMissingInputWarning(false) { 59202879Srdivacky 60218893Sdim Name = llvm::sys::path::stem(ClangExecutable); 61218893Sdim Dir = llvm::sys::path::parent_path(ClangExecutable); 62212904Sdim 63202879Srdivacky // Compute the path to the resource directory. 64226633Sdim StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 65234353Sdim SmallString<128> P(Dir); 66218893Sdim if (ClangResourceDir != "") 67218893Sdim llvm::sys::path::append(P, ClangResourceDir); 68218893Sdim else 69218893Sdim llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); 70202879Srdivacky ResourceDir = P.str(); 71193326Sed} 72193326Sed 73193326SedDriver::~Driver() { 74193326Sed delete Opts; 75234353Sdim 76234353Sdim for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(), 77234353Sdim E = ToolChains.end(); 78234353Sdim I != E; ++I) 79234353Sdim delete I->second; 80193326Sed} 81193326Sed 82226633SdimInputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) { 83193326Sed llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 84199512Srdivacky unsigned MissingArgIndex, MissingArgCount; 85221345Sdim InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(), 86199512Srdivacky MissingArgIndex, MissingArgCount); 87198092Srdivacky 88199512Srdivacky // Check for missing argument error. 89199512Srdivacky if (MissingArgCount) 90199512Srdivacky Diag(clang::diag::err_drv_missing_argument) 91199512Srdivacky << Args->getArgString(MissingArgIndex) << MissingArgCount; 92193326Sed 93199512Srdivacky // Check for unsupported options. 94199512Srdivacky for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 95199512Srdivacky it != ie; ++it) { 96199512Srdivacky Arg *A = *it; 97243830Sdim if (A->getOption().hasFlag(options::Unsupported)) { 98193326Sed Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 99193326Sed continue; 100193326Sed } 101234353Sdim 102234353Sdim // Warn about -mcpu= without an argument. 103239462Sdim if (A->getOption().matches(options::OPT_mcpu_EQ) && 104234353Sdim A->containsValue("")) { 105239462Sdim Diag(clang::diag::warn_drv_empty_joined_argument) << 106239462Sdim A->getAsString(*Args); 107234353Sdim } 108193326Sed } 109193326Sed 110193326Sed return Args; 111193326Sed} 112193326Sed 113226633Sdim// Determine which compilation mode we are in. We look for options which 114226633Sdim// affect the phase, starting with the earliest phases, and record which 115226633Sdim// option we used to determine the final phase. 116226633Sdimphases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) 117226633Sdimconst { 118226633Sdim Arg *PhaseArg = 0; 119226633Sdim phases::ID FinalPhase; 120226633Sdim 121226633Sdim // -{E,M,MM} only run the preprocessor. 122226633Sdim if (CCCIsCPP || 123226633Sdim (PhaseArg = DAL.getLastArg(options::OPT_E)) || 124226633Sdim (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) { 125226633Sdim FinalPhase = phases::Preprocess; 126226633Sdim 127226633Sdim // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. 128226633Sdim } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 129249423Sdim (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 130226633Sdim (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 131234353Sdim (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 132234353Sdim (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 133226633Sdim (PhaseArg = DAL.getLastArg(options::OPT__analyze, 134234353Sdim options::OPT__analyze_auto)) || 135226633Sdim (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || 136226633Sdim (PhaseArg = DAL.getLastArg(options::OPT_S))) { 137226633Sdim FinalPhase = phases::Compile; 138226633Sdim 139226633Sdim // -c only runs up to the assembler. 140226633Sdim } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 141226633Sdim FinalPhase = phases::Assemble; 142226633Sdim 143226633Sdim // Otherwise do everything. 144226633Sdim } else 145226633Sdim FinalPhase = phases::Link; 146226633Sdim 147226633Sdim if (FinalPhaseArg) 148226633Sdim *FinalPhaseArg = PhaseArg; 149226633Sdim 150226633Sdim return FinalPhase; 151226633Sdim} 152226633Sdim 153210299SedDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 154210299Sed DerivedArgList *DAL = new DerivedArgList(Args); 155210299Sed 156218893Sdim bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 157210299Sed for (ArgList::const_iterator it = Args.begin(), 158210299Sed ie = Args.end(); it != ie; ++it) { 159210299Sed const Arg *A = *it; 160210299Sed 161210299Sed // Unfortunately, we have to parse some forwarding options (-Xassembler, 162210299Sed // -Xlinker, -Xpreprocessor) because we either integrate their functionality 163210299Sed // (assembler and preprocessor), or bypass a previous driver ('collect2'). 164210299Sed 165210299Sed // Rewrite linker options, to replace --no-demangle with a custom internal 166210299Sed // option. 167210299Sed if ((A->getOption().matches(options::OPT_Wl_COMMA) || 168210299Sed A->getOption().matches(options::OPT_Xlinker)) && 169210299Sed A->containsValue("--no-demangle")) { 170210299Sed // Add the rewritten no-demangle argument. 171210299Sed DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 172210299Sed 173210299Sed // Add the remaining values as Xlinker arguments. 174210299Sed for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 175243830Sdim if (StringRef(A->getValue(i)) != "--no-demangle") 176210299Sed DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), 177243830Sdim A->getValue(i)); 178210299Sed 179210299Sed continue; 180210299Sed } 181210299Sed 182210299Sed // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 183210299Sed // some build systems. We don't try to be complete here because we don't 184210299Sed // care to encourage this usage model. 185210299Sed if (A->getOption().matches(options::OPT_Wp_COMMA) && 186243830Sdim (A->getValue(0) == StringRef("-MD") || 187243830Sdim A->getValue(0) == StringRef("-MMD"))) { 188210299Sed // Rewrite to -MD/-MMD along with -MF. 189243830Sdim if (A->getValue(0) == StringRef("-MD")) 190210299Sed DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 191210299Sed else 192210299Sed DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 193243830Sdim if (A->getNumValues() == 2) 194243830Sdim DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 195243830Sdim A->getValue(1)); 196210299Sed continue; 197210299Sed } 198210299Sed 199218893Sdim // Rewrite reserved library names. 200218893Sdim if (A->getOption().matches(options::OPT_l)) { 201243830Sdim StringRef Value = A->getValue(); 202218893Sdim 203218893Sdim // Rewrite unless -nostdlib is present. 204218893Sdim if (!HasNostdlib && Value == "stdc++") { 205218893Sdim DAL->AddFlagArg(A, Opts->getOption( 206218893Sdim options::OPT_Z_reserved_lib_stdcxx)); 207218893Sdim continue; 208218893Sdim } 209218893Sdim 210218893Sdim // Rewrite unconditionally. 211218893Sdim if (Value == "cc_kext") { 212218893Sdim DAL->AddFlagArg(A, Opts->getOption( 213218893Sdim options::OPT_Z_reserved_lib_cckext)); 214218893Sdim continue; 215218893Sdim } 216218893Sdim } 217218893Sdim 218210299Sed DAL->append(*it); 219210299Sed } 220210299Sed 221212904Sdim // Add a default value of -mlinker-version=, if one was given and the user 222212904Sdim // didn't specify one. 223212904Sdim#if defined(HOST_LINK_VERSION) 224212904Sdim if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { 225212904Sdim DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 226212904Sdim HOST_LINK_VERSION); 227212904Sdim DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 228212904Sdim } 229212904Sdim#endif 230212904Sdim 231210299Sed return DAL; 232210299Sed} 233210299Sed 234226633SdimCompilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 235193326Sed llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 236193326Sed 237226633Sdim // FIXME: Handle environment options which affect driver behavior, somewhere 238234353Sdim // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 239193326Sed 240226633Sdim if (char *env = ::getenv("COMPILER_PATH")) { 241226633Sdim StringRef CompilerPath = env; 242226633Sdim while (!CompilerPath.empty()) { 243249423Sdim std::pair<StringRef, StringRef> Split 244249423Sdim = CompilerPath.split(llvm::sys::PathSeparator); 245226633Sdim PrefixDirs.push_back(Split.first); 246226633Sdim CompilerPath = Split.second; 247226633Sdim } 248226633Sdim } 249226633Sdim 250193326Sed // FIXME: What are we going to do with -V and -b? 251193326Sed 252198092Srdivacky // FIXME: This stuff needs to go into the Compilation, not the driver. 253249423Sdim bool CCCPrintOptions, CCCPrintActions; 254193326Sed 255221345Sdim InputArgList *Args = ParseArgStrings(ArgList.slice(1)); 256193326Sed 257200583Srdivacky // -no-canonical-prefixes is used very early in main. 258200583Srdivacky Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); 259200583Srdivacky 260212904Sdim // Ignore -pipe. 261212904Sdim Args->ClaimAllArgs(options::OPT_pipe); 262212904Sdim 263200583Srdivacky // Extract -ccc args. 264193326Sed // 265198092Srdivacky // FIXME: We need to figure out where this behavior should live. Most of it 266198092Srdivacky // should be outside in the client; the parts that aren't should have proper 267198092Srdivacky // options, either by introducing new ones or by overloading gcc ones like -V 268198092Srdivacky // or -b. 269200583Srdivacky CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options); 270200583Srdivacky CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); 271200583Srdivacky CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); 272200583Srdivacky CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX; 273200583Srdivacky CCCEcho = Args->hasArg(options::OPT_ccc_echo); 274200583Srdivacky if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) 275243830Sdim CCCGenericGCCName = A->getValue(); 276200583Srdivacky CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, 277200583Srdivacky options::OPT_ccc_pch_is_pth); 278234353Sdim // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 279234353Sdim // and getToolChain is const. 280234353Sdim if (const Arg *A = Args->getLastArg(options::OPT_target)) 281243830Sdim DefaultTargetTriple = A->getValue(); 282200583Srdivacky if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) 283243830Sdim Dir = InstalledDir = A->getValue(); 284218893Sdim for (arg_iterator it = Args->filtered_begin(options::OPT_B), 285218893Sdim ie = Args->filtered_end(); it != ie; ++it) { 286218893Sdim const Arg *A = *it; 287218893Sdim A->claim(); 288243830Sdim PrefixDirs.push_back(A->getValue(0)); 289218893Sdim } 290221345Sdim if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) 291243830Sdim SysRoot = A->getValue(); 292221345Sdim if (Args->hasArg(options::OPT_nostdlib)) 293221345Sdim UseStdLib = false; 294193326Sed 295249423Sdim if (const Arg *A = Args->getLastArg(options::OPT_resource_dir)) 296249423Sdim ResourceDir = A->getValue(); 297249423Sdim 298210299Sed // Perform the default argument translations. 299210299Sed DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); 300210299Sed 301234353Sdim // Owned by the host. 302234353Sdim const ToolChain &TC = getToolChain(*Args); 303234353Sdim 304193326Sed // The compilation takes ownership of Args. 305234353Sdim Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs); 306193326Sed 307193326Sed // FIXME: This behavior shouldn't be here. 308193326Sed if (CCCPrintOptions) { 309210299Sed PrintOptions(C->getInputArgs()); 310193326Sed return C; 311193326Sed } 312193326Sed 313193326Sed if (!HandleImmediateArgs(*C)) 314193326Sed return C; 315193326Sed 316226633Sdim // Construct the list of inputs. 317226633Sdim InputList Inputs; 318226633Sdim BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs); 319226633Sdim 320234353Sdim // Construct the list of abstract actions to perform for this compilation. On 321234353Sdim // Darwin target OSes this uses the driver-driver and universal actions. 322234353Sdim if (TC.getTriple().isOSDarwin()) 323212904Sdim BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), 324226633Sdim Inputs, C->getActions()); 325193326Sed else 326226633Sdim BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, 327226633Sdim C->getActions()); 328193326Sed 329193326Sed if (CCCPrintActions) { 330193326Sed PrintActions(*C); 331193326Sed return C; 332193326Sed } 333193326Sed 334193326Sed BuildJobs(*C); 335193326Sed 336193326Sed return C; 337193326Sed} 338193326Sed 339226633Sdim// When clang crashes, produce diagnostic information including the fully 340226633Sdim// preprocessed source file(s). Request that the developer attach the 341226633Sdim// diagnostic information to a bug report. 342226633Sdimvoid Driver::generateCompilationDiagnostics(Compilation &C, 343226633Sdim const Command *FailingCommand) { 344234353Sdim if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 345239462Sdim return; 346234353Sdim 347249423Sdim // Don't try to generate diagnostics for link or dsymutil jobs. 348249423Sdim if (FailingCommand && (FailingCommand->getCreator().isLinkJob() || 349249423Sdim FailingCommand->getCreator().isDsymutilJob())) 350234353Sdim return; 351234353Sdim 352239462Sdim // Print the version of the compiler. 353239462Sdim PrintVersion(C, llvm::errs()); 354239462Sdim 355226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 356239462Sdim << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 357239462Sdim "crash backtrace, preprocessed source, and associated run script."; 358226633Sdim 359226633Sdim // Suppress driver output and emit preprocessor output to temp file. 360226633Sdim CCCIsCPP = true; 361226633Sdim CCGenDiagnostics = true; 362239462Sdim C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes)); 363226633Sdim 364234353Sdim // Save the original job command(s). 365234353Sdim std::string Cmd; 366234353Sdim llvm::raw_string_ostream OS(Cmd); 367239462Sdim if (FailingCommand) 368243830Sdim C.PrintDiagnosticJob(OS, *FailingCommand); 369239462Sdim else 370239462Sdim // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an 371239462Sdim // associated FailingCommand, so just pass all jobs. 372243830Sdim C.PrintDiagnosticJob(OS, C.getJobs()); 373234353Sdim OS.flush(); 374234353Sdim 375249423Sdim // Keep track of whether we produce any errors while trying to produce 376249423Sdim // preprocessed sources. 377249423Sdim DiagnosticErrorTrap Trap(Diags); 378249423Sdim 379249423Sdim // Suppress tool output. 380226633Sdim C.initCompilationForDiagnostics(); 381226633Sdim 382226633Sdim // Construct the list of inputs. 383226633Sdim InputList Inputs; 384226633Sdim BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 385226633Sdim 386226633Sdim for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 387226633Sdim bool IgnoreInput = false; 388226633Sdim 389226633Sdim // Ignore input from stdin or any inputs that cannot be preprocessed. 390243830Sdim if (!strcmp(it->second->getValue(), "-")) { 391226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 392226633Sdim << "Error generating preprocessed source(s) - ignoring input from stdin" 393226633Sdim "."; 394226633Sdim IgnoreInput = true; 395226633Sdim } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 396226633Sdim IgnoreInput = true; 397226633Sdim } 398226633Sdim 399226633Sdim if (IgnoreInput) { 400226633Sdim it = Inputs.erase(it); 401226633Sdim ie = Inputs.end(); 402226633Sdim } else { 403226633Sdim ++it; 404226633Sdim } 405226633Sdim } 406226633Sdim 407249423Sdim if (Inputs.empty()) { 408249423Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 409249423Sdim << "Error generating preprocessed source(s) - no preprocessable inputs."; 410249423Sdim return; 411249423Sdim } 412249423Sdim 413226633Sdim // Don't attempt to generate preprocessed files if multiple -arch options are 414234353Sdim // used, unless they're all duplicates. 415234353Sdim llvm::StringSet<> ArchNames; 416226633Sdim for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 417226633Sdim it != ie; ++it) { 418226633Sdim Arg *A = *it; 419226633Sdim if (A->getOption().matches(options::OPT_arch)) { 420243830Sdim StringRef ArchName = A->getValue(); 421234353Sdim ArchNames.insert(ArchName); 422226633Sdim } 423226633Sdim } 424234353Sdim if (ArchNames.size() > 1) { 425234353Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 426234353Sdim << "Error generating preprocessed source(s) - cannot generate " 427234353Sdim "preprocessed source with multiple -arch options."; 428234353Sdim return; 429234353Sdim } 430226633Sdim 431234353Sdim // Construct the list of abstract actions to perform for this compilation. On 432234353Sdim // Darwin OSes this uses the driver-driver and builds universal actions. 433234353Sdim const ToolChain &TC = C.getDefaultToolChain(); 434234353Sdim if (TC.getTriple().isOSDarwin()) 435234353Sdim BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions()); 436226633Sdim else 437234353Sdim BuildActions(TC, C.getArgs(), Inputs, C.getActions()); 438226633Sdim 439226633Sdim BuildJobs(C); 440226633Sdim 441226633Sdim // If there were errors building the compilation, quit now. 442249423Sdim if (Trap.hasErrorOccurred()) { 443226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 444226633Sdim << "Error generating preprocessed source(s)."; 445226633Sdim return; 446226633Sdim } 447226633Sdim 448226633Sdim // Generate preprocessed output. 449249423Sdim SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 450249423Sdim C.ExecuteJob(C.getJobs(), FailingCommands); 451226633Sdim 452226633Sdim // If the command succeeded, we are done. 453249423Sdim if (FailingCommands.empty()) { 454226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 455239462Sdim << "\n********************\n\n" 456239462Sdim "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 457239462Sdim "Preprocessed source(s) and associated run script(s) are located at:"; 458226633Sdim ArgStringList Files = C.getTempFiles(); 459226633Sdim for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); 460234353Sdim it != ie; ++it) { 461226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) << *it; 462234353Sdim 463234353Sdim std::string Err; 464234353Sdim std::string Script = StringRef(*it).rsplit('.').first; 465234353Sdim Script += ".sh"; 466234353Sdim llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err, 467234353Sdim llvm::raw_fd_ostream::F_Excl | 468234353Sdim llvm::raw_fd_ostream::F_Binary); 469234353Sdim if (!Err.empty()) { 470234353Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 471234353Sdim << "Error generating run script: " + Script + " " + Err; 472234353Sdim } else { 473239462Sdim // Append the new filename with correct preprocessed suffix. 474239462Sdim size_t I, E; 475239462Sdim I = Cmd.find("-main-file-name "); 476239462Sdim assert (I != std::string::npos && "Expected to find -main-file-name"); 477239462Sdim I += 16; 478239462Sdim E = Cmd.find(" ", I); 479239462Sdim assert (E != std::string::npos && "-main-file-name missing argument?"); 480239462Sdim StringRef OldFilename = StringRef(Cmd).slice(I, E); 481239462Sdim StringRef NewFilename = llvm::sys::path::filename(*it); 482239462Sdim I = StringRef(Cmd).rfind(OldFilename); 483239462Sdim E = I + OldFilename.size(); 484239462Sdim I = Cmd.rfind(" ", I) + 1; 485239462Sdim Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size()); 486234353Sdim ScriptOS << Cmd; 487234353Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 488234353Sdim } 489234353Sdim } 490239462Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 491239462Sdim << "\n\n********************"; 492226633Sdim } else { 493226633Sdim // Failure, remove preprocessed files. 494249423Sdim if (!C.getArgs().hasArg(options::OPT_save_temps)) { 495226633Sdim C.CleanupFileList(C.getTempFiles(), true); 496249423Sdim } 497226633Sdim 498226633Sdim Diag(clang::diag::note_drv_command_failed_diag_msg) 499226633Sdim << "Error generating preprocessed source(s)."; 500226633Sdim } 501226633Sdim} 502226633Sdim 503226633Sdimint Driver::ExecuteCompilation(const Compilation &C, 504249423Sdim SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) const { 505195341Sed // Just print if -### was present. 506195341Sed if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 507195341Sed C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); 508195341Sed return 0; 509195341Sed } 510195341Sed 511195341Sed // If there were errors building the compilation, quit now. 512226633Sdim if (Diags.hasErrorOccurred()) 513195341Sed return 1; 514195341Sed 515249423Sdim C.ExecuteJob(C.getJobs(), FailingCommands); 516198092Srdivacky 517195341Sed // Remove temp files. 518195341Sed C.CleanupFileList(C.getTempFiles()); 519195341Sed 520208600Srdivacky // If the command succeeded, we are done. 521249423Sdim if (FailingCommands.empty()) 522249423Sdim return 0; 523208600Srdivacky 524249423Sdim // Otherwise, remove result files and print extra information about abnormal 525249423Sdim // failures. 526249423Sdim for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it = 527249423Sdim FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) { 528249423Sdim int Res = it->first; 529249423Sdim const Command *FailingCommand = it->second; 530195341Sed 531249423Sdim // Remove result files if we're not saving temps. 532249423Sdim if (!C.getArgs().hasArg(options::OPT_save_temps)) { 533249423Sdim const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 534249423Sdim C.CleanupFileMap(C.getResultFiles(), JA, true); 535234353Sdim 536249423Sdim // Failure result files are valid unless we crashed. 537249423Sdim if (Res < 0) 538249423Sdim C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 539249423Sdim } 540195341Sed 541249423Sdim // Print extra information about abnormal failures, if possible. 542249423Sdim // 543249423Sdim // This is ad-hoc, but we don't want to be excessively noisy. If the result 544249423Sdim // status was 1, assume the command failed normally. In particular, if it 545249423Sdim // was the compiler then assume it gave a reasonable error code. Failures 546249423Sdim // in other tools are less common, and they generally have worse 547249423Sdim // diagnostics, so always print the diagnostic there. 548249423Sdim const Tool &FailingTool = FailingCommand->getCreator(); 549249423Sdim 550249423Sdim if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 551249423Sdim // FIXME: See FIXME above regarding result code interpretation. 552249423Sdim if (Res < 0) 553249423Sdim Diag(clang::diag::err_drv_command_signalled) 554249423Sdim << FailingTool.getShortName(); 555249423Sdim else 556249423Sdim Diag(clang::diag::err_drv_command_failed) 557249423Sdim << FailingTool.getShortName() << Res; 558249423Sdim } 559195341Sed } 560249423Sdim return 0; 561195341Sed} 562195341Sed 563193326Sedvoid Driver::PrintOptions(const ArgList &Args) const { 564193326Sed unsigned i = 0; 565198092Srdivacky for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 566193326Sed it != ie; ++it, ++i) { 567193326Sed Arg *A = *it; 568193326Sed llvm::errs() << "Option " << i << " - " 569243830Sdim << "Name: \"" << A->getOption().getPrefixedName() << "\", " 570193326Sed << "Values: {"; 571193326Sed for (unsigned j = 0; j < A->getNumValues(); ++j) { 572193326Sed if (j) 573193326Sed llvm::errs() << ", "; 574243830Sdim llvm::errs() << '"' << A->getValue(j) << '"'; 575193326Sed } 576193326Sed llvm::errs() << "}\n"; 577193326Sed } 578193326Sed} 579193326Sed 580193326Sedvoid Driver::PrintHelp(bool ShowHidden) const { 581204643Srdivacky getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 582243830Sdim /*Include*/0, 583243830Sdim /*Exclude*/options::NoDriverOption | 584243830Sdim (ShowHidden ? 0 : options::HelpHidden)); 585193326Sed} 586193326Sed 587226633Sdimvoid Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 588198092Srdivacky // FIXME: The following handlers should use a callback mechanism, we don't 589198092Srdivacky // know what the client would like to do. 590202879Srdivacky OS << getClangFullVersion() << '\n'; 591193326Sed const ToolChain &TC = C.getDefaultToolChain(); 592198092Srdivacky OS << "Target: " << TC.getTripleString() << '\n'; 593194613Sed 594194613Sed // Print the threading model. 595194613Sed // 596194613Sed // FIXME: Implement correctly. 597198092Srdivacky OS << "Thread model: " << "posix" << '\n'; 598193326Sed} 599193326Sed 600208600Srdivacky/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 601208600Srdivacky/// option. 602226633Sdimstatic void PrintDiagnosticCategories(raw_ostream &OS) { 603223017Sdim // Skip the empty category. 604223017Sdim for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); 605223017Sdim i != max; ++i) 606223017Sdim OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 607208600Srdivacky} 608208600Srdivacky 609193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) { 610210299Sed // The order these options are handled in gcc is all over the place, but we 611198092Srdivacky // don't expect inconsistencies w.r.t. that to matter in practice. 612193326Sed 613218893Sdim if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 614218893Sdim llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 615218893Sdim return false; 616218893Sdim } 617218893Sdim 618193326Sed if (C.getArgs().hasArg(options::OPT_dumpversion)) { 619218893Sdim // Since -dumpversion is only implemented for pedantic GCC compatibility, we 620218893Sdim // return an answer which matches our definition of __VERSION__. 621218893Sdim // 622218893Sdim // If we want to return a more correct answer some day, then we should 623218893Sdim // introduce a non-pedantically GCC compatible mode to Clang in which we 624218893Sdim // provide sensible definitions for -dumpversion, __VERSION__, etc. 625218893Sdim llvm::outs() << "4.2.1\n"; 626193326Sed return false; 627193326Sed } 628210299Sed 629208600Srdivacky if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 630208600Srdivacky PrintDiagnosticCategories(llvm::outs()); 631208600Srdivacky return false; 632208600Srdivacky } 633193326Sed 634239462Sdim if (C.getArgs().hasArg(options::OPT_help) || 635193326Sed C.getArgs().hasArg(options::OPT__help_hidden)) { 636193326Sed PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 637193326Sed return false; 638193326Sed } 639193326Sed 640193326Sed if (C.getArgs().hasArg(options::OPT__version)) { 641198092Srdivacky // Follow gcc behavior and use stdout for --version and stderr for -v. 642198092Srdivacky PrintVersion(C, llvm::outs()); 643193326Sed return false; 644193326Sed } 645193326Sed 646198092Srdivacky if (C.getArgs().hasArg(options::OPT_v) || 647193326Sed C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 648198092Srdivacky PrintVersion(C, llvm::errs()); 649193326Sed SuppressMissingInputWarning = true; 650193326Sed } 651193326Sed 652193326Sed const ToolChain &TC = C.getDefaultToolChain(); 653193326Sed if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 654193326Sed llvm::outs() << "programs: ="; 655193326Sed for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 656193326Sed ie = TC.getProgramPaths().end(); it != ie; ++it) { 657193326Sed if (it != TC.getProgramPaths().begin()) 658193326Sed llvm::outs() << ':'; 659193326Sed llvm::outs() << *it; 660193326Sed } 661193326Sed llvm::outs() << "\n"; 662226633Sdim llvm::outs() << "libraries: =" << ResourceDir; 663224145Sdim 664234982Sdim StringRef sysroot = C.getSysRoot(); 665224145Sdim 666198092Srdivacky for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 667193326Sed ie = TC.getFilePaths().end(); it != ie; ++it) { 668226633Sdim llvm::outs() << ':'; 669224145Sdim const char *path = it->c_str(); 670224145Sdim if (path[0] == '=') 671224145Sdim llvm::outs() << sysroot << path + 1; 672224145Sdim else 673224145Sdim llvm::outs() << path; 674193326Sed } 675193326Sed llvm::outs() << "\n"; 676193326Sed return false; 677193326Sed } 678193326Sed 679198092Srdivacky // FIXME: The following handlers should use a callback mechanism, we don't 680198092Srdivacky // know what the client would like to do. 681193326Sed if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 682243830Sdim llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 683193326Sed return false; 684193326Sed } 685193326Sed 686193326Sed if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 687243830Sdim llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 688193326Sed return false; 689193326Sed } 690193326Sed 691193326Sed if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 692198092Srdivacky llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 693193326Sed return false; 694193326Sed } 695193326Sed 696194613Sed if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 697194613Sed // FIXME: We need tool chain support for this. 698194613Sed llvm::outs() << ".;\n"; 699194613Sed 700194613Sed switch (C.getDefaultToolChain().getTriple().getArch()) { 701194613Sed default: 702194613Sed break; 703198092Srdivacky 704194613Sed case llvm::Triple::x86_64: 705194613Sed llvm::outs() << "x86_64;@m64" << "\n"; 706194613Sed break; 707194613Sed 708194613Sed case llvm::Triple::ppc64: 709194613Sed llvm::outs() << "ppc64;@m64" << "\n"; 710194613Sed break; 711194613Sed } 712194613Sed return false; 713194613Sed } 714194613Sed 715194613Sed // FIXME: What is the difference between print-multi-directory and 716194613Sed // print-multi-os-directory? 717194613Sed if (C.getArgs().hasArg(options::OPT_print_multi_directory) || 718194613Sed C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 719194613Sed switch (C.getDefaultToolChain().getTriple().getArch()) { 720194613Sed default: 721194613Sed case llvm::Triple::x86: 722194613Sed case llvm::Triple::ppc: 723194613Sed llvm::outs() << "." << "\n"; 724194613Sed break; 725198092Srdivacky 726194613Sed case llvm::Triple::x86_64: 727213492Sdim llvm::outs() << "." << "\n"; 728194613Sed break; 729194613Sed 730194613Sed case llvm::Triple::ppc64: 731194613Sed llvm::outs() << "ppc64" << "\n"; 732194613Sed break; 733194613Sed } 734194613Sed return false; 735194613Sed } 736194613Sed 737193326Sed return true; 738193326Sed} 739193326Sed 740198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A, 741193326Sed std::map<Action*, unsigned> &Ids) { 742193326Sed if (Ids.count(A)) 743193326Sed return Ids[A]; 744198092Srdivacky 745193326Sed std::string str; 746193326Sed llvm::raw_string_ostream os(str); 747198092Srdivacky 748193326Sed os << Action::getClassName(A->getKind()) << ", "; 749198092Srdivacky if (InputAction *IA = dyn_cast<InputAction>(A)) { 750243830Sdim os << "\"" << IA->getInputArg().getValue() << "\""; 751193326Sed } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 752239462Sdim os << '"' << BIA->getArchName() << '"' 753193326Sed << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 754193326Sed } else { 755193326Sed os << "{"; 756193326Sed for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 757193326Sed os << PrintActions1(C, *it, Ids); 758193326Sed ++it; 759193326Sed if (it != ie) 760193326Sed os << ", "; 761193326Sed } 762193326Sed os << "}"; 763193326Sed } 764193326Sed 765193326Sed unsigned Id = Ids.size(); 766193326Sed Ids[A] = Id; 767198092Srdivacky llvm::errs() << Id << ": " << os.str() << ", " 768193326Sed << types::getTypeName(A->getType()) << "\n"; 769193326Sed 770193326Sed return Id; 771193326Sed} 772193326Sed 773193326Sedvoid Driver::PrintActions(const Compilation &C) const { 774193326Sed std::map<Action*, unsigned> Ids; 775198092Srdivacky for (ActionList::const_iterator it = C.getActions().begin(), 776193326Sed ie = C.getActions().end(); it != ie; ++it) 777193326Sed PrintActions1(C, *it, Ids); 778193326Sed} 779193326Sed 780223017Sdim/// \brief Check whether the given input tree contains any compilation or 781223017Sdim/// assembly actions. 782223017Sdimstatic bool ContainsCompileOrAssembleAction(const Action *A) { 783210299Sed if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) 784210299Sed return true; 785210299Sed 786210299Sed for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) 787223017Sdim if (ContainsCompileOrAssembleAction(*it)) 788210299Sed return true; 789210299Sed 790210299Sed return false; 791210299Sed} 792210299Sed 793212904Sdimvoid Driver::BuildUniversalActions(const ToolChain &TC, 794221345Sdim const DerivedArgList &Args, 795226633Sdim const InputList &BAInputs, 796193326Sed ActionList &Actions) const { 797198092Srdivacky llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 798198092Srdivacky // Collect the list of architectures. Duplicates are allowed, but should only 799198092Srdivacky // be handled once (in the order seen). 800193326Sed llvm::StringSet<> ArchNames; 801226633Sdim SmallVector<const char *, 4> Archs; 802198092Srdivacky for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 803193326Sed it != ie; ++it) { 804193326Sed Arg *A = *it; 805193326Sed 806199512Srdivacky if (A->getOption().matches(options::OPT_arch)) { 807198092Srdivacky // Validate the option here; we don't save the type here because its 808198092Srdivacky // particular spelling may participate in other driver choices. 809198092Srdivacky llvm::Triple::ArchType Arch = 810243830Sdim tools::darwin::getArchTypeForDarwinArchName(A->getValue()); 811198092Srdivacky if (Arch == llvm::Triple::UnknownArch) { 812198092Srdivacky Diag(clang::diag::err_drv_invalid_arch_name) 813198092Srdivacky << A->getAsString(Args); 814198092Srdivacky continue; 815198092Srdivacky } 816193326Sed 817193326Sed A->claim(); 818243830Sdim if (ArchNames.insert(A->getValue())) 819243830Sdim Archs.push_back(A->getValue()); 820193326Sed } 821193326Sed } 822193326Sed 823198092Srdivacky // When there is no explicit arch for this platform, make sure we still bind 824198092Srdivacky // the architecture (to the default) so that -Xarch_ is handled correctly. 825193326Sed if (!Archs.size()) 826243830Sdim Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 827193326Sed 828198092Srdivacky // FIXME: We killed off some others but these aren't yet detected in a 829198092Srdivacky // functional manner. If we added information to jobs about which "auxiliary" 830198092Srdivacky // files they wrote then we could detect the conflict these cause downstream. 831193326Sed if (Archs.size() > 1) { 832193326Sed // No recovery needed, the point of this is just to prevent 833193326Sed // overwriting the same files. 834193326Sed if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 835198092Srdivacky Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 836193326Sed << A->getAsString(Args); 837193326Sed } 838193326Sed 839193326Sed ActionList SingleActions; 840226633Sdim BuildActions(TC, Args, BAInputs, SingleActions); 841193326Sed 842210299Sed // Add in arch bindings for every top level action, as well as lipo and 843210299Sed // dsymutil steps if needed. 844193326Sed for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 845193326Sed Action *Act = SingleActions[i]; 846193326Sed 847198092Srdivacky // Make sure we can lipo this kind of output. If not (and it is an actual 848198092Srdivacky // output) then we disallow, since we can't create an output file with the 849198092Srdivacky // right name without overwriting it. We could remove this oddity by just 850198092Srdivacky // changing the output names to include the arch, which would also fix 851193326Sed // -save-temps. Compatibility wins for now. 852193326Sed 853193326Sed if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 854193326Sed Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 855193326Sed << types::getTypeName(Act->getType()); 856193326Sed 857193326Sed ActionList Inputs; 858205219Srdivacky for (unsigned i = 0, e = Archs.size(); i != e; ++i) { 859193326Sed Inputs.push_back(new BindArchAction(Act, Archs[i])); 860205219Srdivacky if (i != 0) 861205219Srdivacky Inputs.back()->setOwnsInputs(false); 862205219Srdivacky } 863193326Sed 864198092Srdivacky // Lipo if necessary, we do it this way because we need to set the arch flag 865198092Srdivacky // so that -Xarch_ gets overwritten. 866193326Sed if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 867193326Sed Actions.append(Inputs.begin(), Inputs.end()); 868193326Sed else 869193326Sed Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 870210299Sed 871234353Sdim // Handle debug info queries. 872234353Sdim Arg *A = Args.getLastArg(options::OPT_g_Group); 873234982Sdim if (A && !A->getOption().matches(options::OPT_g0) && 874234982Sdim !A->getOption().matches(options::OPT_gstabs) && 875234982Sdim ContainsCompileOrAssembleAction(Actions.back())) { 876239462Sdim 877234982Sdim // Add a 'dsymutil' step if necessary, when debug info is enabled and we 878234982Sdim // have a compile input. We need to run 'dsymutil' ourselves in such cases 879249423Sdim // because the debug info will refer to a temporary object file which 880234982Sdim // will be removed at the end of the compilation process. 881234982Sdim if (Act->getType() == types::TY_Image) { 882234982Sdim ActionList Inputs; 883234982Sdim Inputs.push_back(Actions.back()); 884234982Sdim Actions.pop_back(); 885234982Sdim Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); 886234982Sdim } 887210299Sed 888234982Sdim // Verify the output (debug information only) if we passed '-verify'. 889234982Sdim if (Args.hasArg(options::OPT_verify)) { 890234982Sdim ActionList VerifyInputs; 891234982Sdim VerifyInputs.push_back(Actions.back()); 892234982Sdim Actions.pop_back(); 893234982Sdim Actions.push_back(new VerifyJobAction(VerifyInputs, 894234982Sdim types::TY_Nothing)); 895210299Sed } 896234982Sdim } 897193326Sed } 898193326Sed} 899193326Sed 900226633Sdim// Construct a the list of inputs and their types. 901226633Sdimvoid Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 902226633Sdim InputList &Inputs) const { 903198092Srdivacky // Track the current user specified (-x) input. We also explicitly track the 904198092Srdivacky // argument used to set the type; we only want to claim the type when we 905198092Srdivacky // actually use it, so we warn about unused -x arguments. 906193326Sed types::ID InputType = types::TY_Nothing; 907193326Sed Arg *InputTypeArg = 0; 908193326Sed 909198092Srdivacky for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 910193326Sed it != ie; ++it) { 911193326Sed Arg *A = *it; 912193326Sed 913243830Sdim if (A->getOption().getKind() == Option::InputClass) { 914243830Sdim const char *Value = A->getValue(); 915193326Sed types::ID Ty = types::TY_INVALID; 916193326Sed 917193326Sed // Infer the input type if necessary. 918193326Sed if (InputType == types::TY_Nothing) { 919193326Sed // If there was an explicit arg for this, claim it. 920193326Sed if (InputTypeArg) 921193326Sed InputTypeArg->claim(); 922193326Sed 923193326Sed // stdin must be handled specially. 924193326Sed if (memcmp(Value, "-", 2) == 0) { 925198092Srdivacky // If running with -E, treat as a C input (this changes the builtin 926198092Srdivacky // macros, for example). This may be overridden by -ObjC below. 927193326Sed // 928198092Srdivacky // Otherwise emit an error but still use a valid type to avoid 929198092Srdivacky // spurious errors (e.g., no inputs). 930221345Sdim if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP) 931193326Sed Diag(clang::diag::err_drv_unknown_stdin_type); 932193326Sed Ty = types::TY_C; 933193326Sed } else { 934221345Sdim // Otherwise lookup by extension. 935221345Sdim // Fallback is C if invoked as C preprocessor or Object otherwise. 936221345Sdim // We use a host hook here because Darwin at least has its own 937198092Srdivacky // idea of what .s is. 938193326Sed if (const char *Ext = strrchr(Value, '.')) 939212904Sdim Ty = TC.LookupTypeForExtension(Ext + 1); 940193326Sed 941221345Sdim if (Ty == types::TY_INVALID) { 942221345Sdim if (CCCIsCPP) 943221345Sdim Ty = types::TY_C; 944221345Sdim else 945221345Sdim Ty = types::TY_Object; 946221345Sdim } 947204643Srdivacky 948204643Srdivacky // If the driver is invoked as C++ compiler (like clang++ or c++) it 949204643Srdivacky // should autodetect some input files as C++ for g++ compatibility. 950204643Srdivacky if (CCCIsCXX) { 951204643Srdivacky types::ID OldTy = Ty; 952204643Srdivacky Ty = types::lookupCXXTypeForCType(Ty); 953204643Srdivacky 954204643Srdivacky if (Ty != OldTy) 955204643Srdivacky Diag(clang::diag::warn_drv_treating_input_as_cxx) 956204643Srdivacky << getTypeName(OldTy) << getTypeName(Ty); 957204643Srdivacky } 958193326Sed } 959193326Sed 960193326Sed // -ObjC and -ObjC++ override the default language, but only for "source 961193326Sed // files". We just treat everything that isn't a linker input as a 962193326Sed // source file. 963198092Srdivacky // 964193326Sed // FIXME: Clean this up if we move the phase sequence into the type. 965193326Sed if (Ty != types::TY_Object) { 966193326Sed if (Args.hasArg(options::OPT_ObjC)) 967193326Sed Ty = types::TY_ObjC; 968193326Sed else if (Args.hasArg(options::OPT_ObjCXX)) 969193326Sed Ty = types::TY_ObjCXX; 970193326Sed } 971193326Sed } else { 972193326Sed assert(InputTypeArg && "InputType set w/o InputTypeArg"); 973193326Sed InputTypeArg->claim(); 974193326Sed Ty = InputType; 975193326Sed } 976193326Sed 977203955Srdivacky // Check that the file exists, if enabled. 978218893Sdim if (CheckInputsExist && memcmp(Value, "-", 2) != 0) { 979234353Sdim SmallString<64> Path(Value); 980234353Sdim if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 981243830Sdim if (!llvm::sys::path::is_absolute(Path.str())) { 982243830Sdim SmallString<64> Directory(WorkDir->getValue()); 983234353Sdim llvm::sys::path::append(Directory, Value); 984234353Sdim Path.assign(Directory); 985218893Sdim } 986234353Sdim } 987218893Sdim 988218893Sdim bool exists = false; 989234353Sdim if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists) 990218893Sdim Diag(clang::diag::err_drv_no_such_file) << Path.str(); 991218893Sdim else 992218893Sdim Inputs.push_back(std::make_pair(Ty, A)); 993218893Sdim } else 994193326Sed Inputs.push_back(std::make_pair(Ty, A)); 995193326Sed 996243830Sdim } else if (A->getOption().hasFlag(options::LinkerInput)) { 997198092Srdivacky // Just treat as object type, we could make a special type for this if 998198092Srdivacky // necessary. 999193326Sed Inputs.push_back(std::make_pair(types::TY_Object, A)); 1000193326Sed 1001199512Srdivacky } else if (A->getOption().matches(options::OPT_x)) { 1002198092Srdivacky InputTypeArg = A; 1003243830Sdim InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 1004234353Sdim A->claim(); 1005193326Sed 1006193326Sed // Follow gcc behavior and treat as linker input for invalid -x 1007198092Srdivacky // options. Its not clear why we shouldn't just revert to unknown; but 1008218893Sdim // this isn't very important, we might as well be bug compatible. 1009193326Sed if (!InputType) { 1010243830Sdim Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 1011193326Sed InputType = types::TY_Object; 1012193326Sed } 1013193326Sed } 1014193326Sed } 1015221345Sdim if (CCCIsCPP && Inputs.empty()) { 1016221345Sdim // If called as standalone preprocessor, stdin is processed 1017221345Sdim // if no other input is present. 1018221345Sdim unsigned Index = Args.getBaseArgs().MakeIndex("-"); 1019221345Sdim Arg *A = Opts->ParseOneArg(Args, Index); 1020221345Sdim A->claim(); 1021221345Sdim Inputs.push_back(std::make_pair(types::TY_C, A)); 1022221345Sdim } 1023226633Sdim} 1024221345Sdim 1025226633Sdimvoid Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args, 1026226633Sdim const InputList &Inputs, ActionList &Actions) const { 1027226633Sdim llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 1028226633Sdim 1029193326Sed if (!SuppressMissingInputWarning && Inputs.empty()) { 1030193326Sed Diag(clang::diag::err_drv_no_input_files); 1031193326Sed return; 1032193326Sed } 1033193326Sed 1034226633Sdim Arg *FinalPhaseArg; 1035226633Sdim phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 1036193326Sed 1037198092Srdivacky // Reject -Z* at the top level, these options should never have been exposed 1038198092Srdivacky // by gcc. 1039193326Sed if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 1040193326Sed Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 1041193326Sed 1042193326Sed // Construct the actions to perform. 1043193326Sed ActionList LinkerInputs; 1044249423Sdim ActionList SplitInputs; 1045249423Sdim llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 1046193326Sed for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 1047193326Sed types::ID InputType = Inputs[i].first; 1048193326Sed const Arg *InputArg = Inputs[i].second; 1049193326Sed 1050249423Sdim PL.clear(); 1051249423Sdim types::getCompilationPhases(InputType, PL); 1052193326Sed 1053198092Srdivacky // If the first step comes after the final phase we are doing as part of 1054198092Srdivacky // this compilation, warn the user about it. 1055249423Sdim phases::ID InitialPhase = PL[0]; 1056193326Sed if (InitialPhase > FinalPhase) { 1057193326Sed // Claim here to avoid the more general unused warning. 1058193326Sed InputArg->claim(); 1059198092Srdivacky 1060221345Sdim // Suppress all unused style warnings with -Qunused-arguments 1061221345Sdim if (Args.hasArg(options::OPT_Qunused_arguments)) 1062221345Sdim continue; 1063221345Sdim 1064239462Sdim // Special case when final phase determined by binary name, rather than 1065239462Sdim // by a command-line argument with a corresponding Arg. 1066239462Sdim if (CCCIsCPP) 1067239462Sdim Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 1068239462Sdim << InputArg->getAsString(Args) 1069239462Sdim << getPhaseName(InitialPhase); 1070198092Srdivacky // Special case '-E' warning on a previously preprocessed file to make 1071198092Srdivacky // more sense. 1072239462Sdim else if (InitialPhase == phases::Compile && 1073239462Sdim FinalPhase == phases::Preprocess && 1074239462Sdim getPreprocessedType(InputType) == types::TY_INVALID) 1075198092Srdivacky Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 1076198092Srdivacky << InputArg->getAsString(Args) 1077239462Sdim << !!FinalPhaseArg 1078239462Sdim << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""; 1079198092Srdivacky else 1080198092Srdivacky Diag(clang::diag::warn_drv_input_file_unused) 1081198092Srdivacky << InputArg->getAsString(Args) 1082198092Srdivacky << getPhaseName(InitialPhase) 1083239462Sdim << !!FinalPhaseArg 1084239462Sdim << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""; 1085193326Sed continue; 1086193326Sed } 1087198092Srdivacky 1088193326Sed // Build the pipeline for this file. 1089234353Sdim OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); 1090249423Sdim for (llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases>::iterator 1091249423Sdim i = PL.begin(), e = PL.end(); i != e; ++i) { 1092249423Sdim phases::ID Phase = *i; 1093193326Sed 1094193326Sed // We are done if this step is past what the user requested. 1095193326Sed if (Phase > FinalPhase) 1096193326Sed break; 1097193326Sed 1098193326Sed // Queue linker inputs. 1099193326Sed if (Phase == phases::Link) { 1100249423Sdim assert((i + 1) == e && "linking must be final compilation step."); 1101202879Srdivacky LinkerInputs.push_back(Current.take()); 1102193326Sed break; 1103193326Sed } 1104193326Sed 1105198092Srdivacky // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1106198092Srdivacky // encode this in the steps because the intermediate type depends on 1107198092Srdivacky // arguments. Just special case here. 1108193326Sed if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1109193326Sed continue; 1110193326Sed 1111193326Sed // Otherwise construct the appropriate action. 1112202879Srdivacky Current.reset(ConstructPhaseAction(Args, Phase, Current.take())); 1113193326Sed if (Current->getType() == types::TY_Nothing) 1114193326Sed break; 1115193326Sed } 1116193326Sed 1117193326Sed // If we ended with something, add to the output list. 1118193326Sed if (Current) 1119202879Srdivacky Actions.push_back(Current.take()); 1120193326Sed } 1121193326Sed 1122193326Sed // Add a link action if necessary. 1123193326Sed if (!LinkerInputs.empty()) 1124193326Sed Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 1125201361Srdivacky 1126201361Srdivacky // If we are linking, claim any options which are obviously only used for 1127201361Srdivacky // compilation. 1128249423Sdim if (FinalPhase == phases::Link && PL.size() == 1) 1129201361Srdivacky Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1130193326Sed} 1131193326Sed 1132193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 1133193326Sed Action *Input) const { 1134193326Sed llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1135193326Sed // Build the appropriate action. 1136193326Sed switch (Phase) { 1137226633Sdim case phases::Link: llvm_unreachable("link action invalid here."); 1138193326Sed case phases::Preprocess: { 1139193326Sed types::ID OutputTy; 1140193326Sed // -{M, MM} alter the output type. 1141218893Sdim if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1142193326Sed OutputTy = types::TY_Dependencies; 1143193326Sed } else { 1144239462Sdim OutputTy = Input->getType(); 1145239462Sdim if (!Args.hasFlag(options::OPT_frewrite_includes, 1146239462Sdim options::OPT_fno_rewrite_includes, false)) 1147239462Sdim OutputTy = types::getPreprocessedType(OutputTy); 1148193326Sed assert(OutputTy != types::TY_INVALID && 1149193326Sed "Cannot preprocess this input type!"); 1150193326Sed } 1151193326Sed return new PreprocessJobAction(Input, OutputTy); 1152193326Sed } 1153239462Sdim case phases::Precompile: { 1154239462Sdim types::ID OutputTy = types::TY_PCH; 1155239462Sdim if (Args.hasArg(options::OPT_fsyntax_only)) { 1156239462Sdim // Syntax checks should not emit a PCH file 1157239462Sdim OutputTy = types::TY_Nothing; 1158239462Sdim } 1159239462Sdim return new PrecompileJobAction(Input, OutputTy); 1160239462Sdim } 1161193326Sed case phases::Compile: { 1162193326Sed if (Args.hasArg(options::OPT_fsyntax_only)) { 1163193326Sed return new CompileJobAction(Input, types::TY_Nothing); 1164203955Srdivacky } else if (Args.hasArg(options::OPT_rewrite_objc)) { 1165203955Srdivacky return new CompileJobAction(Input, types::TY_RewrittenObjC); 1166234353Sdim } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) { 1167234353Sdim return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC); 1168193326Sed } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { 1169193326Sed return new AnalyzeJobAction(Input, types::TY_Plist); 1170234353Sdim } else if (Args.hasArg(options::OPT__migrate)) { 1171234353Sdim return new MigrateJobAction(Input, types::TY_Remap); 1172198092Srdivacky } else if (Args.hasArg(options::OPT_emit_ast)) { 1173198092Srdivacky return new CompileJobAction(Input, types::TY_AST); 1174249423Sdim } else if (Args.hasArg(options::OPT_module_file_info)) { 1175249423Sdim return new CompileJobAction(Input, types::TY_ModuleFile); 1176224145Sdim } else if (IsUsingLTO(Args)) { 1177198092Srdivacky types::ID Output = 1178210299Sed Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1179193326Sed return new CompileJobAction(Input, Output); 1180193326Sed } else { 1181193326Sed return new CompileJobAction(Input, types::TY_PP_Asm); 1182193326Sed } 1183193326Sed } 1184193326Sed case phases::Assemble: 1185193326Sed return new AssembleJobAction(Input, types::TY_Object); 1186193326Sed } 1187193326Sed 1188226633Sdim llvm_unreachable("invalid phase in ConstructPhaseAction"); 1189193326Sed} 1190193326Sed 1191224145Sdimbool Driver::IsUsingLTO(const ArgList &Args) const { 1192224145Sdim // Check for -emit-llvm or -flto. 1193224145Sdim if (Args.hasArg(options::OPT_emit_llvm) || 1194224145Sdim Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) 1195224145Sdim return true; 1196224145Sdim 1197224145Sdim // Check for -O4. 1198224145Sdim if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) 1199224145Sdim return A->getOption().matches(options::OPT_O4); 1200224145Sdim 1201224145Sdim return false; 1202224145Sdim} 1203224145Sdim 1204193326Sedvoid Driver::BuildJobs(Compilation &C) const { 1205193326Sed llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1206193326Sed 1207193326Sed Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1208193326Sed 1209198092Srdivacky // It is an error to provide a -o option if we are making multiple output 1210198092Srdivacky // files. 1211193326Sed if (FinalOutput) { 1212193326Sed unsigned NumOutputs = 0; 1213198092Srdivacky for (ActionList::const_iterator it = C.getActions().begin(), 1214193326Sed ie = C.getActions().end(); it != ie; ++it) 1215193326Sed if ((*it)->getType() != types::TY_Nothing) 1216193326Sed ++NumOutputs; 1217198092Srdivacky 1218193326Sed if (NumOutputs > 1) { 1219193326Sed Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1220193326Sed FinalOutput = 0; 1221193326Sed } 1222193326Sed } 1223193326Sed 1224198092Srdivacky for (ActionList::const_iterator it = C.getActions().begin(), 1225193326Sed ie = C.getActions().end(); it != ie; ++it) { 1226193326Sed Action *A = *it; 1227193326Sed 1228198092Srdivacky // If we are linking an image for multiple archs then the linker wants 1229198092Srdivacky // -arch_multiple and -final_output <final image name>. Unfortunately, this 1230198092Srdivacky // doesn't fit in cleanly because we have to pass this information down. 1231193326Sed // 1232198092Srdivacky // FIXME: This is a hack; find a cleaner way to integrate this into the 1233198092Srdivacky // process. 1234193326Sed const char *LinkingOutput = 0; 1235193326Sed if (isa<LipoJobAction>(A)) { 1236193326Sed if (FinalOutput) 1237243830Sdim LinkingOutput = FinalOutput->getValue(); 1238193326Sed else 1239193326Sed LinkingOutput = DefaultImageName.c_str(); 1240193326Sed } 1241193326Sed 1242193326Sed InputInfo II; 1243198092Srdivacky BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1244198092Srdivacky /*BoundArch*/0, 1245193326Sed /*AtTopLevel*/ true, 1246193326Sed /*LinkingOutput*/ LinkingOutput, 1247193326Sed II); 1248193326Sed } 1249193326Sed 1250198092Srdivacky // If the user passed -Qunused-arguments or there were errors, don't warn 1251198092Srdivacky // about any unused arguments. 1252218893Sdim if (Diags.hasErrorOccurred() || 1253193326Sed C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1254193326Sed return; 1255193326Sed 1256193326Sed // Claim -### here. 1257193326Sed (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1258198092Srdivacky 1259193326Sed for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 1260193326Sed it != ie; ++it) { 1261193326Sed Arg *A = *it; 1262198092Srdivacky 1263193326Sed // FIXME: It would be nice to be able to send the argument to the 1264226633Sdim // DiagnosticsEngine, so that extra values, position, and so on could be 1265226633Sdim // printed. 1266193326Sed if (!A->isClaimed()) { 1267243830Sdim if (A->getOption().hasFlag(options::NoArgumentUnused)) 1268193326Sed continue; 1269193326Sed 1270198092Srdivacky // Suppress the warning automatically if this is just a flag, and it is an 1271198092Srdivacky // instance of an argument we already claimed. 1272193326Sed const Option &Opt = A->getOption(); 1273243830Sdim if (Opt.getKind() == Option::FlagClass) { 1274193326Sed bool DuplicateClaimed = false; 1275193326Sed 1276199990Srdivacky for (arg_iterator it = C.getArgs().filtered_begin(&Opt), 1277199990Srdivacky ie = C.getArgs().filtered_end(); it != ie; ++it) { 1278199990Srdivacky if ((*it)->isClaimed()) { 1279193326Sed DuplicateClaimed = true; 1280193326Sed break; 1281193326Sed } 1282193326Sed } 1283193326Sed 1284193326Sed if (DuplicateClaimed) 1285193326Sed continue; 1286193326Sed } 1287193326Sed 1288198092Srdivacky Diag(clang::diag::warn_drv_unused_argument) 1289193326Sed << A->getAsString(C.getArgs()); 1290193326Sed } 1291193326Sed } 1292193326Sed} 1293193326Sed 1294249423Sdimstatic const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC, 1295203955Srdivacky const JobAction *JA, 1296203955Srdivacky const ActionList *&Inputs) { 1297203955Srdivacky const Tool *ToolForJob = 0; 1298203955Srdivacky 1299203955Srdivacky // See if we should look for a compiler with an integrated assembler. We match 1300203955Srdivacky // bottom up, so what we are actually looking for is an assembler job with a 1301203955Srdivacky // compiler input. 1302208600Srdivacky 1303249423Sdim if (TC->useIntegratedAs() && 1304203955Srdivacky !C.getArgs().hasArg(options::OPT_save_temps) && 1305203955Srdivacky isa<AssembleJobAction>(JA) && 1306203955Srdivacky Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { 1307249423Sdim const Tool *Compiler = 1308249423Sdim TC->SelectTool(cast<JobAction>(**Inputs->begin())); 1309249423Sdim if (!Compiler) 1310249423Sdim return NULL; 1311249423Sdim if (Compiler->hasIntegratedAssembler()) { 1312203955Srdivacky Inputs = &(*Inputs)[0]->getInputs(); 1313249423Sdim ToolForJob = Compiler; 1314203955Srdivacky } 1315203955Srdivacky } 1316203955Srdivacky 1317203955Srdivacky // Otherwise use the tool for the current job. 1318203955Srdivacky if (!ToolForJob) 1319249423Sdim ToolForJob = TC->SelectTool(*JA); 1320203955Srdivacky 1321203955Srdivacky // See if we should use an integrated preprocessor. We do so when we have 1322203955Srdivacky // exactly one input, since this is the only use case we care about 1323203955Srdivacky // (irrelevant since we don't support combine yet). 1324203955Srdivacky if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 1325203955Srdivacky !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 1326203955Srdivacky !C.getArgs().hasArg(options::OPT_traditional_cpp) && 1327203955Srdivacky !C.getArgs().hasArg(options::OPT_save_temps) && 1328243830Sdim !C.getArgs().hasArg(options::OPT_rewrite_objc) && 1329203955Srdivacky ToolForJob->hasIntegratedCPP()) 1330203955Srdivacky Inputs = &(*Inputs)[0]->getInputs(); 1331203955Srdivacky 1332249423Sdim return ToolForJob; 1333203955Srdivacky} 1334203955Srdivacky 1335193326Sedvoid Driver::BuildJobsForAction(Compilation &C, 1336193326Sed const Action *A, 1337193326Sed const ToolChain *TC, 1338198092Srdivacky const char *BoundArch, 1339193326Sed bool AtTopLevel, 1340193326Sed const char *LinkingOutput, 1341193326Sed InputInfo &Result) const { 1342198092Srdivacky llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1343193326Sed 1344193326Sed if (const InputAction *IA = dyn_cast<InputAction>(A)) { 1345198092Srdivacky // FIXME: It would be nice to not claim this here; maybe the old scheme of 1346198092Srdivacky // just using Args was better? 1347193326Sed const Arg &Input = IA->getInputArg(); 1348193326Sed Input.claim(); 1349210299Sed if (Input.getOption().matches(options::OPT_INPUT)) { 1350243830Sdim const char *Name = Input.getValue(); 1351193326Sed Result = InputInfo(Name, A->getType(), Name); 1352193326Sed } else 1353193326Sed Result = InputInfo(&Input, A->getType(), ""); 1354193326Sed return; 1355193326Sed } 1356193326Sed 1357193326Sed if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 1358239462Sdim const ToolChain *TC; 1359239462Sdim const char *ArchName = BAA->getArchName(); 1360198092Srdivacky 1361239462Sdim if (ArchName) 1362239462Sdim TC = &getToolChain(C.getArgs(), ArchName); 1363239462Sdim else 1364239462Sdim TC = &C.getDefaultToolChain(); 1365198092Srdivacky 1366198092Srdivacky BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), 1367212904Sdim AtTopLevel, LinkingOutput, Result); 1368193326Sed return; 1369193326Sed } 1370193326Sed 1371203955Srdivacky const ActionList *Inputs = &A->getInputs(); 1372203955Srdivacky 1373193326Sed const JobAction *JA = cast<JobAction>(A); 1374249423Sdim const Tool *T = SelectToolForJob(C, TC, JA, Inputs); 1375249423Sdim if (!T) 1376249423Sdim return; 1377198092Srdivacky 1378193326Sed // Only use pipes when there is exactly one input. 1379193326Sed InputInfoList InputInfos; 1380193326Sed for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 1381193326Sed it != ie; ++it) { 1382249423Sdim // Treat dsymutil and verify sub-jobs as being at the top-level too, they 1383249423Sdim // shouldn't get temporary output names. 1384210299Sed // FIXME: Clean this up. 1385210299Sed bool SubJobAtTopLevel = false; 1386249423Sdim if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A))) 1387210299Sed SubJobAtTopLevel = true; 1388210299Sed 1389193326Sed InputInfo II; 1390212904Sdim BuildJobsForAction(C, *it, TC, BoundArch, 1391210299Sed SubJobAtTopLevel, LinkingOutput, II); 1392193326Sed InputInfos.push_back(II); 1393193326Sed } 1394193326Sed 1395193326Sed // Always use the first input as the base input. 1396193326Sed const char *BaseInput = InputInfos[0].getBaseInput(); 1397193326Sed 1398210299Sed // ... except dsymutil actions, which use their actual input as the base 1399210299Sed // input. 1400210299Sed if (JA->getType() == types::TY_dSYM) 1401210299Sed BaseInput = InputInfos[0].getFilename(); 1402210299Sed 1403212904Sdim // Determine the place to write output to, if any. 1404249423Sdim if (JA->getType() == types::TY_Nothing) 1405193326Sed Result = InputInfo(A->getType(), BaseInput); 1406249423Sdim else 1407193326Sed Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 1408193326Sed A->getType(), BaseInput); 1409193326Sed 1410226633Sdim if (CCCPrintBindings && !CCGenDiagnostics) { 1411249423Sdim llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 1412249423Sdim << " - \"" << T->getName() << "\", inputs: ["; 1413193326Sed for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 1414193326Sed llvm::errs() << InputInfos[i].getAsString(); 1415193326Sed if (i + 1 != e) 1416193326Sed llvm::errs() << ", "; 1417193326Sed } 1418193326Sed llvm::errs() << "], output: " << Result.getAsString() << "\n"; 1419193326Sed } else { 1420249423Sdim T->ConstructJob(C, *JA, Result, InputInfos, 1421249423Sdim C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 1422193326Sed } 1423193326Sed} 1424193326Sed 1425198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C, 1426193326Sed const JobAction &JA, 1427193326Sed const char *BaseInput, 1428193326Sed bool AtTopLevel) const { 1429193326Sed llvm::PrettyStackTraceString CrashInfo("Computing output path"); 1430193326Sed // Output to a user requested destination? 1431226633Sdim if (AtTopLevel && !isa<DsymutilJobAction>(JA) && 1432226633Sdim !isa<VerifyJobAction>(JA)) { 1433193326Sed if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 1434249423Sdim return C.addResultFile(FinalOutput->getValue(), &JA); 1435193326Sed } 1436193326Sed 1437212904Sdim // Default to writing to stdout? 1438249423Sdim if (AtTopLevel && !CCGenDiagnostics && 1439249423Sdim (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 1440212904Sdim return "-"; 1441212904Sdim 1442193326Sed // Output to a temporary file? 1443226633Sdim if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) || 1444226633Sdim CCGenDiagnostics) { 1445226633Sdim StringRef Name = llvm::sys::path::filename(BaseInput); 1446226633Sdim std::pair<StringRef, StringRef> Split = Name.split('.'); 1447198092Srdivacky std::string TmpName = 1448226633Sdim GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1449193326Sed return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1450193326Sed } 1451193326Sed 1452234353Sdim SmallString<128> BasePath(BaseInput); 1453226633Sdim StringRef BaseName; 1454193326Sed 1455221345Sdim // Dsymutil actions should use the full path. 1456226633Sdim if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 1457221345Sdim BaseName = BasePath; 1458221345Sdim else 1459221345Sdim BaseName = llvm::sys::path::filename(BasePath); 1460221345Sdim 1461193326Sed // Determine what the derived output name should be. 1462193326Sed const char *NamedOutput; 1463193326Sed if (JA.getType() == types::TY_Image) { 1464193326Sed NamedOutput = DefaultImageName.c_str(); 1465193326Sed } else { 1466193326Sed const char *Suffix = types::getTypeTempSuffix(JA.getType()); 1467193326Sed assert(Suffix && "All types used for output should have a suffix."); 1468193326Sed 1469193326Sed std::string::size_type End = std::string::npos; 1470193326Sed if (!types::appendSuffixForType(JA.getType())) 1471193326Sed End = BaseName.rfind('.'); 1472193326Sed std::string Suffixed(BaseName.substr(0, End)); 1473193326Sed Suffixed += '.'; 1474193326Sed Suffixed += Suffix; 1475193326Sed NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 1476193326Sed } 1477193326Sed 1478239462Sdim // If we're saving temps and the temp file conflicts with the input file, 1479239462Sdim // then avoid overwriting input file. 1480224145Sdim if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && 1481226633Sdim NamedOutput == BaseName) { 1482239462Sdim 1483239462Sdim bool SameFile = false; 1484239462Sdim SmallString<256> Result; 1485239462Sdim llvm::sys::fs::current_path(Result); 1486239462Sdim llvm::sys::path::append(Result, BaseName); 1487239462Sdim llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 1488239462Sdim // Must share the same path to conflict. 1489239462Sdim if (SameFile) { 1490239462Sdim StringRef Name = llvm::sys::path::filename(BaseInput); 1491239462Sdim std::pair<StringRef, StringRef> Split = Name.split('.'); 1492239462Sdim std::string TmpName = 1493239462Sdim GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1494239462Sdim return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1495239462Sdim } 1496224145Sdim } 1497224145Sdim 1498198092Srdivacky // As an annoying special case, PCH generation doesn't strip the pathname. 1499193326Sed if (JA.getType() == types::TY_PCH) { 1500218893Sdim llvm::sys::path::remove_filename(BasePath); 1501218893Sdim if (BasePath.empty()) 1502193326Sed BasePath = NamedOutput; 1503193326Sed else 1504218893Sdim llvm::sys::path::append(BasePath, NamedOutput); 1505249423Sdim return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 1506193326Sed } else { 1507249423Sdim return C.addResultFile(NamedOutput, &JA); 1508193326Sed } 1509193326Sed} 1510193326Sed 1511198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 1512206084Srdivacky // Respect a limited subset of the '-Bprefix' functionality in GCC by 1513243830Sdim // attempting to use this prefix when looking for file paths. 1514218893Sdim for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1515218893Sdim ie = PrefixDirs.end(); it != ie; ++it) { 1516221345Sdim std::string Dir(*it); 1517221345Sdim if (Dir.empty()) 1518221345Sdim continue; 1519221345Sdim if (Dir[0] == '=') 1520221345Sdim Dir = SysRoot + Dir.substr(1); 1521221345Sdim llvm::sys::Path P(Dir); 1522206084Srdivacky P.appendComponent(Name); 1523218893Sdim bool Exists; 1524218893Sdim if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1525206084Srdivacky return P.str(); 1526206084Srdivacky } 1527206084Srdivacky 1528226633Sdim llvm::sys::Path P(ResourceDir); 1529226633Sdim P.appendComponent(Name); 1530226633Sdim bool Exists; 1531226633Sdim if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1532226633Sdim return P.str(); 1533226633Sdim 1534193326Sed const ToolChain::path_list &List = TC.getFilePaths(); 1535198092Srdivacky for (ToolChain::path_list::const_iterator 1536193326Sed it = List.begin(), ie = List.end(); it != ie; ++it) { 1537221345Sdim std::string Dir(*it); 1538221345Sdim if (Dir.empty()) 1539221345Sdim continue; 1540221345Sdim if (Dir[0] == '=') 1541221345Sdim Dir = SysRoot + Dir.substr(1); 1542221345Sdim llvm::sys::Path P(Dir); 1543193326Sed P.appendComponent(Name); 1544218893Sdim bool Exists; 1545218893Sdim if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1546198092Srdivacky return P.str(); 1547193326Sed } 1548193326Sed 1549198092Srdivacky return Name; 1550193326Sed} 1551193326Sed 1552243830Sdimstd::string Driver::GetProgramPath(const char *Name, 1553243830Sdim const ToolChain &TC) const { 1554234353Sdim // FIXME: Needs a better variable than DefaultTargetTriple 1555234353Sdim std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name); 1556206084Srdivacky // Respect a limited subset of the '-Bprefix' functionality in GCC by 1557243830Sdim // attempting to use this prefix when looking for program paths. 1558218893Sdim for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1559218893Sdim ie = PrefixDirs.end(); it != ie; ++it) { 1560243830Sdim bool IsDirectory; 1561243830Sdim if (!llvm::sys::fs::is_directory(*it, IsDirectory) && IsDirectory) { 1562243830Sdim llvm::sys::Path P(*it); 1563243830Sdim P.appendComponent(TargetSpecificExecutable); 1564243830Sdim if (P.canExecute()) return P.str(); 1565243830Sdim P.eraseComponent(); 1566243830Sdim P.appendComponent(Name); 1567243830Sdim if (P.canExecute()) return P.str(); 1568243830Sdim } else { 1569243830Sdim llvm::sys::Path P(*it + Name); 1570243830Sdim if (P.canExecute()) return P.str(); 1571243830Sdim } 1572206084Srdivacky } 1573206084Srdivacky 1574193326Sed const ToolChain::path_list &List = TC.getProgramPaths(); 1575198092Srdivacky for (ToolChain::path_list::const_iterator 1576193326Sed it = List.begin(), ie = List.end(); it != ie; ++it) { 1577193326Sed llvm::sys::Path P(*it); 1578226633Sdim P.appendComponent(TargetSpecificExecutable); 1579243830Sdim if (P.canExecute()) return P.str(); 1580226633Sdim P.eraseComponent(); 1581193326Sed P.appendComponent(Name); 1582243830Sdim if (P.canExecute()) return P.str(); 1583193326Sed } 1584193326Sed 1585193326Sed // If all else failed, search the path. 1586226633Sdim llvm::sys::Path 1587226633Sdim P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable)); 1588193326Sed if (!P.empty()) 1589198092Srdivacky return P.str(); 1590193326Sed 1591226633Sdim P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name)); 1592226633Sdim if (!P.empty()) 1593226633Sdim return P.str(); 1594226633Sdim 1595198092Srdivacky return Name; 1596193326Sed} 1597193326Sed 1598239462Sdimstd::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) 1599226633Sdim const { 1600198092Srdivacky // FIXME: This is lame; sys::Path should provide this function (in particular, 1601198092Srdivacky // it should know how to find the temporary files dir). 1602193326Sed std::string Error; 1603193326Sed const char *TmpDir = ::getenv("TMPDIR"); 1604193326Sed if (!TmpDir) 1605193326Sed TmpDir = ::getenv("TEMP"); 1606193326Sed if (!TmpDir) 1607193326Sed TmpDir = ::getenv("TMP"); 1608193326Sed if (!TmpDir) 1609193326Sed TmpDir = "/tmp"; 1610193326Sed llvm::sys::Path P(TmpDir); 1611226633Sdim P.appendComponent(Prefix); 1612193326Sed if (P.makeUnique(false, &Error)) { 1613239462Sdim Diag(clang::diag::err_unable_to_make_temp) << Error; 1614193326Sed return ""; 1615193326Sed } 1616193326Sed 1617198092Srdivacky // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. 1618193326Sed P.eraseFromDisk(false, 0); 1619193326Sed 1620239462Sdim if (Suffix) 1621239462Sdim P.appendSuffix(Suffix); 1622198092Srdivacky return P.str(); 1623193326Sed} 1624193326Sed 1625234353Sdim/// \brief Compute target triple from args. 1626234353Sdim/// 1627234353Sdim/// This routine provides the logic to compute a target triple from various 1628234353Sdim/// args passed to the driver and the default triple string. 1629234353Sdimstatic llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple, 1630234353Sdim const ArgList &Args, 1631234353Sdim StringRef DarwinArchName) { 1632234353Sdim // FIXME: Already done in Compilation *Driver::BuildCompilation 1633234353Sdim if (const Arg *A = Args.getLastArg(options::OPT_target)) 1634243830Sdim DefaultTargetTriple = A->getValue(); 1635193326Sed 1636234353Sdim llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 1637204793Srdivacky 1638234353Sdim // Handle Darwin-specific options available here. 1639234353Sdim if (Target.isOSDarwin()) { 1640234353Sdim // If an explict Darwin arch name is given, that trumps all. 1641234353Sdim if (!DarwinArchName.empty()) { 1642234353Sdim Target.setArch( 1643243830Sdim tools::darwin::getArchTypeForDarwinArchName(DarwinArchName)); 1644234353Sdim return Target; 1645234353Sdim } 1646234353Sdim 1647234353Sdim // Handle the Darwin '-arch' flag. 1648234353Sdim if (Arg *A = Args.getLastArg(options::OPT_arch)) { 1649234353Sdim llvm::Triple::ArchType DarwinArch 1650243830Sdim = tools::darwin::getArchTypeForDarwinArchName(A->getValue()); 1651234353Sdim if (DarwinArch != llvm::Triple::UnknownArch) 1652234353Sdim Target.setArch(DarwinArch); 1653234353Sdim } 1654193326Sed } 1655234353Sdim 1656249423Sdim // Handle pseudo-target flags '-EL' and '-EB'. 1657249423Sdim if (Arg *A = Args.getLastArg(options::OPT_EL, options::OPT_EB)) { 1658249423Sdim if (A->getOption().matches(options::OPT_EL)) { 1659249423Sdim if (Target.getArch() == llvm::Triple::mips) 1660249423Sdim Target.setArch(llvm::Triple::mipsel); 1661249423Sdim else if (Target.getArch() == llvm::Triple::mips64) 1662249423Sdim Target.setArch(llvm::Triple::mips64el); 1663249423Sdim } else { 1664249423Sdim if (Target.getArch() == llvm::Triple::mipsel) 1665249423Sdim Target.setArch(llvm::Triple::mips); 1666249423Sdim else if (Target.getArch() == llvm::Triple::mips64el) 1667249423Sdim Target.setArch(llvm::Triple::mips64); 1668249423Sdim } 1669249423Sdim } 1670249423Sdim 1671234353Sdim // Skip further flag support on OSes which don't support '-m32' or '-m64'. 1672234353Sdim if (Target.getArchName() == "tce" || 1673234353Sdim Target.getOS() == llvm::Triple::AuroraUX || 1674234353Sdim Target.getOS() == llvm::Triple::Minix) 1675234353Sdim return Target; 1676234353Sdim 1677234353Sdim // Handle pseudo-target flags '-m32' and '-m64'. 1678234353Sdim // FIXME: Should this information be in llvm::Triple? 1679234353Sdim if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { 1680234353Sdim if (A->getOption().matches(options::OPT_m32)) { 1681234353Sdim if (Target.getArch() == llvm::Triple::x86_64) 1682234353Sdim Target.setArch(llvm::Triple::x86); 1683234353Sdim if (Target.getArch() == llvm::Triple::ppc64) 1684234353Sdim Target.setArch(llvm::Triple::ppc); 1685234353Sdim } else { 1686234353Sdim if (Target.getArch() == llvm::Triple::x86) 1687234353Sdim Target.setArch(llvm::Triple::x86_64); 1688234353Sdim if (Target.getArch() == llvm::Triple::ppc) 1689234353Sdim Target.setArch(llvm::Triple::ppc64); 1690234353Sdim } 1691234353Sdim } 1692234353Sdim 1693234353Sdim return Target; 1694193326Sed} 1695193326Sed 1696234353Sdimconst ToolChain &Driver::getToolChain(const ArgList &Args, 1697234353Sdim StringRef DarwinArchName) const { 1698234353Sdim llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args, 1699234353Sdim DarwinArchName); 1700234353Sdim 1701234353Sdim ToolChain *&TC = ToolChains[Target.str()]; 1702234353Sdim if (!TC) { 1703234353Sdim switch (Target.getOS()) { 1704234353Sdim case llvm::Triple::AuroraUX: 1705234353Sdim TC = new toolchains::AuroraUX(*this, Target, Args); 1706234353Sdim break; 1707234353Sdim case llvm::Triple::Darwin: 1708234353Sdim case llvm::Triple::MacOSX: 1709234353Sdim case llvm::Triple::IOS: 1710234353Sdim if (Target.getArch() == llvm::Triple::x86 || 1711234353Sdim Target.getArch() == llvm::Triple::x86_64 || 1712234353Sdim Target.getArch() == llvm::Triple::arm || 1713234353Sdim Target.getArch() == llvm::Triple::thumb) 1714249423Sdim TC = new toolchains::DarwinClang(*this, Target, Args); 1715234353Sdim else 1716234353Sdim TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args); 1717234353Sdim break; 1718234353Sdim case llvm::Triple::DragonFly: 1719234353Sdim TC = new toolchains::DragonFly(*this, Target, Args); 1720234353Sdim break; 1721234353Sdim case llvm::Triple::OpenBSD: 1722234353Sdim TC = new toolchains::OpenBSD(*this, Target, Args); 1723234353Sdim break; 1724239462Sdim case llvm::Triple::Bitrig: 1725239462Sdim TC = new toolchains::Bitrig(*this, Target, Args); 1726239462Sdim break; 1727234353Sdim case llvm::Triple::NetBSD: 1728234353Sdim TC = new toolchains::NetBSD(*this, Target, Args); 1729234353Sdim break; 1730234353Sdim case llvm::Triple::FreeBSD: 1731234353Sdim TC = new toolchains::FreeBSD(*this, Target, Args); 1732234353Sdim break; 1733234353Sdim case llvm::Triple::Minix: 1734234353Sdim TC = new toolchains::Minix(*this, Target, Args); 1735234353Sdim break; 1736234353Sdim case llvm::Triple::Linux: 1737234353Sdim if (Target.getArch() == llvm::Triple::hexagon) 1738249423Sdim TC = new toolchains::Hexagon_TC(*this, Target, Args); 1739234353Sdim else 1740234353Sdim TC = new toolchains::Linux(*this, Target, Args); 1741234353Sdim break; 1742234353Sdim case llvm::Triple::Solaris: 1743234353Sdim TC = new toolchains::Solaris(*this, Target, Args); 1744234353Sdim break; 1745234353Sdim case llvm::Triple::Win32: 1746249423Sdim TC = new toolchains::Windows(*this, Target, Args); 1747234353Sdim break; 1748234353Sdim case llvm::Triple::MinGW32: 1749234353Sdim // FIXME: We need a MinGW toolchain. Fallthrough for now. 1750234353Sdim default: 1751234353Sdim // TCE is an OSless target 1752234353Sdim if (Target.getArchName() == "tce") { 1753249423Sdim TC = new toolchains::TCEToolChain(*this, Target, Args); 1754234353Sdim break; 1755234353Sdim } 1756249423Sdim // If Hexagon is configured as an OSless target 1757249423Sdim if (Target.getArch() == llvm::Triple::hexagon) { 1758249423Sdim TC = new toolchains::Hexagon_TC(*this, Target, Args); 1759249423Sdim break; 1760249423Sdim } 1761234353Sdim TC = new toolchains::Generic_GCC(*this, Target, Args); 1762234353Sdim break; 1763234353Sdim } 1764234353Sdim } 1765234353Sdim return *TC; 1766234353Sdim} 1767234353Sdim 1768249423Sdimbool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 1769198092Srdivacky // Check if user requested no clang, or clang doesn't understand this type (we 1770198092Srdivacky // only handle single inputs for now). 1771243830Sdim if (JA.size() != 1 || 1772193326Sed !types::isAcceptedByClang((*JA.begin())->getType())) 1773193326Sed return false; 1774193326Sed 1775193326Sed // Otherwise make sure this is an action clang understands. 1776243830Sdim if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 1777243830Sdim !isa<CompileJobAction>(JA)) 1778193326Sed return false; 1779193326Sed 1780193326Sed return true; 1781193326Sed} 1782193326Sed 1783198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 1784198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0. 1785193326Sed/// 1786198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were 1787198092Srdivacky/// parsed (10.3.5extrastuff). 1788198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 1789193326Sed unsigned &Minor, unsigned &Micro, 1790193326Sed bool &HadExtra) { 1791193326Sed HadExtra = false; 1792193326Sed 1793193326Sed Major = Minor = Micro = 0; 1794198092Srdivacky if (*Str == '\0') 1795193326Sed return true; 1796193326Sed 1797193326Sed char *End; 1798193326Sed Major = (unsigned) strtol(Str, &End, 10); 1799193326Sed if (*Str != '\0' && *End == '\0') 1800193326Sed return true; 1801193326Sed if (*End != '.') 1802193326Sed return false; 1803198092Srdivacky 1804193326Sed Str = End+1; 1805193326Sed Minor = (unsigned) strtol(Str, &End, 10); 1806193326Sed if (*Str != '\0' && *End == '\0') 1807193326Sed return true; 1808193326Sed if (*End != '.') 1809193326Sed return false; 1810193326Sed 1811193326Sed Str = End+1; 1812193326Sed Micro = (unsigned) strtol(Str, &End, 10); 1813193326Sed if (*Str != '\0' && *End == '\0') 1814193326Sed return true; 1815193326Sed if (Str == End) 1816193326Sed return false; 1817193326Sed HadExtra = true; 1818193326Sed return true; 1819193326Sed} 1820