clang API Documentation
00001 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 00010 #include "clang/Driver/Driver.h" 00011 00012 #include "clang/Driver/Action.h" 00013 #include "clang/Driver/Arg.h" 00014 #include "clang/Driver/ArgList.h" 00015 #include "clang/Driver/Compilation.h" 00016 #include "clang/Driver/DriverDiagnostic.h" 00017 #include "clang/Driver/Job.h" 00018 #include "clang/Driver/OptTable.h" 00019 #include "clang/Driver/Option.h" 00020 #include "clang/Driver/Options.h" 00021 #include "clang/Driver/Tool.h" 00022 #include "clang/Driver/ToolChain.h" 00023 00024 #include "clang/Basic/Version.h" 00025 00026 #include "llvm/ADT/ArrayRef.h" 00027 #include "llvm/ADT/StringSet.h" 00028 #include "llvm/ADT/OwningPtr.h" 00029 #include "llvm/Support/ErrorHandling.h" 00030 #include "llvm/Support/PrettyStackTrace.h" 00031 #include "llvm/Support/raw_ostream.h" 00032 #include "llvm/Support/FileSystem.h" 00033 #include "llvm/Support/Path.h" 00034 #include "llvm/Support/Program.h" 00035 00036 #include "InputInfo.h" 00037 #include "ToolChains.h" 00038 00039 #include <map> 00040 00041 #include "clang/Config/config.h" 00042 00043 using namespace clang::driver; 00044 using namespace clang; 00045 00046 Driver::Driver(StringRef ClangExecutable, 00047 StringRef DefaultTargetTriple, 00048 StringRef DefaultImageName, 00049 bool IsProduction, 00050 DiagnosticsEngine &Diags) 00051 : Opts(createDriverOptTable()), Diags(Diags), 00052 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), 00053 UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple), 00054 DefaultImageName(DefaultImageName), 00055 DriverTitle("clang \"gcc-compatible\" driver"), 00056 CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), 00057 CCLogDiagnosticsFilename(0), CCCIsCXX(false), 00058 CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false), 00059 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), 00060 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 00061 CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true), 00062 CCCUsePCH(true), SuppressMissingInputWarning(false) { 00063 if (IsProduction) { 00064 // In a "production" build, only use clang on architectures we expect to 00065 // work. 00066 // 00067 // During development its more convenient to always have the driver use 00068 // clang, but we don't want users to be confused when things don't work, or 00069 // to file bugs for things we don't support. 00070 CCCClangArchs.insert(llvm::Triple::x86); 00071 CCCClangArchs.insert(llvm::Triple::x86_64); 00072 CCCClangArchs.insert(llvm::Triple::arm); 00073 } 00074 00075 Name = llvm::sys::path::stem(ClangExecutable); 00076 Dir = llvm::sys::path::parent_path(ClangExecutable); 00077 00078 // Compute the path to the resource directory. 00079 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 00080 SmallString<128> P(Dir); 00081 if (ClangResourceDir != "") 00082 llvm::sys::path::append(P, ClangResourceDir); 00083 else 00084 llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); 00085 ResourceDir = P.str(); 00086 } 00087 00088 Driver::~Driver() { 00089 delete Opts; 00090 00091 for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(), 00092 E = ToolChains.end(); 00093 I != E; ++I) 00094 delete I->second; 00095 } 00096 00097 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) { 00098 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 00099 unsigned MissingArgIndex, MissingArgCount; 00100 InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(), 00101 MissingArgIndex, MissingArgCount); 00102 00103 // Check for missing argument error. 00104 if (MissingArgCount) 00105 Diag(clang::diag::err_drv_missing_argument) 00106 << Args->getArgString(MissingArgIndex) << MissingArgCount; 00107 00108 // Check for unsupported options. 00109 for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 00110 it != ie; ++it) { 00111 Arg *A = *it; 00112 if (A->getOption().isUnsupported()) { 00113 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 00114 continue; 00115 } 00116 00117 // Warn about -mcpu= without an argument. 00118 if (A->getOption().matches(options::OPT_mcpu_EQ) && 00119 A->containsValue("")) { 00120 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(*Args); 00121 } 00122 } 00123 00124 return Args; 00125 } 00126 00127 // Determine which compilation mode we are in. We look for options which 00128 // affect the phase, starting with the earliest phases, and record which 00129 // option we used to determine the final phase. 00130 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) 00131 const { 00132 Arg *PhaseArg = 0; 00133 phases::ID FinalPhase; 00134 00135 // -{E,M,MM} only run the preprocessor. 00136 if (CCCIsCPP || 00137 (PhaseArg = DAL.getLastArg(options::OPT_E)) || 00138 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) { 00139 FinalPhase = phases::Preprocess; 00140 00141 // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. 00142 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 00143 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 00144 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 00145 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 00146 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 00147 options::OPT__analyze_auto)) || 00148 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || 00149 (PhaseArg = DAL.getLastArg(options::OPT_S))) { 00150 FinalPhase = phases::Compile; 00151 00152 // -c only runs up to the assembler. 00153 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 00154 FinalPhase = phases::Assemble; 00155 00156 // Otherwise do everything. 00157 } else 00158 FinalPhase = phases::Link; 00159 00160 if (FinalPhaseArg) 00161 *FinalPhaseArg = PhaseArg; 00162 00163 return FinalPhase; 00164 } 00165 00166 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 00167 DerivedArgList *DAL = new DerivedArgList(Args); 00168 00169 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 00170 for (ArgList::const_iterator it = Args.begin(), 00171 ie = Args.end(); it != ie; ++it) { 00172 const Arg *A = *it; 00173 00174 // Unfortunately, we have to parse some forwarding options (-Xassembler, 00175 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 00176 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 00177 00178 // Rewrite linker options, to replace --no-demangle with a custom internal 00179 // option. 00180 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 00181 A->getOption().matches(options::OPT_Xlinker)) && 00182 A->containsValue("--no-demangle")) { 00183 // Add the rewritten no-demangle argument. 00184 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 00185 00186 // Add the remaining values as Xlinker arguments. 00187 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 00188 if (StringRef(A->getValue(Args, i)) != "--no-demangle") 00189 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), 00190 A->getValue(Args, i)); 00191 00192 continue; 00193 } 00194 00195 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 00196 // some build systems. We don't try to be complete here because we don't 00197 // care to encourage this usage model. 00198 if (A->getOption().matches(options::OPT_Wp_COMMA) && 00199 A->getNumValues() == 2 && 00200 (A->getValue(Args, 0) == StringRef("-MD") || 00201 A->getValue(Args, 0) == StringRef("-MMD"))) { 00202 // Rewrite to -MD/-MMD along with -MF. 00203 if (A->getValue(Args, 0) == StringRef("-MD")) 00204 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 00205 else 00206 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 00207 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 00208 A->getValue(Args, 1)); 00209 continue; 00210 } 00211 00212 // Rewrite reserved library names. 00213 if (A->getOption().matches(options::OPT_l)) { 00214 StringRef Value = A->getValue(Args); 00215 00216 // Rewrite unless -nostdlib is present. 00217 if (!HasNostdlib && Value == "stdc++") { 00218 DAL->AddFlagArg(A, Opts->getOption( 00219 options::OPT_Z_reserved_lib_stdcxx)); 00220 continue; 00221 } 00222 00223 // Rewrite unconditionally. 00224 if (Value == "cc_kext") { 00225 DAL->AddFlagArg(A, Opts->getOption( 00226 options::OPT_Z_reserved_lib_cckext)); 00227 continue; 00228 } 00229 } 00230 00231 DAL->append(*it); 00232 } 00233 00234 // Add a default value of -mlinker-version=, if one was given and the user 00235 // didn't specify one. 00236 #if defined(HOST_LINK_VERSION) 00237 if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { 00238 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 00239 HOST_LINK_VERSION); 00240 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 00241 } 00242 #endif 00243 00244 return DAL; 00245 } 00246 00247 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 00248 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 00249 00250 // FIXME: Handle environment options which affect driver behavior, somewhere 00251 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 00252 00253 if (char *env = ::getenv("COMPILER_PATH")) { 00254 StringRef CompilerPath = env; 00255 while (!CompilerPath.empty()) { 00256 std::pair<StringRef, StringRef> Split = CompilerPath.split(':'); 00257 PrefixDirs.push_back(Split.first); 00258 CompilerPath = Split.second; 00259 } 00260 } 00261 00262 // FIXME: What are we going to do with -V and -b? 00263 00264 // FIXME: This stuff needs to go into the Compilation, not the driver. 00265 bool CCCPrintOptions = false, CCCPrintActions = false; 00266 00267 InputArgList *Args = ParseArgStrings(ArgList.slice(1)); 00268 00269 // -no-canonical-prefixes is used very early in main. 00270 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); 00271 00272 // Ignore -pipe. 00273 Args->ClaimAllArgs(options::OPT_pipe); 00274 00275 // Extract -ccc args. 00276 // 00277 // FIXME: We need to figure out where this behavior should live. Most of it 00278 // should be outside in the client; the parts that aren't should have proper 00279 // options, either by introducing new ones or by overloading gcc ones like -V 00280 // or -b. 00281 CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options); 00282 CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); 00283 CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); 00284 CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX; 00285 CCCEcho = Args->hasArg(options::OPT_ccc_echo); 00286 if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) 00287 CCCGenericGCCName = A->getValue(*Args); 00288 CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx, 00289 options::OPT_ccc_no_clang_cxx, 00290 CCCUseClangCXX); 00291 CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, 00292 options::OPT_ccc_pch_is_pth); 00293 CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang); 00294 CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp); 00295 if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) { 00296 StringRef Cur = A->getValue(*Args); 00297 00298 CCCClangArchs.clear(); 00299 while (!Cur.empty()) { 00300 std::pair<StringRef, StringRef> Split = Cur.split(','); 00301 00302 if (!Split.first.empty()) { 00303 llvm::Triple::ArchType Arch = 00304 llvm::Triple(Split.first, "", "").getArch(); 00305 00306 if (Arch == llvm::Triple::UnknownArch) 00307 Diag(clang::diag::err_drv_invalid_arch_name) << Split.first; 00308 00309 CCCClangArchs.insert(Arch); 00310 } 00311 00312 Cur = Split.second; 00313 } 00314 } 00315 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 00316 // and getToolChain is const. 00317 if (const Arg *A = Args->getLastArg(options::OPT_target)) 00318 DefaultTargetTriple = A->getValue(*Args); 00319 if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) 00320 Dir = InstalledDir = A->getValue(*Args); 00321 for (arg_iterator it = Args->filtered_begin(options::OPT_B), 00322 ie = Args->filtered_end(); it != ie; ++it) { 00323 const Arg *A = *it; 00324 A->claim(); 00325 PrefixDirs.push_back(A->getValue(*Args, 0)); 00326 } 00327 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) 00328 SysRoot = A->getValue(*Args); 00329 if (Args->hasArg(options::OPT_nostdlib)) 00330 UseStdLib = false; 00331 00332 // Perform the default argument translations. 00333 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); 00334 00335 // Owned by the host. 00336 const ToolChain &TC = getToolChain(*Args); 00337 00338 // The compilation takes ownership of Args. 00339 Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs); 00340 00341 // FIXME: This behavior shouldn't be here. 00342 if (CCCPrintOptions) { 00343 PrintOptions(C->getInputArgs()); 00344 return C; 00345 } 00346 00347 if (!HandleImmediateArgs(*C)) 00348 return C; 00349 00350 // Construct the list of inputs. 00351 InputList Inputs; 00352 BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs); 00353 00354 // Construct the list of abstract actions to perform for this compilation. On 00355 // Darwin target OSes this uses the driver-driver and universal actions. 00356 if (TC.getTriple().isOSDarwin()) 00357 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), 00358 Inputs, C->getActions()); 00359 else 00360 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, 00361 C->getActions()); 00362 00363 if (CCCPrintActions) { 00364 PrintActions(*C); 00365 return C; 00366 } 00367 00368 BuildJobs(*C); 00369 00370 return C; 00371 } 00372 00373 // When clang crashes, produce diagnostic information including the fully 00374 // preprocessed source file(s). Request that the developer attach the 00375 // diagnostic information to a bug report. 00376 void Driver::generateCompilationDiagnostics(Compilation &C, 00377 const Command *FailingCommand) { 00378 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 00379 return; 00380 00381 // Don't try to generate diagnostics for link jobs. 00382 if (FailingCommand && FailingCommand->getCreator().isLinkJob()) 00383 return; 00384 00385 Diag(clang::diag::note_drv_command_failed_diag_msg) 00386 << "Please submit a bug report to " BUG_REPORT_URL " and include command" 00387 " line arguments and all diagnostic information."; 00388 00389 // Suppress driver output and emit preprocessor output to temp file. 00390 CCCIsCPP = true; 00391 CCGenDiagnostics = true; 00392 00393 // Save the original job command(s). 00394 std::string Cmd; 00395 llvm::raw_string_ostream OS(Cmd); 00396 if (FailingCommand) 00397 C.PrintJob(OS, *FailingCommand, "\n", false); 00398 else 00399 // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an 00400 // associated FailingCommand, so just pass all jobs. 00401 C.PrintJob(OS, C.getJobs(), "\n", false); 00402 OS.flush(); 00403 00404 // Clear stale state and suppress tool output. 00405 C.initCompilationForDiagnostics(); 00406 Diags.Reset(); 00407 00408 // Construct the list of inputs. 00409 InputList Inputs; 00410 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 00411 00412 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 00413 bool IgnoreInput = false; 00414 00415 // Ignore input from stdin or any inputs that cannot be preprocessed. 00416 if (!strcmp(it->second->getValue(C.getArgs()), "-")) { 00417 Diag(clang::diag::note_drv_command_failed_diag_msg) 00418 << "Error generating preprocessed source(s) - ignoring input from stdin" 00419 "."; 00420 IgnoreInput = true; 00421 } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 00422 IgnoreInput = true; 00423 } 00424 00425 if (IgnoreInput) { 00426 it = Inputs.erase(it); 00427 ie = Inputs.end(); 00428 } else { 00429 ++it; 00430 } 00431 } 00432 00433 // Don't attempt to generate preprocessed files if multiple -arch options are 00434 // used, unless they're all duplicates. 00435 llvm::StringSet<> ArchNames; 00436 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 00437 it != ie; ++it) { 00438 Arg *A = *it; 00439 if (A->getOption().matches(options::OPT_arch)) { 00440 StringRef ArchName = A->getValue(C.getArgs()); 00441 ArchNames.insert(ArchName); 00442 } 00443 } 00444 if (ArchNames.size() > 1) { 00445 Diag(clang::diag::note_drv_command_failed_diag_msg) 00446 << "Error generating preprocessed source(s) - cannot generate " 00447 "preprocessed source with multiple -arch options."; 00448 return; 00449 } 00450 00451 if (Inputs.empty()) { 00452 Diag(clang::diag::note_drv_command_failed_diag_msg) 00453 << "Error generating preprocessed source(s) - no preprocessable inputs."; 00454 return; 00455 } 00456 00457 // Construct the list of abstract actions to perform for this compilation. On 00458 // Darwin OSes this uses the driver-driver and builds universal actions. 00459 const ToolChain &TC = C.getDefaultToolChain(); 00460 if (TC.getTriple().isOSDarwin()) 00461 BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions()); 00462 else 00463 BuildActions(TC, C.getArgs(), Inputs, C.getActions()); 00464 00465 BuildJobs(C); 00466 00467 // If there were errors building the compilation, quit now. 00468 if (Diags.hasErrorOccurred()) { 00469 Diag(clang::diag::note_drv_command_failed_diag_msg) 00470 << "Error generating preprocessed source(s)."; 00471 return; 00472 } 00473 00474 // Generate preprocessed output. 00475 FailingCommand = 0; 00476 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 00477 00478 // If the command succeeded, we are done. 00479 if (Res == 0) { 00480 Diag(clang::diag::note_drv_command_failed_diag_msg) 00481 << "Preprocessed source(s) and associated run script(s) are located at:"; 00482 ArgStringList Files = C.getTempFiles(); 00483 for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); 00484 it != ie; ++it) { 00485 Diag(clang::diag::note_drv_command_failed_diag_msg) << *it; 00486 00487 std::string Err; 00488 std::string Script = StringRef(*it).rsplit('.').first; 00489 Script += ".sh"; 00490 llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err, 00491 llvm::raw_fd_ostream::F_Excl | 00492 llvm::raw_fd_ostream::F_Binary); 00493 if (!Err.empty()) { 00494 Diag(clang::diag::note_drv_command_failed_diag_msg) 00495 << "Error generating run script: " + Script + " " + Err; 00496 } else { 00497 // Strip away options not necessary to reproduce the crash. 00498 // FIXME: This doesn't work with quotes (e.g., -D "foo bar"). 00499 SmallVector<std::string, 16> Flag; 00500 Flag.push_back("-D "); 00501 Flag.push_back("-F"); 00502 Flag.push_back("-I "); 00503 Flag.push_back("-o "); 00504 Flag.push_back("-coverage-file "); 00505 Flag.push_back("-dependency-file "); 00506 Flag.push_back("-fdebug-compilation-dir "); 00507 Flag.push_back("-fmodule-cache-path "); 00508 Flag.push_back("-include "); 00509 Flag.push_back("-include-pch "); 00510 Flag.push_back("-isysroot "); 00511 Flag.push_back("-resource-dir "); 00512 Flag.push_back("-serialize-diagnostic-file "); 00513 for (unsigned i = 0, e = Flag.size(); i < e; ++i) { 00514 size_t I = 0, E = 0; 00515 do { 00516 I = Cmd.find(Flag[i], I); 00517 if (I == std::string::npos) break; 00518 00519 E = Cmd.find(" ", I + Flag[i].length()); 00520 if (E == std::string::npos) break; 00521 Cmd.erase(I, E - I + 1); 00522 } while(1); 00523 } 00524 // Append the new filename with correct preprocessed suffix. 00525 size_t I, E; 00526 I = Cmd.find("-main-file-name "); 00527 assert (I != std::string::npos && "Expected to find -main-file-name"); 00528 I += 16; 00529 E = Cmd.find(" ", I); 00530 assert (E != std::string::npos && "-main-file-name missing argument?"); 00531 StringRef OldFilename = StringRef(Cmd).slice(I, E); 00532 StringRef NewFilename = llvm::sys::path::filename(*it); 00533 I = StringRef(Cmd).rfind(OldFilename); 00534 E = I + OldFilename.size(); 00535 I = Cmd.rfind(" ", I) + 1; 00536 Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size()); 00537 ScriptOS << Cmd; 00538 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 00539 } 00540 } 00541 } else { 00542 // Failure, remove preprocessed files. 00543 if (!C.getArgs().hasArg(options::OPT_save_temps)) 00544 C.CleanupFileList(C.getTempFiles(), true); 00545 00546 Diag(clang::diag::note_drv_command_failed_diag_msg) 00547 << "Error generating preprocessed source(s)."; 00548 } 00549 } 00550 00551 int Driver::ExecuteCompilation(const Compilation &C, 00552 const Command *&FailingCommand) const { 00553 // Just print if -### was present. 00554 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 00555 C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); 00556 return 0; 00557 } 00558 00559 // If there were errors building the compilation, quit now. 00560 if (Diags.hasErrorOccurred()) 00561 return 1; 00562 00563 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 00564 00565 // Remove temp files. 00566 C.CleanupFileList(C.getTempFiles()); 00567 00568 // If the command succeeded, we are done. 00569 if (Res == 0) 00570 return Res; 00571 00572 // Otherwise, remove result files as well. 00573 if (!C.getArgs().hasArg(options::OPT_save_temps)) { 00574 C.CleanupFileList(C.getResultFiles(), true); 00575 00576 // Failure result files are valid unless we crashed. 00577 if (Res < 0) { 00578 C.CleanupFileList(C.getFailureResultFiles(), true); 00579 #ifdef _WIN32 00580 // Exit status should not be negative on Win32, 00581 // unless abnormal termination. 00582 Res = 1; 00583 #endif 00584 } 00585 } 00586 00587 // Print extra information about abnormal failures, if possible. 00588 // 00589 // This is ad-hoc, but we don't want to be excessively noisy. If the result 00590 // status was 1, assume the command failed normally. In particular, if it was 00591 // the compiler then assume it gave a reasonable error code. Failures in other 00592 // tools are less common, and they generally have worse diagnostics, so always 00593 // print the diagnostic there. 00594 const Tool &FailingTool = FailingCommand->getCreator(); 00595 00596 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 00597 // FIXME: See FIXME above regarding result code interpretation. 00598 if (Res < 0) 00599 Diag(clang::diag::err_drv_command_signalled) 00600 << FailingTool.getShortName(); 00601 else 00602 Diag(clang::diag::err_drv_command_failed) 00603 << FailingTool.getShortName() << Res; 00604 } 00605 00606 return Res; 00607 } 00608 00609 void Driver::PrintOptions(const ArgList &Args) const { 00610 unsigned i = 0; 00611 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 00612 it != ie; ++it, ++i) { 00613 Arg *A = *it; 00614 llvm::errs() << "Option " << i << " - " 00615 << "Name: \"" << A->getOption().getName() << "\", " 00616 << "Values: {"; 00617 for (unsigned j = 0; j < A->getNumValues(); ++j) { 00618 if (j) 00619 llvm::errs() << ", "; 00620 llvm::errs() << '"' << A->getValue(Args, j) << '"'; 00621 } 00622 llvm::errs() << "}\n"; 00623 } 00624 } 00625 00626 void Driver::PrintHelp(bool ShowHidden) const { 00627 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 00628 ShowHidden); 00629 } 00630 00631 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 00632 // FIXME: The following handlers should use a callback mechanism, we don't 00633 // know what the client would like to do. 00634 OS << getClangFullVersion() << '\n'; 00635 const ToolChain &TC = C.getDefaultToolChain(); 00636 OS << "Target: " << TC.getTripleString() << '\n'; 00637 00638 // Print the threading model. 00639 // 00640 // FIXME: Implement correctly. 00641 OS << "Thread model: " << "posix" << '\n'; 00642 } 00643 00644 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 00645 /// option. 00646 static void PrintDiagnosticCategories(raw_ostream &OS) { 00647 // Skip the empty category. 00648 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); 00649 i != max; ++i) 00650 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 00651 } 00652 00653 bool Driver::HandleImmediateArgs(const Compilation &C) { 00654 // The order these options are handled in gcc is all over the place, but we 00655 // don't expect inconsistencies w.r.t. that to matter in practice. 00656 00657 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 00658 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 00659 return false; 00660 } 00661 00662 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 00663 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 00664 // return an answer which matches our definition of __VERSION__. 00665 // 00666 // If we want to return a more correct answer some day, then we should 00667 // introduce a non-pedantically GCC compatible mode to Clang in which we 00668 // provide sensible definitions for -dumpversion, __VERSION__, etc. 00669 llvm::outs() << "4.2.1\n"; 00670 return false; 00671 } 00672 00673 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 00674 PrintDiagnosticCategories(llvm::outs()); 00675 return false; 00676 } 00677 00678 if (C.getArgs().hasArg(options::OPT_help) || 00679 C.getArgs().hasArg(options::OPT__help_hidden)) { 00680 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 00681 return false; 00682 } 00683 00684 if (C.getArgs().hasArg(options::OPT__version)) { 00685 // Follow gcc behavior and use stdout for --version and stderr for -v. 00686 PrintVersion(C, llvm::outs()); 00687 return false; 00688 } 00689 00690 if (C.getArgs().hasArg(options::OPT_v) || 00691 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 00692 PrintVersion(C, llvm::errs()); 00693 SuppressMissingInputWarning = true; 00694 } 00695 00696 const ToolChain &TC = C.getDefaultToolChain(); 00697 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 00698 llvm::outs() << "programs: ="; 00699 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 00700 ie = TC.getProgramPaths().end(); it != ie; ++it) { 00701 if (it != TC.getProgramPaths().begin()) 00702 llvm::outs() << ':'; 00703 llvm::outs() << *it; 00704 } 00705 llvm::outs() << "\n"; 00706 llvm::outs() << "libraries: =" << ResourceDir; 00707 00708 StringRef sysroot = C.getSysRoot(); 00709 00710 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 00711 ie = TC.getFilePaths().end(); it != ie; ++it) { 00712 llvm::outs() << ':'; 00713 const char *path = it->c_str(); 00714 if (path[0] == '=') 00715 llvm::outs() << sysroot << path + 1; 00716 else 00717 llvm::outs() << path; 00718 } 00719 llvm::outs() << "\n"; 00720 return false; 00721 } 00722 00723 // FIXME: The following handlers should use a callback mechanism, we don't 00724 // know what the client would like to do. 00725 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 00726 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n"; 00727 return false; 00728 } 00729 00730 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 00731 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n"; 00732 return false; 00733 } 00734 00735 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 00736 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 00737 return false; 00738 } 00739 00740 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 00741 // FIXME: We need tool chain support for this. 00742 llvm::outs() << ".;\n"; 00743 00744 switch (C.getDefaultToolChain().getTriple().getArch()) { 00745 default: 00746 break; 00747 00748 case llvm::Triple::x86_64: 00749 llvm::outs() << "x86_64;@m64" << "\n"; 00750 break; 00751 00752 case llvm::Triple::ppc64: 00753 llvm::outs() << "ppc64;@m64" << "\n"; 00754 break; 00755 } 00756 return false; 00757 } 00758 00759 // FIXME: What is the difference between print-multi-directory and 00760 // print-multi-os-directory? 00761 if (C.getArgs().hasArg(options::OPT_print_multi_directory) || 00762 C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 00763 switch (C.getDefaultToolChain().getTriple().getArch()) { 00764 default: 00765 case llvm::Triple::x86: 00766 case llvm::Triple::ppc: 00767 llvm::outs() << "." << "\n"; 00768 break; 00769 00770 case llvm::Triple::x86_64: 00771 llvm::outs() << "x86_64" << "\n"; 00772 break; 00773 00774 case llvm::Triple::ppc64: 00775 llvm::outs() << "ppc64" << "\n"; 00776 break; 00777 } 00778 return false; 00779 } 00780 00781 return true; 00782 } 00783 00784 static unsigned PrintActions1(const Compilation &C, Action *A, 00785 std::map<Action*, unsigned> &Ids) { 00786 if (Ids.count(A)) 00787 return Ids[A]; 00788 00789 std::string str; 00790 llvm::raw_string_ostream os(str); 00791 00792 os << Action::getClassName(A->getKind()) << ", "; 00793 if (InputAction *IA = dyn_cast<InputAction>(A)) { 00794 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; 00795 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 00796 os << '"' << BIA->getArchName() << '"' 00797 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 00798 } else { 00799 os << "{"; 00800 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 00801 os << PrintActions1(C, *it, Ids); 00802 ++it; 00803 if (it != ie) 00804 os << ", "; 00805 } 00806 os << "}"; 00807 } 00808 00809 unsigned Id = Ids.size(); 00810 Ids[A] = Id; 00811 llvm::errs() << Id << ": " << os.str() << ", " 00812 << types::getTypeName(A->getType()) << "\n"; 00813 00814 return Id; 00815 } 00816 00817 void Driver::PrintActions(const Compilation &C) const { 00818 std::map<Action*, unsigned> Ids; 00819 for (ActionList::const_iterator it = C.getActions().begin(), 00820 ie = C.getActions().end(); it != ie; ++it) 00821 PrintActions1(C, *it, Ids); 00822 } 00823 00824 /// \brief Check whether the given input tree contains any compilation or 00825 /// assembly actions. 00826 static bool ContainsCompileOrAssembleAction(const Action *A) { 00827 if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) 00828 return true; 00829 00830 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) 00831 if (ContainsCompileOrAssembleAction(*it)) 00832 return true; 00833 00834 return false; 00835 } 00836 00837 void Driver::BuildUniversalActions(const ToolChain &TC, 00838 const DerivedArgList &Args, 00839 const InputList &BAInputs, 00840 ActionList &Actions) const { 00841 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 00842 // Collect the list of architectures. Duplicates are allowed, but should only 00843 // be handled once (in the order seen). 00844 llvm::StringSet<> ArchNames; 00845 SmallVector<const char *, 4> Archs; 00846 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 00847 it != ie; ++it) { 00848 Arg *A = *it; 00849 00850 if (A->getOption().matches(options::OPT_arch)) { 00851 // Validate the option here; we don't save the type here because its 00852 // particular spelling may participate in other driver choices. 00853 llvm::Triple::ArchType Arch = 00854 llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); 00855 if (Arch == llvm::Triple::UnknownArch) { 00856 Diag(clang::diag::err_drv_invalid_arch_name) 00857 << A->getAsString(Args); 00858 continue; 00859 } 00860 00861 A->claim(); 00862 if (ArchNames.insert(A->getValue(Args))) 00863 Archs.push_back(A->getValue(Args)); 00864 } 00865 } 00866 00867 // When there is no explicit arch for this platform, make sure we still bind 00868 // the architecture (to the default) so that -Xarch_ is handled correctly. 00869 if (!Archs.size()) 00870 Archs.push_back(Args.MakeArgString(TC.getArchName())); 00871 00872 // FIXME: We killed off some others but these aren't yet detected in a 00873 // functional manner. If we added information to jobs about which "auxiliary" 00874 // files they wrote then we could detect the conflict these cause downstream. 00875 if (Archs.size() > 1) { 00876 // No recovery needed, the point of this is just to prevent 00877 // overwriting the same files. 00878 if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 00879 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 00880 << A->getAsString(Args); 00881 } 00882 00883 ActionList SingleActions; 00884 BuildActions(TC, Args, BAInputs, SingleActions); 00885 00886 // Add in arch bindings for every top level action, as well as lipo and 00887 // dsymutil steps if needed. 00888 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 00889 Action *Act = SingleActions[i]; 00890 00891 // Make sure we can lipo this kind of output. If not (and it is an actual 00892 // output) then we disallow, since we can't create an output file with the 00893 // right name without overwriting it. We could remove this oddity by just 00894 // changing the output names to include the arch, which would also fix 00895 // -save-temps. Compatibility wins for now. 00896 00897 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 00898 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 00899 << types::getTypeName(Act->getType()); 00900 00901 ActionList Inputs; 00902 for (unsigned i = 0, e = Archs.size(); i != e; ++i) { 00903 Inputs.push_back(new BindArchAction(Act, Archs[i])); 00904 if (i != 0) 00905 Inputs.back()->setOwnsInputs(false); 00906 } 00907 00908 // Lipo if necessary, we do it this way because we need to set the arch flag 00909 // so that -Xarch_ gets overwritten. 00910 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 00911 Actions.append(Inputs.begin(), Inputs.end()); 00912 else 00913 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 00914 00915 // Handle debug info queries. 00916 Arg *A = Args.getLastArg(options::OPT_g_Group); 00917 if (A && !A->getOption().matches(options::OPT_g0) && 00918 !A->getOption().matches(options::OPT_gstabs) && 00919 ContainsCompileOrAssembleAction(Actions.back())) { 00920 00921 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 00922 // have a compile input. We need to run 'dsymutil' ourselves in such cases 00923 // because the debug info will refer to a temporary object file which is 00924 // will be removed at the end of the compilation process. 00925 if (Act->getType() == types::TY_Image) { 00926 ActionList Inputs; 00927 Inputs.push_back(Actions.back()); 00928 Actions.pop_back(); 00929 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); 00930 } 00931 00932 // Verify the output (debug information only) if we passed '-verify'. 00933 if (Args.hasArg(options::OPT_verify)) { 00934 ActionList VerifyInputs; 00935 VerifyInputs.push_back(Actions.back()); 00936 Actions.pop_back(); 00937 Actions.push_back(new VerifyJobAction(VerifyInputs, 00938 types::TY_Nothing)); 00939 } 00940 } 00941 } 00942 } 00943 00944 // Construct a the list of inputs and their types. 00945 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 00946 InputList &Inputs) const { 00947 // Track the current user specified (-x) input. We also explicitly track the 00948 // argument used to set the type; we only want to claim the type when we 00949 // actually use it, so we warn about unused -x arguments. 00950 types::ID InputType = types::TY_Nothing; 00951 Arg *InputTypeArg = 0; 00952 00953 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 00954 it != ie; ++it) { 00955 Arg *A = *it; 00956 00957 if (isa<InputOption>(A->getOption())) { 00958 const char *Value = A->getValue(Args); 00959 types::ID Ty = types::TY_INVALID; 00960 00961 // Infer the input type if necessary. 00962 if (InputType == types::TY_Nothing) { 00963 // If there was an explicit arg for this, claim it. 00964 if (InputTypeArg) 00965 InputTypeArg->claim(); 00966 00967 // stdin must be handled specially. 00968 if (memcmp(Value, "-", 2) == 0) { 00969 // If running with -E, treat as a C input (this changes the builtin 00970 // macros, for example). This may be overridden by -ObjC below. 00971 // 00972 // Otherwise emit an error but still use a valid type to avoid 00973 // spurious errors (e.g., no inputs). 00974 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP) 00975 Diag(clang::diag::err_drv_unknown_stdin_type); 00976 Ty = types::TY_C; 00977 } else { 00978 // Otherwise lookup by extension. 00979 // Fallback is C if invoked as C preprocessor or Object otherwise. 00980 // We use a host hook here because Darwin at least has its own 00981 // idea of what .s is. 00982 if (const char *Ext = strrchr(Value, '.')) 00983 Ty = TC.LookupTypeForExtension(Ext + 1); 00984 00985 if (Ty == types::TY_INVALID) { 00986 if (CCCIsCPP) 00987 Ty = types::TY_C; 00988 else 00989 Ty = types::TY_Object; 00990 } 00991 00992 // If the driver is invoked as C++ compiler (like clang++ or c++) it 00993 // should autodetect some input files as C++ for g++ compatibility. 00994 if (CCCIsCXX) { 00995 types::ID OldTy = Ty; 00996 Ty = types::lookupCXXTypeForCType(Ty); 00997 00998 if (Ty != OldTy) 00999 Diag(clang::diag::warn_drv_treating_input_as_cxx) 01000 << getTypeName(OldTy) << getTypeName(Ty); 01001 } 01002 } 01003 01004 // -ObjC and -ObjC++ override the default language, but only for "source 01005 // files". We just treat everything that isn't a linker input as a 01006 // source file. 01007 // 01008 // FIXME: Clean this up if we move the phase sequence into the type. 01009 if (Ty != types::TY_Object) { 01010 if (Args.hasArg(options::OPT_ObjC)) 01011 Ty = types::TY_ObjC; 01012 else if (Args.hasArg(options::OPT_ObjCXX)) 01013 Ty = types::TY_ObjCXX; 01014 } 01015 } else { 01016 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 01017 InputTypeArg->claim(); 01018 Ty = InputType; 01019 } 01020 01021 // Check that the file exists, if enabled. 01022 if (CheckInputsExist && memcmp(Value, "-", 2) != 0) { 01023 SmallString<64> Path(Value); 01024 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 01025 SmallString<64> Directory(WorkDir->getValue(Args)); 01026 if (llvm::sys::path::is_absolute(Directory.str())) { 01027 llvm::sys::path::append(Directory, Value); 01028 Path.assign(Directory); 01029 } 01030 } 01031 01032 bool exists = false; 01033 if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists) 01034 Diag(clang::diag::err_drv_no_such_file) << Path.str(); 01035 else 01036 Inputs.push_back(std::make_pair(Ty, A)); 01037 } else 01038 Inputs.push_back(std::make_pair(Ty, A)); 01039 01040 } else if (A->getOption().isLinkerInput()) { 01041 // Just treat as object type, we could make a special type for this if 01042 // necessary. 01043 Inputs.push_back(std::make_pair(types::TY_Object, A)); 01044 01045 } else if (A->getOption().matches(options::OPT_x)) { 01046 InputTypeArg = A; 01047 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); 01048 A->claim(); 01049 01050 // Follow gcc behavior and treat as linker input for invalid -x 01051 // options. Its not clear why we shouldn't just revert to unknown; but 01052 // this isn't very important, we might as well be bug compatible. 01053 if (!InputType) { 01054 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); 01055 InputType = types::TY_Object; 01056 } 01057 } 01058 } 01059 if (CCCIsCPP && Inputs.empty()) { 01060 // If called as standalone preprocessor, stdin is processed 01061 // if no other input is present. 01062 unsigned Index = Args.getBaseArgs().MakeIndex("-"); 01063 Arg *A = Opts->ParseOneArg(Args, Index); 01064 A->claim(); 01065 Inputs.push_back(std::make_pair(types::TY_C, A)); 01066 } 01067 } 01068 01069 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args, 01070 const InputList &Inputs, ActionList &Actions) const { 01071 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 01072 01073 if (!SuppressMissingInputWarning && Inputs.empty()) { 01074 Diag(clang::diag::err_drv_no_input_files); 01075 return; 01076 } 01077 01078 Arg *FinalPhaseArg; 01079 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 01080 01081 // Reject -Z* at the top level, these options should never have been exposed 01082 // by gcc. 01083 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 01084 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 01085 01086 // Construct the actions to perform. 01087 ActionList LinkerInputs; 01088 unsigned NumSteps = 0; 01089 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 01090 types::ID InputType = Inputs[i].first; 01091 const Arg *InputArg = Inputs[i].second; 01092 01093 NumSteps = types::getNumCompilationPhases(InputType); 01094 assert(NumSteps && "Invalid number of steps!"); 01095 01096 // If the first step comes after the final phase we are doing as part of 01097 // this compilation, warn the user about it. 01098 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); 01099 if (InitialPhase > FinalPhase) { 01100 // Claim here to avoid the more general unused warning. 01101 InputArg->claim(); 01102 01103 // Suppress all unused style warnings with -Qunused-arguments 01104 if (Args.hasArg(options::OPT_Qunused_arguments)) 01105 continue; 01106 01107 // Special case '-E' warning on a previously preprocessed file to make 01108 // more sense. 01109 if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess && 01110 getPreprocessedType(InputType) == types::TY_INVALID) 01111 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 01112 << InputArg->getAsString(Args) 01113 << FinalPhaseArg->getOption().getName(); 01114 else 01115 Diag(clang::diag::warn_drv_input_file_unused) 01116 << InputArg->getAsString(Args) 01117 << getPhaseName(InitialPhase) 01118 << FinalPhaseArg->getOption().getName(); 01119 continue; 01120 } 01121 01122 // Build the pipeline for this file. 01123 OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); 01124 for (unsigned i = 0; i != NumSteps; ++i) { 01125 phases::ID Phase = types::getCompilationPhase(InputType, i); 01126 01127 // We are done if this step is past what the user requested. 01128 if (Phase > FinalPhase) 01129 break; 01130 01131 // Queue linker inputs. 01132 if (Phase == phases::Link) { 01133 assert(i + 1 == NumSteps && "linking must be final compilation step."); 01134 LinkerInputs.push_back(Current.take()); 01135 break; 01136 } 01137 01138 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 01139 // encode this in the steps because the intermediate type depends on 01140 // arguments. Just special case here. 01141 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 01142 continue; 01143 01144 // Otherwise construct the appropriate action. 01145 Current.reset(ConstructPhaseAction(Args, Phase, Current.take())); 01146 if (Current->getType() == types::TY_Nothing) 01147 break; 01148 } 01149 01150 // If we ended with something, add to the output list. 01151 if (Current) 01152 Actions.push_back(Current.take()); 01153 } 01154 01155 // Add a link action if necessary. 01156 if (!LinkerInputs.empty()) 01157 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 01158 01159 // If we are linking, claim any options which are obviously only used for 01160 // compilation. 01161 if (FinalPhase == phases::Link && (NumSteps == 1)) 01162 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 01163 } 01164 01165 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 01166 Action *Input) const { 01167 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 01168 // Build the appropriate action. 01169 switch (Phase) { 01170 case phases::Link: llvm_unreachable("link action invalid here."); 01171 case phases::Preprocess: { 01172 types::ID OutputTy; 01173 // -{M, MM} alter the output type. 01174 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 01175 OutputTy = types::TY_Dependencies; 01176 } else { 01177 OutputTy = types::getPreprocessedType(Input->getType()); 01178 assert(OutputTy != types::TY_INVALID && 01179 "Cannot preprocess this input type!"); 01180 } 01181 return new PreprocessJobAction(Input, OutputTy); 01182 } 01183 case phases::Precompile: 01184 return new PrecompileJobAction(Input, types::TY_PCH); 01185 case phases::Compile: { 01186 if (Args.hasArg(options::OPT_fsyntax_only)) { 01187 return new CompileJobAction(Input, types::TY_Nothing); 01188 } else if (Args.hasArg(options::OPT_rewrite_objc)) { 01189 return new CompileJobAction(Input, types::TY_RewrittenObjC); 01190 } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) { 01191 return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC); 01192 } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { 01193 return new AnalyzeJobAction(Input, types::TY_Plist); 01194 } else if (Args.hasArg(options::OPT__migrate)) { 01195 return new MigrateJobAction(Input, types::TY_Remap); 01196 } else if (Args.hasArg(options::OPT_emit_ast)) { 01197 return new CompileJobAction(Input, types::TY_AST); 01198 } else if (IsUsingLTO(Args)) { 01199 types::ID Output = 01200 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 01201 return new CompileJobAction(Input, Output); 01202 } else { 01203 return new CompileJobAction(Input, types::TY_PP_Asm); 01204 } 01205 } 01206 case phases::Assemble: 01207 return new AssembleJobAction(Input, types::TY_Object); 01208 } 01209 01210 llvm_unreachable("invalid phase in ConstructPhaseAction"); 01211 } 01212 01213 bool Driver::IsUsingLTO(const ArgList &Args) const { 01214 // Check for -emit-llvm or -flto. 01215 if (Args.hasArg(options::OPT_emit_llvm) || 01216 Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) 01217 return true; 01218 01219 // Check for -O4. 01220 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) 01221 return A->getOption().matches(options::OPT_O4); 01222 01223 return false; 01224 } 01225 01226 void Driver::BuildJobs(Compilation &C) const { 01227 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 01228 01229 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 01230 01231 // It is an error to provide a -o option if we are making multiple output 01232 // files. 01233 if (FinalOutput) { 01234 unsigned NumOutputs = 0; 01235 for (ActionList::const_iterator it = C.getActions().begin(), 01236 ie = C.getActions().end(); it != ie; ++it) 01237 if ((*it)->getType() != types::TY_Nothing) 01238 ++NumOutputs; 01239 01240 if (NumOutputs > 1) { 01241 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 01242 FinalOutput = 0; 01243 } 01244 } 01245 01246 for (ActionList::const_iterator it = C.getActions().begin(), 01247 ie = C.getActions().end(); it != ie; ++it) { 01248 Action *A = *it; 01249 01250 // If we are linking an image for multiple archs then the linker wants 01251 // -arch_multiple and -final_output <final image name>. Unfortunately, this 01252 // doesn't fit in cleanly because we have to pass this information down. 01253 // 01254 // FIXME: This is a hack; find a cleaner way to integrate this into the 01255 // process. 01256 const char *LinkingOutput = 0; 01257 if (isa<LipoJobAction>(A)) { 01258 if (FinalOutput) 01259 LinkingOutput = FinalOutput->getValue(C.getArgs()); 01260 else 01261 LinkingOutput = DefaultImageName.c_str(); 01262 } 01263 01264 InputInfo II; 01265 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 01266 /*BoundArch*/0, 01267 /*AtTopLevel*/ true, 01268 /*LinkingOutput*/ LinkingOutput, 01269 II); 01270 } 01271 01272 // If the user passed -Qunused-arguments or there were errors, don't warn 01273 // about any unused arguments. 01274 if (Diags.hasErrorOccurred() || 01275 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 01276 return; 01277 01278 // Claim -### here. 01279 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 01280 01281 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 01282 it != ie; ++it) { 01283 Arg *A = *it; 01284 01285 // FIXME: It would be nice to be able to send the argument to the 01286 // DiagnosticsEngine, so that extra values, position, and so on could be 01287 // printed. 01288 if (!A->isClaimed()) { 01289 if (A->getOption().hasNoArgumentUnused()) 01290 continue; 01291 01292 // Suppress the warning automatically if this is just a flag, and it is an 01293 // instance of an argument we already claimed. 01294 const Option &Opt = A->getOption(); 01295 if (isa<FlagOption>(Opt)) { 01296 bool DuplicateClaimed = false; 01297 01298 for (arg_iterator it = C.getArgs().filtered_begin(&Opt), 01299 ie = C.getArgs().filtered_end(); it != ie; ++it) { 01300 if ((*it)->isClaimed()) { 01301 DuplicateClaimed = true; 01302 break; 01303 } 01304 } 01305 01306 if (DuplicateClaimed) 01307 continue; 01308 } 01309 01310 Diag(clang::diag::warn_drv_unused_argument) 01311 << A->getAsString(C.getArgs()); 01312 } 01313 } 01314 } 01315 01316 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC, 01317 const JobAction *JA, 01318 const ActionList *&Inputs) { 01319 const Tool *ToolForJob = 0; 01320 01321 // See if we should look for a compiler with an integrated assembler. We match 01322 // bottom up, so what we are actually looking for is an assembler job with a 01323 // compiler input. 01324 01325 if (C.getArgs().hasFlag(options::OPT_integrated_as, 01326 options::OPT_no_integrated_as, 01327 TC->IsIntegratedAssemblerDefault()) && 01328 !C.getArgs().hasArg(options::OPT_save_temps) && 01329 isa<AssembleJobAction>(JA) && 01330 Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { 01331 const Tool &Compiler = TC->SelectTool( 01332 C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs()); 01333 if (Compiler.hasIntegratedAssembler()) { 01334 Inputs = &(*Inputs)[0]->getInputs(); 01335 ToolForJob = &Compiler; 01336 } 01337 } 01338 01339 // Otherwise use the tool for the current job. 01340 if (!ToolForJob) 01341 ToolForJob = &TC->SelectTool(C, *JA, *Inputs); 01342 01343 // See if we should use an integrated preprocessor. We do so when we have 01344 // exactly one input, since this is the only use case we care about 01345 // (irrelevant since we don't support combine yet). 01346 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 01347 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 01348 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 01349 !C.getArgs().hasArg(options::OPT_save_temps) && 01350 ToolForJob->hasIntegratedCPP()) 01351 Inputs = &(*Inputs)[0]->getInputs(); 01352 01353 return *ToolForJob; 01354 } 01355 01356 void Driver::BuildJobsForAction(Compilation &C, 01357 const Action *A, 01358 const ToolChain *TC, 01359 const char *BoundArch, 01360 bool AtTopLevel, 01361 const char *LinkingOutput, 01362 InputInfo &Result) const { 01363 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 01364 01365 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 01366 // FIXME: It would be nice to not claim this here; maybe the old scheme of 01367 // just using Args was better? 01368 const Arg &Input = IA->getInputArg(); 01369 Input.claim(); 01370 if (Input.getOption().matches(options::OPT_INPUT)) { 01371 const char *Name = Input.getValue(C.getArgs()); 01372 Result = InputInfo(Name, A->getType(), Name); 01373 } else 01374 Result = InputInfo(&Input, A->getType(), ""); 01375 return; 01376 } 01377 01378 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 01379 const ToolChain *TC; 01380 const char *ArchName = BAA->getArchName(); 01381 01382 if (ArchName) 01383 TC = &getToolChain(C.getArgs(), ArchName); 01384 else 01385 TC = &C.getDefaultToolChain(); 01386 01387 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), 01388 AtTopLevel, LinkingOutput, Result); 01389 return; 01390 } 01391 01392 const ActionList *Inputs = &A->getInputs(); 01393 01394 const JobAction *JA = cast<JobAction>(A); 01395 const Tool &T = SelectToolForJob(C, TC, JA, Inputs); 01396 01397 // Only use pipes when there is exactly one input. 01398 InputInfoList InputInfos; 01399 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 01400 it != ie; ++it) { 01401 // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get 01402 // temporary output names. 01403 // 01404 // FIXME: Clean this up. 01405 bool SubJobAtTopLevel = false; 01406 if (AtTopLevel && isa<DsymutilJobAction>(A)) 01407 SubJobAtTopLevel = true; 01408 01409 // Also treat verify sub-jobs as being at the top-level. They don't 01410 // produce any output and so don't need temporary output names. 01411 if (AtTopLevel && isa<VerifyJobAction>(A)) 01412 SubJobAtTopLevel = true; 01413 01414 InputInfo II; 01415 BuildJobsForAction(C, *it, TC, BoundArch, 01416 SubJobAtTopLevel, LinkingOutput, II); 01417 InputInfos.push_back(II); 01418 } 01419 01420 // Always use the first input as the base input. 01421 const char *BaseInput = InputInfos[0].getBaseInput(); 01422 01423 // ... except dsymutil actions, which use their actual input as the base 01424 // input. 01425 if (JA->getType() == types::TY_dSYM) 01426 BaseInput = InputInfos[0].getFilename(); 01427 01428 // Determine the place to write output to, if any. 01429 if (JA->getType() == types::TY_Nothing) { 01430 Result = InputInfo(A->getType(), BaseInput); 01431 } else { 01432 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 01433 A->getType(), BaseInput); 01434 } 01435 01436 if (CCCPrintBindings && !CCGenDiagnostics) { 01437 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' 01438 << " - \"" << T.getName() << "\", inputs: ["; 01439 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 01440 llvm::errs() << InputInfos[i].getAsString(); 01441 if (i + 1 != e) 01442 llvm::errs() << ", "; 01443 } 01444 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 01445 } else { 01446 T.ConstructJob(C, *JA, Result, InputInfos, 01447 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 01448 } 01449 } 01450 01451 const char *Driver::GetNamedOutputPath(Compilation &C, 01452 const JobAction &JA, 01453 const char *BaseInput, 01454 bool AtTopLevel) const { 01455 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 01456 // Output to a user requested destination? 01457 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && 01458 !isa<VerifyJobAction>(JA)) { 01459 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 01460 return C.addResultFile(FinalOutput->getValue(C.getArgs())); 01461 } 01462 01463 // Default to writing to stdout? 01464 if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics) 01465 return "-"; 01466 01467 // Output to a temporary file? 01468 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) || 01469 CCGenDiagnostics) { 01470 StringRef Name = llvm::sys::path::filename(BaseInput); 01471 std::pair<StringRef, StringRef> Split = Name.split('.'); 01472 std::string TmpName = 01473 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 01474 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 01475 } 01476 01477 SmallString<128> BasePath(BaseInput); 01478 StringRef BaseName; 01479 01480 // Dsymutil actions should use the full path. 01481 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 01482 BaseName = BasePath; 01483 else 01484 BaseName = llvm::sys::path::filename(BasePath); 01485 01486 // Determine what the derived output name should be. 01487 const char *NamedOutput; 01488 if (JA.getType() == types::TY_Image) { 01489 NamedOutput = DefaultImageName.c_str(); 01490 } else { 01491 const char *Suffix = types::getTypeTempSuffix(JA.getType()); 01492 assert(Suffix && "All types used for output should have a suffix."); 01493 01494 std::string::size_type End = std::string::npos; 01495 if (!types::appendSuffixForType(JA.getType())) 01496 End = BaseName.rfind('.'); 01497 std::string Suffixed(BaseName.substr(0, End)); 01498 Suffixed += '.'; 01499 Suffixed += Suffix; 01500 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 01501 } 01502 01503 // If we're saving temps and the temp file conflicts with the input file, 01504 // then avoid overwriting input file. 01505 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && 01506 NamedOutput == BaseName) { 01507 01508 bool SameFile = false; 01509 SmallString<256> Result; 01510 llvm::sys::fs::current_path(Result); 01511 llvm::sys::path::append(Result, BaseName); 01512 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 01513 // Must share the same path to conflict. 01514 if (SameFile) { 01515 StringRef Name = llvm::sys::path::filename(BaseInput); 01516 std::pair<StringRef, StringRef> Split = Name.split('.'); 01517 std::string TmpName = 01518 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 01519 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 01520 } 01521 } 01522 01523 // As an annoying special case, PCH generation doesn't strip the pathname. 01524 if (JA.getType() == types::TY_PCH) { 01525 llvm::sys::path::remove_filename(BasePath); 01526 if (BasePath.empty()) 01527 BasePath = NamedOutput; 01528 else 01529 llvm::sys::path::append(BasePath, NamedOutput); 01530 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); 01531 } else { 01532 return C.addResultFile(NamedOutput); 01533 } 01534 } 01535 01536 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 01537 // Respect a limited subset of the '-Bprefix' functionality in GCC by 01538 // attempting to use this prefix when lokup up program paths. 01539 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 01540 ie = PrefixDirs.end(); it != ie; ++it) { 01541 std::string Dir(*it); 01542 if (Dir.empty()) 01543 continue; 01544 if (Dir[0] == '=') 01545 Dir = SysRoot + Dir.substr(1); 01546 llvm::sys::Path P(Dir); 01547 P.appendComponent(Name); 01548 bool Exists; 01549 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 01550 return P.str(); 01551 } 01552 01553 llvm::sys::Path P(ResourceDir); 01554 P.appendComponent(Name); 01555 bool Exists; 01556 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 01557 return P.str(); 01558 01559 const ToolChain::path_list &List = TC.getFilePaths(); 01560 for (ToolChain::path_list::const_iterator 01561 it = List.begin(), ie = List.end(); it != ie; ++it) { 01562 std::string Dir(*it); 01563 if (Dir.empty()) 01564 continue; 01565 if (Dir[0] == '=') 01566 Dir = SysRoot + Dir.substr(1); 01567 llvm::sys::Path P(Dir); 01568 P.appendComponent(Name); 01569 bool Exists; 01570 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 01571 return P.str(); 01572 } 01573 01574 return Name; 01575 } 01576 01577 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) { 01578 bool Exists; 01579 return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists 01580 : P.canExecute()); 01581 } 01582 01583 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC, 01584 bool WantFile) const { 01585 // FIXME: Needs a better variable than DefaultTargetTriple 01586 std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name); 01587 // Respect a limited subset of the '-Bprefix' functionality in GCC by 01588 // attempting to use this prefix when lokup up program paths. 01589 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 01590 ie = PrefixDirs.end(); it != ie; ++it) { 01591 llvm::sys::Path P(*it); 01592 P.appendComponent(TargetSpecificExecutable); 01593 if (isPathExecutable(P, WantFile)) return P.str(); 01594 P.eraseComponent(); 01595 P.appendComponent(Name); 01596 if (isPathExecutable(P, WantFile)) return P.str(); 01597 } 01598 01599 const ToolChain::path_list &List = TC.getProgramPaths(); 01600 for (ToolChain::path_list::const_iterator 01601 it = List.begin(), ie = List.end(); it != ie; ++it) { 01602 llvm::sys::Path P(*it); 01603 P.appendComponent(TargetSpecificExecutable); 01604 if (isPathExecutable(P, WantFile)) return P.str(); 01605 P.eraseComponent(); 01606 P.appendComponent(Name); 01607 if (isPathExecutable(P, WantFile)) return P.str(); 01608 } 01609 01610 // If all else failed, search the path. 01611 llvm::sys::Path 01612 P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable)); 01613 if (!P.empty()) 01614 return P.str(); 01615 01616 P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name)); 01617 if (!P.empty()) 01618 return P.str(); 01619 01620 return Name; 01621 } 01622 01623 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) 01624 const { 01625 // FIXME: This is lame; sys::Path should provide this function (in particular, 01626 // it should know how to find the temporary files dir). 01627 std::string Error; 01628 const char *TmpDir = ::getenv("TMPDIR"); 01629 if (!TmpDir) 01630 TmpDir = ::getenv("TEMP"); 01631 if (!TmpDir) 01632 TmpDir = ::getenv("TMP"); 01633 if (!TmpDir) 01634 TmpDir = "/tmp"; 01635 llvm::sys::Path P(TmpDir); 01636 P.appendComponent(Prefix); 01637 if (P.makeUnique(false, &Error)) { 01638 Diag(clang::diag::err_unable_to_make_temp) << Error; 01639 return ""; 01640 } 01641 01642 // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. 01643 P.eraseFromDisk(false, 0); 01644 01645 P.appendSuffix(Suffix); 01646 return P.str(); 01647 } 01648 01649 /// \brief Compute target triple from args. 01650 /// 01651 /// This routine provides the logic to compute a target triple from various 01652 /// args passed to the driver and the default triple string. 01653 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple, 01654 const ArgList &Args, 01655 StringRef DarwinArchName) { 01656 // FIXME: Already done in Compilation *Driver::BuildCompilation 01657 if (const Arg *A = Args.getLastArg(options::OPT_target)) 01658 DefaultTargetTriple = A->getValue(Args); 01659 01660 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 01661 01662 // Handle Darwin-specific options available here. 01663 if (Target.isOSDarwin()) { 01664 // If an explict Darwin arch name is given, that trumps all. 01665 if (!DarwinArchName.empty()) { 01666 Target.setArch( 01667 llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName)); 01668 return Target; 01669 } 01670 01671 // Handle the Darwin '-arch' flag. 01672 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 01673 llvm::Triple::ArchType DarwinArch 01674 = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); 01675 if (DarwinArch != llvm::Triple::UnknownArch) 01676 Target.setArch(DarwinArch); 01677 } 01678 } 01679 01680 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 01681 if (Target.getArchName() == "tce" || 01682 Target.getOS() == llvm::Triple::AuroraUX || 01683 Target.getOS() == llvm::Triple::Minix) 01684 return Target; 01685 01686 // Handle pseudo-target flags '-m32' and '-m64'. 01687 // FIXME: Should this information be in llvm::Triple? 01688 if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { 01689 if (A->getOption().matches(options::OPT_m32)) { 01690 if (Target.getArch() == llvm::Triple::x86_64) 01691 Target.setArch(llvm::Triple::x86); 01692 if (Target.getArch() == llvm::Triple::ppc64) 01693 Target.setArch(llvm::Triple::ppc); 01694 } else { 01695 if (Target.getArch() == llvm::Triple::x86) 01696 Target.setArch(llvm::Triple::x86_64); 01697 if (Target.getArch() == llvm::Triple::ppc) 01698 Target.setArch(llvm::Triple::ppc64); 01699 } 01700 } 01701 01702 return Target; 01703 } 01704 01705 const ToolChain &Driver::getToolChain(const ArgList &Args, 01706 StringRef DarwinArchName) const { 01707 llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args, 01708 DarwinArchName); 01709 01710 ToolChain *&TC = ToolChains[Target.str()]; 01711 if (!TC) { 01712 switch (Target.getOS()) { 01713 case llvm::Triple::AuroraUX: 01714 TC = new toolchains::AuroraUX(*this, Target, Args); 01715 break; 01716 case llvm::Triple::Darwin: 01717 case llvm::Triple::MacOSX: 01718 case llvm::Triple::IOS: 01719 if (Target.getArch() == llvm::Triple::x86 || 01720 Target.getArch() == llvm::Triple::x86_64 || 01721 Target.getArch() == llvm::Triple::arm || 01722 Target.getArch() == llvm::Triple::thumb) 01723 TC = new toolchains::DarwinClang(*this, Target); 01724 else 01725 TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args); 01726 break; 01727 case llvm::Triple::DragonFly: 01728 TC = new toolchains::DragonFly(*this, Target, Args); 01729 break; 01730 case llvm::Triple::OpenBSD: 01731 TC = new toolchains::OpenBSD(*this, Target, Args); 01732 break; 01733 case llvm::Triple::NetBSD: 01734 TC = new toolchains::NetBSD(*this, Target, Args); 01735 break; 01736 case llvm::Triple::FreeBSD: 01737 TC = new toolchains::FreeBSD(*this, Target, Args); 01738 break; 01739 case llvm::Triple::Minix: 01740 TC = new toolchains::Minix(*this, Target, Args); 01741 break; 01742 case llvm::Triple::Linux: 01743 if (Target.getArch() == llvm::Triple::hexagon) 01744 TC = new toolchains::Hexagon_TC(*this, Target); 01745 else 01746 TC = new toolchains::Linux(*this, Target, Args); 01747 break; 01748 case llvm::Triple::Solaris: 01749 TC = new toolchains::Solaris(*this, Target, Args); 01750 break; 01751 case llvm::Triple::Win32: 01752 TC = new toolchains::Windows(*this, Target); 01753 break; 01754 case llvm::Triple::MinGW32: 01755 // FIXME: We need a MinGW toolchain. Fallthrough for now. 01756 default: 01757 // TCE is an OSless target 01758 if (Target.getArchName() == "tce") { 01759 TC = new toolchains::TCEToolChain(*this, Target); 01760 break; 01761 } 01762 01763 TC = new toolchains::Generic_GCC(*this, Target, Args); 01764 break; 01765 } 01766 } 01767 return *TC; 01768 } 01769 01770 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, 01771 const llvm::Triple &Triple) const { 01772 // Check if user requested no clang, or clang doesn't understand this type (we 01773 // only handle single inputs for now). 01774 if (!CCCUseClang || JA.size() != 1 || 01775 !types::isAcceptedByClang((*JA.begin())->getType())) 01776 return false; 01777 01778 // Otherwise make sure this is an action clang understands. 01779 if (isa<PreprocessJobAction>(JA)) { 01780 if (!CCCUseClangCPP) { 01781 Diag(clang::diag::warn_drv_not_using_clang_cpp); 01782 return false; 01783 } 01784 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) 01785 return false; 01786 01787 // Use clang for C++? 01788 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { 01789 Diag(clang::diag::warn_drv_not_using_clang_cxx); 01790 return false; 01791 } 01792 01793 // Always use clang for precompiling, AST generation, and rewriting, 01794 // regardless of archs. 01795 if (isa<PrecompileJobAction>(JA) || 01796 types::isOnlyAcceptedByClang(JA.getType())) 01797 return true; 01798 01799 // Finally, don't use clang if this isn't one of the user specified archs to 01800 // build. 01801 if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) { 01802 Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName(); 01803 return false; 01804 } 01805 01806 return true; 01807 } 01808 01809 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 01810 /// grouped values as integers. Numbers which are not provided are set to 0. 01811 /// 01812 /// \return True if the entire string was parsed (9.2), or all groups were 01813 /// parsed (10.3.5extrastuff). 01814 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 01815 unsigned &Minor, unsigned &Micro, 01816 bool &HadExtra) { 01817 HadExtra = false; 01818 01819 Major = Minor = Micro = 0; 01820 if (*Str == '\0') 01821 return true; 01822 01823 char *End; 01824 Major = (unsigned) strtol(Str, &End, 10); 01825 if (*Str != '\0' && *End == '\0') 01826 return true; 01827 if (*End != '.') 01828 return false; 01829 01830 Str = End+1; 01831 Minor = (unsigned) strtol(Str, &End, 10); 01832 if (*Str != '\0' && *End == '\0') 01833 return true; 01834 if (*End != '.') 01835 return false; 01836 01837 Str = End+1; 01838 Micro = (unsigned) strtol(Str, &End, 10); 01839 if (*Str != '\0' && *End == '\0') 01840 return true; 01841 if (Str == End) 01842 return false; 01843 HadExtra = true; 01844 return true; 01845 }