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 #include "InputInfo.h" 00012 #include "ToolChains.h" 00013 #include "clang/Basic/Version.h" 00014 #include "clang/Config/config.h" 00015 #include "clang/Driver/Action.h" 00016 #include "clang/Driver/Compilation.h" 00017 #include "clang/Driver/DriverDiagnostic.h" 00018 #include "clang/Driver/Job.h" 00019 #include "clang/Driver/Options.h" 00020 #include "clang/Driver/Tool.h" 00021 #include "clang/Driver/ToolChain.h" 00022 #include "llvm/ADT/ArrayRef.h" 00023 #include "llvm/ADT/STLExtras.h" 00024 #include "llvm/ADT/StringExtras.h" 00025 #include "llvm/ADT/StringSet.h" 00026 #include "llvm/ADT/StringSwitch.h" 00027 #include "llvm/Option/Arg.h" 00028 #include "llvm/Option/ArgList.h" 00029 #include "llvm/Option/OptSpecifier.h" 00030 #include "llvm/Option/OptTable.h" 00031 #include "llvm/Option/Option.h" 00032 #include "llvm/Support/Debug.h" 00033 #include "llvm/Support/ErrorHandling.h" 00034 #include "llvm/Support/FileSystem.h" 00035 #include "llvm/Support/Path.h" 00036 #include "llvm/Support/PrettyStackTrace.h" 00037 #include "llvm/Support/Process.h" 00038 #include "llvm/Support/Program.h" 00039 #include "llvm/Support/raw_ostream.h" 00040 #include <map> 00041 #include <memory> 00042 00043 using namespace clang::driver; 00044 using namespace clang; 00045 using namespace llvm::opt; 00046 00047 Driver::Driver(StringRef ClangExecutable, 00048 StringRef DefaultTargetTriple, 00049 DiagnosticsEngine &Diags) 00050 : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode), 00051 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), 00052 UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple), 00053 DefaultImageName("a.out"), 00054 DriverTitle("clang LLVM compiler"), 00055 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr), 00056 CCLogDiagnosticsFilename(nullptr), 00057 CCCPrintBindings(false), 00058 CCPrintHeaders(false), CCLogDiagnostics(false), 00059 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 00060 CCCUsePCH(true), SuppressMissingInputWarning(false) { 00061 00062 Name = llvm::sys::path::stem(ClangExecutable); 00063 Dir = llvm::sys::path::parent_path(ClangExecutable); 00064 00065 // Compute the path to the resource directory. 00066 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 00067 SmallString<128> P(Dir); 00068 if (ClangResourceDir != "") 00069 llvm::sys::path::append(P, ClangResourceDir); 00070 else 00071 llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); 00072 ResourceDir = P.str(); 00073 } 00074 00075 Driver::~Driver() { 00076 delete Opts; 00077 00078 llvm::DeleteContainerSeconds(ToolChains); 00079 } 00080 00081 void Driver::ParseDriverMode(ArrayRef<const char *> Args) { 00082 const std::string OptName = 00083 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 00084 00085 for (size_t I = 0, E = Args.size(); I != E; ++I) { 00086 // Ingore nullptrs, they are response file's EOL markers 00087 if (Args[I] == nullptr) 00088 continue; 00089 const StringRef Arg = Args[I]; 00090 if (!Arg.startswith(OptName)) 00091 continue; 00092 00093 const StringRef Value = Arg.drop_front(OptName.size()); 00094 const unsigned M = llvm::StringSwitch<unsigned>(Value) 00095 .Case("gcc", GCCMode) 00096 .Case("g++", GXXMode) 00097 .Case("cpp", CPPMode) 00098 .Case("cl", CLMode) 00099 .Default(~0U); 00100 00101 if (M != ~0U) 00102 Mode = static_cast<DriverMode>(M); 00103 else 00104 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 00105 } 00106 } 00107 00108 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { 00109 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 00110 00111 unsigned IncludedFlagsBitmask; 00112 unsigned ExcludedFlagsBitmask; 00113 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 00114 getIncludeExcludeOptionFlagMasks(); 00115 00116 unsigned MissingArgIndex, MissingArgCount; 00117 InputArgList *Args = getOpts().ParseArgs(ArgStrings.begin(), ArgStrings.end(), 00118 MissingArgIndex, MissingArgCount, 00119 IncludedFlagsBitmask, 00120 ExcludedFlagsBitmask); 00121 00122 // Check for missing argument error. 00123 if (MissingArgCount) 00124 Diag(clang::diag::err_drv_missing_argument) 00125 << Args->getArgString(MissingArgIndex) << MissingArgCount; 00126 00127 // Check for unsupported options. 00128 for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 00129 it != ie; ++it) { 00130 Arg *A = *it; 00131 if (A->getOption().hasFlag(options::Unsupported)) { 00132 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 00133 continue; 00134 } 00135 00136 // Warn about -mcpu= without an argument. 00137 if (A->getOption().matches(options::OPT_mcpu_EQ) && 00138 A->containsValue("")) { 00139 Diag(clang::diag::warn_drv_empty_joined_argument) << 00140 A->getAsString(*Args); 00141 } 00142 } 00143 00144 for (arg_iterator it = Args->filtered_begin(options::OPT_UNKNOWN), 00145 ie = Args->filtered_end(); it != ie; ++it) { 00146 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args); 00147 } 00148 00149 return Args; 00150 } 00151 00152 // Determine which compilation mode we are in. We look for options which 00153 // affect the phase, starting with the earliest phases, and record which 00154 // option we used to determine the final phase. 00155 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) 00156 const { 00157 Arg *PhaseArg = nullptr; 00158 phases::ID FinalPhase; 00159 00160 // -{E,EP,P,M,MM} only run the preprocessor. 00161 if (CCCIsCPP() || 00162 (PhaseArg = DAL.getLastArg(options::OPT_E)) || 00163 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 00164 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 00165 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) { 00166 FinalPhase = phases::Preprocess; 00167 00168 // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. 00169 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 00170 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 00171 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 00172 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 00173 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 00174 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 00175 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 00176 options::OPT__analyze_auto)) || 00177 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || 00178 (PhaseArg = DAL.getLastArg(options::OPT_S))) { 00179 FinalPhase = phases::Compile; 00180 00181 // -c only runs up to the assembler. 00182 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 00183 FinalPhase = phases::Assemble; 00184 00185 // Otherwise do everything. 00186 } else 00187 FinalPhase = phases::Link; 00188 00189 if (FinalPhaseArg) 00190 *FinalPhaseArg = PhaseArg; 00191 00192 return FinalPhase; 00193 } 00194 00195 static Arg* MakeInputArg(DerivedArgList &Args, OptTable *Opts, 00196 StringRef Value) { 00197 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value, 00198 Args.getBaseArgs().MakeIndex(Value), Value.data()); 00199 Args.AddSynthesizedArg(A); 00200 A->claim(); 00201 return A; 00202 } 00203 00204 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 00205 DerivedArgList *DAL = new DerivedArgList(Args); 00206 00207 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 00208 for (ArgList::const_iterator it = Args.begin(), 00209 ie = Args.end(); it != ie; ++it) { 00210 const Arg *A = *it; 00211 00212 // Unfortunately, we have to parse some forwarding options (-Xassembler, 00213 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 00214 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 00215 00216 // Rewrite linker options, to replace --no-demangle with a custom internal 00217 // option. 00218 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 00219 A->getOption().matches(options::OPT_Xlinker)) && 00220 A->containsValue("--no-demangle")) { 00221 // Add the rewritten no-demangle argument. 00222 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 00223 00224 // Add the remaining values as Xlinker arguments. 00225 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 00226 if (StringRef(A->getValue(i)) != "--no-demangle") 00227 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), 00228 A->getValue(i)); 00229 00230 continue; 00231 } 00232 00233 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 00234 // some build systems. We don't try to be complete here because we don't 00235 // care to encourage this usage model. 00236 if (A->getOption().matches(options::OPT_Wp_COMMA) && 00237 (A->getValue(0) == StringRef("-MD") || 00238 A->getValue(0) == StringRef("-MMD"))) { 00239 // Rewrite to -MD/-MMD along with -MF. 00240 if (A->getValue(0) == StringRef("-MD")) 00241 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 00242 else 00243 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 00244 if (A->getNumValues() == 2) 00245 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 00246 A->getValue(1)); 00247 continue; 00248 } 00249 00250 // Rewrite reserved library names. 00251 if (A->getOption().matches(options::OPT_l)) { 00252 StringRef Value = A->getValue(); 00253 00254 // Rewrite unless -nostdlib is present. 00255 if (!HasNostdlib && Value == "stdc++") { 00256 DAL->AddFlagArg(A, Opts->getOption( 00257 options::OPT_Z_reserved_lib_stdcxx)); 00258 continue; 00259 } 00260 00261 // Rewrite unconditionally. 00262 if (Value == "cc_kext") { 00263 DAL->AddFlagArg(A, Opts->getOption( 00264 options::OPT_Z_reserved_lib_cckext)); 00265 continue; 00266 } 00267 } 00268 00269 // Pick up inputs via the -- option. 00270 if (A->getOption().matches(options::OPT__DASH_DASH)) { 00271 A->claim(); 00272 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 00273 DAL->append(MakeInputArg(*DAL, Opts, A->getValue(i))); 00274 continue; 00275 } 00276 00277 DAL->append(*it); 00278 } 00279 00280 // Add a default value of -mlinker-version=, if one was given and the user 00281 // didn't specify one. 00282 #if defined(HOST_LINK_VERSION) 00283 if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { 00284 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 00285 HOST_LINK_VERSION); 00286 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 00287 } 00288 #endif 00289 00290 return DAL; 00291 } 00292 00293 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 00294 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 00295 00296 // FIXME: Handle environment options which affect driver behavior, somewhere 00297 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 00298 00299 if (char *env = ::getenv("COMPILER_PATH")) { 00300 StringRef CompilerPath = env; 00301 while (!CompilerPath.empty()) { 00302 std::pair<StringRef, StringRef> Split 00303 = CompilerPath.split(llvm::sys::EnvPathSeparator); 00304 PrefixDirs.push_back(Split.first); 00305 CompilerPath = Split.second; 00306 } 00307 } 00308 00309 // We look for the driver mode option early, because the mode can affect 00310 // how other options are parsed. 00311 ParseDriverMode(ArgList.slice(1)); 00312 00313 // FIXME: What are we going to do with -V and -b? 00314 00315 // FIXME: This stuff needs to go into the Compilation, not the driver. 00316 bool CCCPrintActions; 00317 00318 InputArgList *Args = ParseArgStrings(ArgList.slice(1)); 00319 00320 // -no-canonical-prefixes is used very early in main. 00321 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); 00322 00323 // Ignore -pipe. 00324 Args->ClaimAllArgs(options::OPT_pipe); 00325 00326 // Extract -ccc args. 00327 // 00328 // FIXME: We need to figure out where this behavior should live. Most of it 00329 // should be outside in the client; the parts that aren't should have proper 00330 // options, either by introducing new ones or by overloading gcc ones like -V 00331 // or -b. 00332 CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); 00333 CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); 00334 if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) 00335 CCCGenericGCCName = A->getValue(); 00336 CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, 00337 options::OPT_ccc_pch_is_pth); 00338 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 00339 // and getToolChain is const. 00340 if (IsCLMode()) { 00341 // clang-cl targets MSVC-style Win32. 00342 llvm::Triple T(DefaultTargetTriple); 00343 T.setOS(llvm::Triple::Win32); 00344 T.setEnvironment(llvm::Triple::MSVC); 00345 DefaultTargetTriple = T.str(); 00346 } 00347 if (const Arg *A = Args->getLastArg(options::OPT_target)) 00348 DefaultTargetTriple = A->getValue(); 00349 if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) 00350 Dir = InstalledDir = A->getValue(); 00351 for (arg_iterator it = Args->filtered_begin(options::OPT_B), 00352 ie = Args->filtered_end(); it != ie; ++it) { 00353 const Arg *A = *it; 00354 A->claim(); 00355 PrefixDirs.push_back(A->getValue(0)); 00356 } 00357 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) 00358 SysRoot = A->getValue(); 00359 if (const Arg *A = Args->getLastArg(options::OPT__dyld_prefix_EQ)) 00360 DyldPrefix = A->getValue(); 00361 if (Args->hasArg(options::OPT_nostdlib)) 00362 UseStdLib = false; 00363 00364 if (const Arg *A = Args->getLastArg(options::OPT_resource_dir)) 00365 ResourceDir = A->getValue(); 00366 00367 // Perform the default argument translations. 00368 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); 00369 00370 // Owned by the host. 00371 const ToolChain &TC = getToolChain(*Args); 00372 00373 // The compilation takes ownership of Args. 00374 Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs); 00375 00376 if (!HandleImmediateArgs(*C)) 00377 return C; 00378 00379 // Construct the list of inputs. 00380 InputList Inputs; 00381 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 00382 00383 // Construct the list of abstract actions to perform for this compilation. On 00384 // MachO targets this uses the driver-driver and universal actions. 00385 if (TC.getTriple().isOSBinFormatMachO()) 00386 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), 00387 Inputs, C->getActions()); 00388 else 00389 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, 00390 C->getActions()); 00391 00392 if (CCCPrintActions) { 00393 PrintActions(*C); 00394 return C; 00395 } 00396 00397 BuildJobs(*C); 00398 00399 return C; 00400 } 00401 00402 // When clang crashes, produce diagnostic information including the fully 00403 // preprocessed source file(s). Request that the developer attach the 00404 // diagnostic information to a bug report. 00405 void Driver::generateCompilationDiagnostics(Compilation &C, 00406 const Command &FailingCommand) { 00407 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 00408 return; 00409 00410 // Don't try to generate diagnostics for link or dsymutil jobs. 00411 if (FailingCommand.getCreator().isLinkJob() || 00412 FailingCommand.getCreator().isDsymutilJob()) 00413 return; 00414 00415 // Print the version of the compiler. 00416 PrintVersion(C, llvm::errs()); 00417 00418 Diag(clang::diag::note_drv_command_failed_diag_msg) 00419 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 00420 "crash backtrace, preprocessed source, and associated run script."; 00421 00422 // Suppress driver output and emit preprocessor output to temp file. 00423 Mode = CPPMode; 00424 CCGenDiagnostics = true; 00425 00426 // Save the original job command(s). 00427 Command Cmd = FailingCommand; 00428 00429 // Keep track of whether we produce any errors while trying to produce 00430 // preprocessed sources. 00431 DiagnosticErrorTrap Trap(Diags); 00432 00433 // Suppress tool output. 00434 C.initCompilationForDiagnostics(); 00435 00436 // Construct the list of inputs. 00437 InputList Inputs; 00438 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 00439 00440 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 00441 bool IgnoreInput = false; 00442 00443 // Ignore input from stdin or any inputs that cannot be preprocessed. 00444 // Check type first as not all linker inputs have a value. 00445 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 00446 IgnoreInput = true; 00447 } else if (!strcmp(it->second->getValue(), "-")) { 00448 Diag(clang::diag::note_drv_command_failed_diag_msg) 00449 << "Error generating preprocessed source(s) - ignoring input from stdin" 00450 "."; 00451 IgnoreInput = true; 00452 } 00453 00454 if (IgnoreInput) { 00455 it = Inputs.erase(it); 00456 ie = Inputs.end(); 00457 } else { 00458 ++it; 00459 } 00460 } 00461 00462 if (Inputs.empty()) { 00463 Diag(clang::diag::note_drv_command_failed_diag_msg) 00464 << "Error generating preprocessed source(s) - no preprocessable inputs."; 00465 return; 00466 } 00467 00468 // Don't attempt to generate preprocessed files if multiple -arch options are 00469 // used, unless they're all duplicates. 00470 llvm::StringSet<> ArchNames; 00471 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 00472 it != ie; ++it) { 00473 Arg *A = *it; 00474 if (A->getOption().matches(options::OPT_arch)) { 00475 StringRef ArchName = A->getValue(); 00476 ArchNames.insert(ArchName); 00477 } 00478 } 00479 if (ArchNames.size() > 1) { 00480 Diag(clang::diag::note_drv_command_failed_diag_msg) 00481 << "Error generating preprocessed source(s) - cannot generate " 00482 "preprocessed source with multiple -arch options."; 00483 return; 00484 } 00485 00486 // Construct the list of abstract actions to perform for this compilation. On 00487 // Darwin OSes this uses the driver-driver and builds universal actions. 00488 const ToolChain &TC = C.getDefaultToolChain(); 00489 if (TC.getTriple().isOSBinFormatMachO()) 00490 BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions()); 00491 else 00492 BuildActions(TC, C.getArgs(), Inputs, C.getActions()); 00493 00494 BuildJobs(C); 00495 00496 // If there were errors building the compilation, quit now. 00497 if (Trap.hasErrorOccurred()) { 00498 Diag(clang::diag::note_drv_command_failed_diag_msg) 00499 << "Error generating preprocessed source(s)."; 00500 return; 00501 } 00502 00503 // Generate preprocessed output. 00504 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 00505 C.ExecuteJob(C.getJobs(), FailingCommands); 00506 00507 // If any of the preprocessing commands failed, clean up and exit. 00508 if (!FailingCommands.empty()) { 00509 if (!C.getArgs().hasArg(options::OPT_save_temps)) 00510 C.CleanupFileList(C.getTempFiles(), true); 00511 00512 Diag(clang::diag::note_drv_command_failed_diag_msg) 00513 << "Error generating preprocessed source(s)."; 00514 return; 00515 } 00516 00517 const ArgStringList &TempFiles = C.getTempFiles(); 00518 if (TempFiles.empty()) { 00519 Diag(clang::diag::note_drv_command_failed_diag_msg) 00520 << "Error generating preprocessed source(s)."; 00521 return; 00522 } 00523 00524 Diag(clang::diag::note_drv_command_failed_diag_msg) 00525 << "\n********************\n\n" 00526 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 00527 "Preprocessed source(s) and associated run script(s) are located at:"; 00528 00529 SmallString<128> VFS; 00530 for (const char *TempFile : TempFiles) { 00531 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 00532 if (StringRef(TempFile).endswith(".cache")) { 00533 // In some cases (modules) we'll dump extra data to help with reproducing 00534 // the crash into a directory next to the output. 00535 VFS = llvm::sys::path::filename(TempFile); 00536 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 00537 } 00538 } 00539 00540 // Assume associated files are based off of the first temporary file. 00541 CrashReportInfo CrashInfo(TempFiles[0], VFS); 00542 00543 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh"; 00544 std::error_code EC; 00545 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl); 00546 if (EC) { 00547 Diag(clang::diag::note_drv_command_failed_diag_msg) 00548 << "Error generating run script: " + Script + " " + EC.message(); 00549 } else { 00550 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 00551 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 00552 } 00553 Diag(clang::diag::note_drv_command_failed_diag_msg) 00554 << "\n\n********************"; 00555 } 00556 00557 void Driver::setUpResponseFiles(Compilation &C, Job &J) { 00558 if (JobList *Jobs = dyn_cast<JobList>(&J)) { 00559 for (auto &Job : *Jobs) 00560 setUpResponseFiles(C, Job); 00561 return; 00562 } 00563 00564 Command *CurCommand = dyn_cast<Command>(&J); 00565 if (!CurCommand) 00566 return; 00567 00568 // Since argumentsFitWithinSystemLimits() may underestimate system's capacity 00569 // if the tool does not support response files, there is a chance/ that things 00570 // will just work without a response file, so we silently just skip it. 00571 if (CurCommand->getCreator().getResponseFilesSupport() == Tool::RF_None || 00572 llvm::sys::argumentsFitWithinSystemLimits(CurCommand->getArguments())) 00573 return; 00574 00575 std::string TmpName = GetTemporaryPath("response", "txt"); 00576 CurCommand->setResponseFile(C.addTempFile(C.getArgs().MakeArgString( 00577 TmpName.c_str()))); 00578 } 00579 00580 int Driver::ExecuteCompilation(Compilation &C, 00581 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) { 00582 // Just print if -### was present. 00583 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 00584 C.getJobs().Print(llvm::errs(), "\n", true); 00585 return 0; 00586 } 00587 00588 // If there were errors building the compilation, quit now. 00589 if (Diags.hasErrorOccurred()) 00590 return 1; 00591 00592 // Set up response file names for each command, if necessary 00593 setUpResponseFiles(C, C.getJobs()); 00594 00595 C.ExecuteJob(C.getJobs(), FailingCommands); 00596 00597 // Remove temp files. 00598 C.CleanupFileList(C.getTempFiles()); 00599 00600 // If the command succeeded, we are done. 00601 if (FailingCommands.empty()) 00602 return 0; 00603 00604 // Otherwise, remove result files and print extra information about abnormal 00605 // failures. 00606 for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it = 00607 FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) { 00608 int Res = it->first; 00609 const Command *FailingCommand = it->second; 00610 00611 // Remove result files if we're not saving temps. 00612 if (!C.getArgs().hasArg(options::OPT_save_temps)) { 00613 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 00614 C.CleanupFileMap(C.getResultFiles(), JA, true); 00615 00616 // Failure result files are valid unless we crashed. 00617 if (Res < 0) 00618 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 00619 } 00620 00621 // Print extra information about abnormal failures, if possible. 00622 // 00623 // This is ad-hoc, but we don't want to be excessively noisy. If the result 00624 // status was 1, assume the command failed normally. In particular, if it 00625 // was the compiler then assume it gave a reasonable error code. Failures 00626 // in other tools are less common, and they generally have worse 00627 // diagnostics, so always print the diagnostic there. 00628 const Tool &FailingTool = FailingCommand->getCreator(); 00629 00630 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 00631 // FIXME: See FIXME above regarding result code interpretation. 00632 if (Res < 0) 00633 Diag(clang::diag::err_drv_command_signalled) 00634 << FailingTool.getShortName(); 00635 else 00636 Diag(clang::diag::err_drv_command_failed) 00637 << FailingTool.getShortName() << Res; 00638 } 00639 } 00640 return 0; 00641 } 00642 00643 void Driver::PrintHelp(bool ShowHidden) const { 00644 unsigned IncludedFlagsBitmask; 00645 unsigned ExcludedFlagsBitmask; 00646 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 00647 getIncludeExcludeOptionFlagMasks(); 00648 00649 ExcludedFlagsBitmask |= options::NoDriverOption; 00650 if (!ShowHidden) 00651 ExcludedFlagsBitmask |= HelpHidden; 00652 00653 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 00654 IncludedFlagsBitmask, ExcludedFlagsBitmask); 00655 } 00656 00657 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 00658 // FIXME: The following handlers should use a callback mechanism, we don't 00659 // know what the client would like to do. 00660 OS << getClangFullVersion() << '\n'; 00661 const ToolChain &TC = C.getDefaultToolChain(); 00662 OS << "Target: " << TC.getTripleString() << '\n'; 00663 00664 // Print the threading model. 00665 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 00666 // Don't print if the ToolChain would have barfed on it already 00667 if (TC.isThreadModelSupported(A->getValue())) 00668 OS << "Thread model: " << A->getValue(); 00669 } else 00670 OS << "Thread model: " << TC.getThreadModel(); 00671 OS << '\n'; 00672 } 00673 00674 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 00675 /// option. 00676 static void PrintDiagnosticCategories(raw_ostream &OS) { 00677 // Skip the empty category. 00678 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); 00679 i != max; ++i) 00680 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 00681 } 00682 00683 bool Driver::HandleImmediateArgs(const Compilation &C) { 00684 // The order these options are handled in gcc is all over the place, but we 00685 // don't expect inconsistencies w.r.t. that to matter in practice. 00686 00687 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 00688 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 00689 return false; 00690 } 00691 00692 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 00693 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 00694 // return an answer which matches our definition of __VERSION__. 00695 // 00696 // If we want to return a more correct answer some day, then we should 00697 // introduce a non-pedantically GCC compatible mode to Clang in which we 00698 // provide sensible definitions for -dumpversion, __VERSION__, etc. 00699 llvm::outs() << "4.2.1\n"; 00700 return false; 00701 } 00702 00703 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 00704 PrintDiagnosticCategories(llvm::outs()); 00705 return false; 00706 } 00707 00708 if (C.getArgs().hasArg(options::OPT_help) || 00709 C.getArgs().hasArg(options::OPT__help_hidden)) { 00710 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 00711 return false; 00712 } 00713 00714 if (C.getArgs().hasArg(options::OPT__version)) { 00715 // Follow gcc behavior and use stdout for --version and stderr for -v. 00716 PrintVersion(C, llvm::outs()); 00717 return false; 00718 } 00719 00720 if (C.getArgs().hasArg(options::OPT_v) || 00721 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 00722 PrintVersion(C, llvm::errs()); 00723 SuppressMissingInputWarning = true; 00724 } 00725 00726 const ToolChain &TC = C.getDefaultToolChain(); 00727 00728 if (C.getArgs().hasArg(options::OPT_v)) 00729 TC.printVerboseInfo(llvm::errs()); 00730 00731 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 00732 llvm::outs() << "programs: ="; 00733 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 00734 ie = TC.getProgramPaths().end(); it != ie; ++it) { 00735 if (it != TC.getProgramPaths().begin()) 00736 llvm::outs() << ':'; 00737 llvm::outs() << *it; 00738 } 00739 llvm::outs() << "\n"; 00740 llvm::outs() << "libraries: =" << ResourceDir; 00741 00742 StringRef sysroot = C.getSysRoot(); 00743 00744 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 00745 ie = TC.getFilePaths().end(); it != ie; ++it) { 00746 llvm::outs() << ':'; 00747 const char *path = it->c_str(); 00748 if (path[0] == '=') 00749 llvm::outs() << sysroot << path + 1; 00750 else 00751 llvm::outs() << path; 00752 } 00753 llvm::outs() << "\n"; 00754 return false; 00755 } 00756 00757 // FIXME: The following handlers should use a callback mechanism, we don't 00758 // know what the client would like to do. 00759 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 00760 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 00761 return false; 00762 } 00763 00764 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 00765 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 00766 return false; 00767 } 00768 00769 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 00770 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 00771 return false; 00772 } 00773 00774 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 00775 const MultilibSet &Multilibs = TC.getMultilibs(); 00776 00777 for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end(); 00778 I != E; ++I) { 00779 llvm::outs() << *I << "\n"; 00780 } 00781 return false; 00782 } 00783 00784 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 00785 const MultilibSet &Multilibs = TC.getMultilibs(); 00786 for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end(); 00787 I != E; ++I) { 00788 if (I->gccSuffix().empty()) 00789 llvm::outs() << ".\n"; 00790 else { 00791 StringRef Suffix(I->gccSuffix()); 00792 assert(Suffix.front() == '/'); 00793 llvm::outs() << Suffix.substr(1) << "\n"; 00794 } 00795 } 00796 return false; 00797 } 00798 00799 if (C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 00800 // FIXME: This should print out "lib/../lib", "lib/../lib64", or 00801 // "lib/../lib32" as appropriate for the toolchain. For now, print 00802 // nothing because it's not supported yet. 00803 return false; 00804 } 00805 00806 return true; 00807 } 00808 00809 static unsigned PrintActions1(const Compilation &C, Action *A, 00810 std::map<Action*, unsigned> &Ids) { 00811 if (Ids.count(A)) 00812 return Ids[A]; 00813 00814 std::string str; 00815 llvm::raw_string_ostream os(str); 00816 00817 os << Action::getClassName(A->getKind()) << ", "; 00818 if (InputAction *IA = dyn_cast<InputAction>(A)) { 00819 os << "\"" << IA->getInputArg().getValue() << "\""; 00820 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 00821 os << '"' << BIA->getArchName() << '"' 00822 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 00823 } else { 00824 os << "{"; 00825 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 00826 os << PrintActions1(C, *it, Ids); 00827 ++it; 00828 if (it != ie) 00829 os << ", "; 00830 } 00831 os << "}"; 00832 } 00833 00834 unsigned Id = Ids.size(); 00835 Ids[A] = Id; 00836 llvm::errs() << Id << ": " << os.str() << ", " 00837 << types::getTypeName(A->getType()) << "\n"; 00838 00839 return Id; 00840 } 00841 00842 void Driver::PrintActions(const Compilation &C) const { 00843 std::map<Action*, unsigned> Ids; 00844 for (ActionList::const_iterator it = C.getActions().begin(), 00845 ie = C.getActions().end(); it != ie; ++it) 00846 PrintActions1(C, *it, Ids); 00847 } 00848 00849 /// \brief Check whether the given input tree contains any compilation or 00850 /// assembly actions. 00851 static bool ContainsCompileOrAssembleAction(const Action *A) { 00852 if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) 00853 return true; 00854 00855 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) 00856 if (ContainsCompileOrAssembleAction(*it)) 00857 return true; 00858 00859 return false; 00860 } 00861 00862 void Driver::BuildUniversalActions(const ToolChain &TC, 00863 DerivedArgList &Args, 00864 const InputList &BAInputs, 00865 ActionList &Actions) const { 00866 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 00867 // Collect the list of architectures. Duplicates are allowed, but should only 00868 // be handled once (in the order seen). 00869 llvm::StringSet<> ArchNames; 00870 SmallVector<const char *, 4> Archs; 00871 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 00872 it != ie; ++it) { 00873 Arg *A = *it; 00874 00875 if (A->getOption().matches(options::OPT_arch)) { 00876 // Validate the option here; we don't save the type here because its 00877 // particular spelling may participate in other driver choices. 00878 llvm::Triple::ArchType Arch = 00879 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 00880 if (Arch == llvm::Triple::UnknownArch) { 00881 Diag(clang::diag::err_drv_invalid_arch_name) 00882 << A->getAsString(Args); 00883 continue; 00884 } 00885 00886 A->claim(); 00887 if (ArchNames.insert(A->getValue())) 00888 Archs.push_back(A->getValue()); 00889 } 00890 } 00891 00892 // When there is no explicit arch for this platform, make sure we still bind 00893 // the architecture (to the default) so that -Xarch_ is handled correctly. 00894 if (!Archs.size()) 00895 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 00896 00897 ActionList SingleActions; 00898 BuildActions(TC, Args, BAInputs, SingleActions); 00899 00900 // Add in arch bindings for every top level action, as well as lipo and 00901 // dsymutil steps if needed. 00902 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 00903 Action *Act = SingleActions[i]; 00904 00905 // Make sure we can lipo this kind of output. If not (and it is an actual 00906 // output) then we disallow, since we can't create an output file with the 00907 // right name without overwriting it. We could remove this oddity by just 00908 // changing the output names to include the arch, which would also fix 00909 // -save-temps. Compatibility wins for now. 00910 00911 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 00912 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 00913 << types::getTypeName(Act->getType()); 00914 00915 ActionList Inputs; 00916 for (unsigned i = 0, e = Archs.size(); i != e; ++i) { 00917 Inputs.push_back( 00918 new BindArchAction(std::unique_ptr<Action>(Act), Archs[i])); 00919 if (i != 0) 00920 Inputs.back()->setOwnsInputs(false); 00921 } 00922 00923 // Lipo if necessary, we do it this way because we need to set the arch flag 00924 // so that -Xarch_ gets overwritten. 00925 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 00926 Actions.append(Inputs.begin(), Inputs.end()); 00927 else 00928 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 00929 00930 // Handle debug info queries. 00931 Arg *A = Args.getLastArg(options::OPT_g_Group); 00932 if (A && !A->getOption().matches(options::OPT_g0) && 00933 !A->getOption().matches(options::OPT_gstabs) && 00934 ContainsCompileOrAssembleAction(Actions.back())) { 00935 00936 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 00937 // have a compile input. We need to run 'dsymutil' ourselves in such cases 00938 // because the debug info will refer to a temporary object file which 00939 // will be removed at the end of the compilation process. 00940 if (Act->getType() == types::TY_Image) { 00941 ActionList Inputs; 00942 Inputs.push_back(Actions.back()); 00943 Actions.pop_back(); 00944 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); 00945 } 00946 00947 // Verify the debug info output. 00948 if (Args.hasArg(options::OPT_verify_debug_info)) { 00949 std::unique_ptr<Action> VerifyInput(Actions.back()); 00950 Actions.pop_back(); 00951 Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput), 00952 types::TY_Nothing)); 00953 } 00954 } 00955 } 00956 } 00957 00958 /// \brief Check that the file referenced by Value exists. If it doesn't, 00959 /// issue a diagnostic and return false. 00960 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, 00961 StringRef Value) { 00962 if (!D.getCheckInputsExist()) 00963 return true; 00964 00965 // stdin always exists. 00966 if (Value == "-") 00967 return true; 00968 00969 SmallString<64> Path(Value); 00970 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 00971 if (!llvm::sys::path::is_absolute(Path.str())) { 00972 SmallString<64> Directory(WorkDir->getValue()); 00973 llvm::sys::path::append(Directory, Value); 00974 Path.assign(Directory); 00975 } 00976 } 00977 00978 if (llvm::sys::fs::exists(Twine(Path))) 00979 return true; 00980 00981 if (D.IsCLMode() && llvm::sys::Process::FindInEnvPath("LIB", Value)) 00982 return true; 00983 00984 D.Diag(clang::diag::err_drv_no_such_file) << Path.str(); 00985 return false; 00986 } 00987 00988 // Construct a the list of inputs and their types. 00989 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 00990 InputList &Inputs) const { 00991 // Track the current user specified (-x) input. We also explicitly track the 00992 // argument used to set the type; we only want to claim the type when we 00993 // actually use it, so we warn about unused -x arguments. 00994 types::ID InputType = types::TY_Nothing; 00995 Arg *InputTypeArg = nullptr; 00996 00997 // The last /TC or /TP option sets the input type to C or C++ globally. 00998 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 00999 options::OPT__SLASH_TP)) { 01000 InputTypeArg = TCTP; 01001 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 01002 ? types::TY_C : types::TY_CXX; 01003 01004 arg_iterator it = Args.filtered_begin(options::OPT__SLASH_TC, 01005 options::OPT__SLASH_TP); 01006 const arg_iterator ie = Args.filtered_end(); 01007 Arg *Previous = *it++; 01008 bool ShowNote = false; 01009 while (it != ie) { 01010 Diag(clang::diag::warn_drv_overriding_flag_option) 01011 << Previous->getSpelling() << (*it)->getSpelling(); 01012 Previous = *it++; 01013 ShowNote = true; 01014 } 01015 if (ShowNote) 01016 Diag(clang::diag::note_drv_t_option_is_global); 01017 01018 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 01019 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 01020 } 01021 01022 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 01023 it != ie; ++it) { 01024 Arg *A = *it; 01025 01026 if (A->getOption().getKind() == Option::InputClass) { 01027 const char *Value = A->getValue(); 01028 types::ID Ty = types::TY_INVALID; 01029 01030 // Infer the input type if necessary. 01031 if (InputType == types::TY_Nothing) { 01032 // If there was an explicit arg for this, claim it. 01033 if (InputTypeArg) 01034 InputTypeArg->claim(); 01035 01036 // stdin must be handled specially. 01037 if (memcmp(Value, "-", 2) == 0) { 01038 // If running with -E, treat as a C input (this changes the builtin 01039 // macros, for example). This may be overridden by -ObjC below. 01040 // 01041 // Otherwise emit an error but still use a valid type to avoid 01042 // spurious errors (e.g., no inputs). 01043 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 01044 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 01045 : clang::diag::err_drv_unknown_stdin_type); 01046 Ty = types::TY_C; 01047 } else { 01048 // Otherwise lookup by extension. 01049 // Fallback is C if invoked as C preprocessor or Object otherwise. 01050 // We use a host hook here because Darwin at least has its own 01051 // idea of what .s is. 01052 if (const char *Ext = strrchr(Value, '.')) 01053 Ty = TC.LookupTypeForExtension(Ext + 1); 01054 01055 if (Ty == types::TY_INVALID) { 01056 if (CCCIsCPP()) 01057 Ty = types::TY_C; 01058 else 01059 Ty = types::TY_Object; 01060 } 01061 01062 // If the driver is invoked as C++ compiler (like clang++ or c++) it 01063 // should autodetect some input files as C++ for g++ compatibility. 01064 if (CCCIsCXX()) { 01065 types::ID OldTy = Ty; 01066 Ty = types::lookupCXXTypeForCType(Ty); 01067 01068 if (Ty != OldTy) 01069 Diag(clang::diag::warn_drv_treating_input_as_cxx) 01070 << getTypeName(OldTy) << getTypeName(Ty); 01071 } 01072 } 01073 01074 // -ObjC and -ObjC++ override the default language, but only for "source 01075 // files". We just treat everything that isn't a linker input as a 01076 // source file. 01077 // 01078 // FIXME: Clean this up if we move the phase sequence into the type. 01079 if (Ty != types::TY_Object) { 01080 if (Args.hasArg(options::OPT_ObjC)) 01081 Ty = types::TY_ObjC; 01082 else if (Args.hasArg(options::OPT_ObjCXX)) 01083 Ty = types::TY_ObjCXX; 01084 } 01085 } else { 01086 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 01087 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 01088 // If emulating cl.exe, make sure that /TC and /TP don't affect input 01089 // object files. 01090 const char *Ext = strrchr(Value, '.'); 01091 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 01092 Ty = types::TY_Object; 01093 } 01094 if (Ty == types::TY_INVALID) { 01095 Ty = InputType; 01096 InputTypeArg->claim(); 01097 } 01098 } 01099 01100 if (DiagnoseInputExistence(*this, Args, Value)) 01101 Inputs.push_back(std::make_pair(Ty, A)); 01102 01103 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 01104 StringRef Value = A->getValue(); 01105 if (DiagnoseInputExistence(*this, Args, Value)) { 01106 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 01107 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 01108 } 01109 A->claim(); 01110 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 01111 StringRef Value = A->getValue(); 01112 if (DiagnoseInputExistence(*this, Args, Value)) { 01113 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 01114 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 01115 } 01116 A->claim(); 01117 } else if (A->getOption().hasFlag(options::LinkerInput)) { 01118 // Just treat as object type, we could make a special type for this if 01119 // necessary. 01120 Inputs.push_back(std::make_pair(types::TY_Object, A)); 01121 01122 } else if (A->getOption().matches(options::OPT_x)) { 01123 InputTypeArg = A; 01124 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 01125 A->claim(); 01126 01127 // Follow gcc behavior and treat as linker input for invalid -x 01128 // options. Its not clear why we shouldn't just revert to unknown; but 01129 // this isn't very important, we might as well be bug compatible. 01130 if (!InputType) { 01131 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 01132 InputType = types::TY_Object; 01133 } 01134 } 01135 } 01136 if (CCCIsCPP() && Inputs.empty()) { 01137 // If called as standalone preprocessor, stdin is processed 01138 // if no other input is present. 01139 Arg *A = MakeInputArg(Args, Opts, "-"); 01140 Inputs.push_back(std::make_pair(types::TY_C, A)); 01141 } 01142 } 01143 01144 void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args, 01145 const InputList &Inputs, ActionList &Actions) const { 01146 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 01147 01148 if (!SuppressMissingInputWarning && Inputs.empty()) { 01149 Diag(clang::diag::err_drv_no_input_files); 01150 return; 01151 } 01152 01153 Arg *FinalPhaseArg; 01154 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 01155 01156 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) { 01157 Diag(clang::diag::err_drv_emit_llvm_link); 01158 } 01159 01160 // Reject -Z* at the top level, these options should never have been exposed 01161 // by gcc. 01162 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 01163 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 01164 01165 // Diagnose misuse of /Fo. 01166 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 01167 StringRef V = A->getValue(); 01168 if (Inputs.size() > 1 && !V.empty() && 01169 !llvm::sys::path::is_separator(V.back())) { 01170 // Check whether /Fo tries to name an output file for multiple inputs. 01171 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 01172 << A->getSpelling() << V; 01173 Args.eraseArg(options::OPT__SLASH_Fo); 01174 } 01175 } 01176 01177 // Diagnose misuse of /Fa. 01178 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 01179 StringRef V = A->getValue(); 01180 if (Inputs.size() > 1 && !V.empty() && 01181 !llvm::sys::path::is_separator(V.back())) { 01182 // Check whether /Fa tries to name an asm file for multiple inputs. 01183 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 01184 << A->getSpelling() << V; 01185 Args.eraseArg(options::OPT__SLASH_Fa); 01186 } 01187 } 01188 01189 // Diagnose misuse of /o. 01190 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 01191 if (A->getValue()[0] == '\0') { 01192 // It has to have a value. 01193 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 01194 Args.eraseArg(options::OPT__SLASH_o); 01195 } 01196 } 01197 01198 // Construct the actions to perform. 01199 ActionList LinkerInputs; 01200 01201 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 01202 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 01203 types::ID InputType = Inputs[i].first; 01204 const Arg *InputArg = Inputs[i].second; 01205 01206 PL.clear(); 01207 types::getCompilationPhases(InputType, PL); 01208 01209 // If the first step comes after the final phase we are doing as part of 01210 // this compilation, warn the user about it. 01211 phases::ID InitialPhase = PL[0]; 01212 if (InitialPhase > FinalPhase) { 01213 // Claim here to avoid the more general unused warning. 01214 InputArg->claim(); 01215 01216 // Suppress all unused style warnings with -Qunused-arguments 01217 if (Args.hasArg(options::OPT_Qunused_arguments)) 01218 continue; 01219 01220 // Special case when final phase determined by binary name, rather than 01221 // by a command-line argument with a corresponding Arg. 01222 if (CCCIsCPP()) 01223 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 01224 << InputArg->getAsString(Args) 01225 << getPhaseName(InitialPhase); 01226 // Special case '-E' warning on a previously preprocessed file to make 01227 // more sense. 01228 else if (InitialPhase == phases::Compile && 01229 FinalPhase == phases::Preprocess && 01230 getPreprocessedType(InputType) == types::TY_INVALID) 01231 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 01232 << InputArg->getAsString(Args) 01233 << !!FinalPhaseArg 01234 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 01235 else 01236 Diag(clang::diag::warn_drv_input_file_unused) 01237 << InputArg->getAsString(Args) 01238 << getPhaseName(InitialPhase) 01239 << !!FinalPhaseArg 01240 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 01241 continue; 01242 } 01243 01244 // Build the pipeline for this file. 01245 std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType)); 01246 for (SmallVectorImpl<phases::ID>::iterator 01247 i = PL.begin(), e = PL.end(); i != e; ++i) { 01248 phases::ID Phase = *i; 01249 01250 // We are done if this step is past what the user requested. 01251 if (Phase > FinalPhase) 01252 break; 01253 01254 // Queue linker inputs. 01255 if (Phase == phases::Link) { 01256 assert((i + 1) == e && "linking must be final compilation step."); 01257 LinkerInputs.push_back(Current.release()); 01258 break; 01259 } 01260 01261 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 01262 // encode this in the steps because the intermediate type depends on 01263 // arguments. Just special case here. 01264 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 01265 continue; 01266 01267 // Otherwise construct the appropriate action. 01268 Current = ConstructPhaseAction(Args, Phase, std::move(Current)); 01269 if (Current->getType() == types::TY_Nothing) 01270 break; 01271 } 01272 01273 // If we ended with something, add to the output list. 01274 if (Current) 01275 Actions.push_back(Current.release()); 01276 } 01277 01278 // Add a link action if necessary. 01279 if (!LinkerInputs.empty()) 01280 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 01281 01282 // If we are linking, claim any options which are obviously only used for 01283 // compilation. 01284 if (FinalPhase == phases::Link && PL.size() == 1) { 01285 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 01286 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 01287 } 01288 01289 // Claim ignored clang-cl options. 01290 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 01291 } 01292 01293 std::unique_ptr<Action> 01294 Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 01295 std::unique_ptr<Action> Input) const { 01296 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 01297 // Build the appropriate action. 01298 switch (Phase) { 01299 case phases::Link: llvm_unreachable("link action invalid here."); 01300 case phases::Preprocess: { 01301 types::ID OutputTy; 01302 // -{M, MM} alter the output type. 01303 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 01304 OutputTy = types::TY_Dependencies; 01305 } else { 01306 OutputTy = Input->getType(); 01307 if (!Args.hasFlag(options::OPT_frewrite_includes, 01308 options::OPT_fno_rewrite_includes, false) && 01309 !CCGenDiagnostics) 01310 OutputTy = types::getPreprocessedType(OutputTy); 01311 assert(OutputTy != types::TY_INVALID && 01312 "Cannot preprocess this input type!"); 01313 } 01314 return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy); 01315 } 01316 case phases::Precompile: { 01317 types::ID OutputTy = types::TY_PCH; 01318 if (Args.hasArg(options::OPT_fsyntax_only)) { 01319 // Syntax checks should not emit a PCH file 01320 OutputTy = types::TY_Nothing; 01321 } 01322 return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy); 01323 } 01324 case phases::Compile: { 01325 if (Args.hasArg(options::OPT_fsyntax_only)) 01326 return llvm::make_unique<CompileJobAction>(std::move(Input), 01327 types::TY_Nothing); 01328 if (Args.hasArg(options::OPT_rewrite_objc)) 01329 return llvm::make_unique<CompileJobAction>(std::move(Input), 01330 types::TY_RewrittenObjC); 01331 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 01332 return llvm::make_unique<CompileJobAction>(std::move(Input), 01333 types::TY_RewrittenLegacyObjC); 01334 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) 01335 return llvm::make_unique<AnalyzeJobAction>(std::move(Input), 01336 types::TY_Plist); 01337 if (Args.hasArg(options::OPT__migrate)) 01338 return llvm::make_unique<MigrateJobAction>(std::move(Input), 01339 types::TY_Remap); 01340 if (Args.hasArg(options::OPT_emit_ast)) 01341 return llvm::make_unique<CompileJobAction>(std::move(Input), 01342 types::TY_AST); 01343 if (Args.hasArg(options::OPT_module_file_info)) 01344 return llvm::make_unique<CompileJobAction>(std::move(Input), 01345 types::TY_ModuleFile); 01346 if (Args.hasArg(options::OPT_verify_pch)) 01347 return llvm::make_unique<VerifyPCHJobAction>(std::move(Input), 01348 types::TY_Nothing); 01349 if (IsUsingLTO(Args)) { 01350 types::ID Output = 01351 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 01352 return llvm::make_unique<CompileJobAction>(std::move(Input), Output); 01353 } 01354 if (Args.hasArg(options::OPT_emit_llvm)) { 01355 types::ID Output = 01356 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 01357 return llvm::make_unique<CompileJobAction>(std::move(Input), Output); 01358 } 01359 return llvm::make_unique<CompileJobAction>(std::move(Input), 01360 types::TY_PP_Asm); 01361 } 01362 case phases::Assemble: 01363 return llvm::make_unique<AssembleJobAction>(std::move(Input), 01364 types::TY_Object); 01365 } 01366 01367 llvm_unreachable("invalid phase in ConstructPhaseAction"); 01368 } 01369 01370 bool Driver::IsUsingLTO(const ArgList &Args) const { 01371 if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) 01372 return true; 01373 01374 return false; 01375 } 01376 01377 void Driver::BuildJobs(Compilation &C) const { 01378 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 01379 01380 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 01381 01382 // It is an error to provide a -o option if we are making multiple output 01383 // files. 01384 if (FinalOutput) { 01385 unsigned NumOutputs = 0; 01386 for (ActionList::const_iterator it = C.getActions().begin(), 01387 ie = C.getActions().end(); it != ie; ++it) 01388 if ((*it)->getType() != types::TY_Nothing) 01389 ++NumOutputs; 01390 01391 if (NumOutputs > 1) { 01392 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 01393 FinalOutput = nullptr; 01394 } 01395 } 01396 01397 // Collect the list of architectures. 01398 llvm::StringSet<> ArchNames; 01399 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) { 01400 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 01401 it != ie; ++it) { 01402 Arg *A = *it; 01403 if (A->getOption().matches(options::OPT_arch)) 01404 ArchNames.insert(A->getValue()); 01405 } 01406 } 01407 01408 for (ActionList::const_iterator it = C.getActions().begin(), 01409 ie = C.getActions().end(); it != ie; ++it) { 01410 Action *A = *it; 01411 01412 // If we are linking an image for multiple archs then the linker wants 01413 // -arch_multiple and -final_output <final image name>. Unfortunately, this 01414 // doesn't fit in cleanly because we have to pass this information down. 01415 // 01416 // FIXME: This is a hack; find a cleaner way to integrate this into the 01417 // process. 01418 const char *LinkingOutput = nullptr; 01419 if (isa<LipoJobAction>(A)) { 01420 if (FinalOutput) 01421 LinkingOutput = FinalOutput->getValue(); 01422 else 01423 LinkingOutput = DefaultImageName.c_str(); 01424 } 01425 01426 InputInfo II; 01427 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 01428 /*BoundArch*/nullptr, 01429 /*AtTopLevel*/ true, 01430 /*MultipleArchs*/ ArchNames.size() > 1, 01431 /*LinkingOutput*/ LinkingOutput, 01432 II); 01433 } 01434 01435 // If the user passed -Qunused-arguments or there were errors, don't warn 01436 // about any unused arguments. 01437 if (Diags.hasErrorOccurred() || 01438 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 01439 return; 01440 01441 // Claim -### here. 01442 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 01443 01444 // Claim --driver-mode, it was handled earlier. 01445 (void) C.getArgs().hasArg(options::OPT_driver_mode); 01446 01447 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 01448 it != ie; ++it) { 01449 Arg *A = *it; 01450 01451 // FIXME: It would be nice to be able to send the argument to the 01452 // DiagnosticsEngine, so that extra values, position, and so on could be 01453 // printed. 01454 if (!A->isClaimed()) { 01455 if (A->getOption().hasFlag(options::NoArgumentUnused)) 01456 continue; 01457 01458 // Suppress the warning automatically if this is just a flag, and it is an 01459 // instance of an argument we already claimed. 01460 const Option &Opt = A->getOption(); 01461 if (Opt.getKind() == Option::FlagClass) { 01462 bool DuplicateClaimed = false; 01463 01464 for (arg_iterator it = C.getArgs().filtered_begin(&Opt), 01465 ie = C.getArgs().filtered_end(); it != ie; ++it) { 01466 if ((*it)->isClaimed()) { 01467 DuplicateClaimed = true; 01468 break; 01469 } 01470 } 01471 01472 if (DuplicateClaimed) 01473 continue; 01474 } 01475 01476 Diag(clang::diag::warn_drv_unused_argument) 01477 << A->getAsString(C.getArgs()); 01478 } 01479 } 01480 } 01481 01482 static const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC, 01483 const JobAction *JA, 01484 const ActionList *&Inputs) { 01485 const Tool *ToolForJob = nullptr; 01486 01487 // See if we should look for a compiler with an integrated assembler. We match 01488 // bottom up, so what we are actually looking for is an assembler job with a 01489 // compiler input. 01490 01491 if (TC->useIntegratedAs() && 01492 !C.getArgs().hasArg(options::OPT_save_temps) && 01493 !C.getArgs().hasArg(options::OPT_via_file_asm) && 01494 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 01495 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && 01496 isa<AssembleJobAction>(JA) && 01497 Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { 01498 const Tool *Compiler = 01499 TC->SelectTool(cast<JobAction>(**Inputs->begin())); 01500 if (!Compiler) 01501 return nullptr; 01502 if (Compiler->hasIntegratedAssembler()) { 01503 Inputs = &(*Inputs)[0]->getInputs(); 01504 ToolForJob = Compiler; 01505 } 01506 } 01507 01508 // Otherwise use the tool for the current job. 01509 if (!ToolForJob) 01510 ToolForJob = TC->SelectTool(*JA); 01511 01512 // See if we should use an integrated preprocessor. We do so when we have 01513 // exactly one input, since this is the only use case we care about 01514 // (irrelevant since we don't support combine yet). 01515 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 01516 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 01517 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 01518 !C.getArgs().hasArg(options::OPT_save_temps) && 01519 !C.getArgs().hasArg(options::OPT_rewrite_objc) && 01520 ToolForJob->hasIntegratedCPP()) 01521 Inputs = &(*Inputs)[0]->getInputs(); 01522 01523 return ToolForJob; 01524 } 01525 01526 void Driver::BuildJobsForAction(Compilation &C, 01527 const Action *A, 01528 const ToolChain *TC, 01529 const char *BoundArch, 01530 bool AtTopLevel, 01531 bool MultipleArchs, 01532 const char *LinkingOutput, 01533 InputInfo &Result) const { 01534 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 01535 01536 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 01537 // FIXME: It would be nice to not claim this here; maybe the old scheme of 01538 // just using Args was better? 01539 const Arg &Input = IA->getInputArg(); 01540 Input.claim(); 01541 if (Input.getOption().matches(options::OPT_INPUT)) { 01542 const char *Name = Input.getValue(); 01543 Result = InputInfo(Name, A->getType(), Name); 01544 } else 01545 Result = InputInfo(&Input, A->getType(), ""); 01546 return; 01547 } 01548 01549 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 01550 const ToolChain *TC; 01551 const char *ArchName = BAA->getArchName(); 01552 01553 if (ArchName) 01554 TC = &getToolChain(C.getArgs(), ArchName); 01555 else 01556 TC = &C.getDefaultToolChain(); 01557 01558 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), 01559 AtTopLevel, MultipleArchs, LinkingOutput, Result); 01560 return; 01561 } 01562 01563 const ActionList *Inputs = &A->getInputs(); 01564 01565 const JobAction *JA = cast<JobAction>(A); 01566 const Tool *T = SelectToolForJob(C, TC, JA, Inputs); 01567 if (!T) 01568 return; 01569 01570 // Only use pipes when there is exactly one input. 01571 InputInfoList InputInfos; 01572 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 01573 it != ie; ++it) { 01574 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 01575 // shouldn't get temporary output names. 01576 // FIXME: Clean this up. 01577 bool SubJobAtTopLevel = false; 01578 if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A))) 01579 SubJobAtTopLevel = true; 01580 01581 InputInfo II; 01582 BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, 01583 LinkingOutput, II); 01584 InputInfos.push_back(II); 01585 } 01586 01587 // Always use the first input as the base input. 01588 const char *BaseInput = InputInfos[0].getBaseInput(); 01589 01590 // ... except dsymutil actions, which use their actual input as the base 01591 // input. 01592 if (JA->getType() == types::TY_dSYM) 01593 BaseInput = InputInfos[0].getFilename(); 01594 01595 // Determine the place to write output to, if any. 01596 if (JA->getType() == types::TY_Nothing) 01597 Result = InputInfo(A->getType(), BaseInput); 01598 else 01599 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 01600 AtTopLevel, MultipleArchs), 01601 A->getType(), BaseInput); 01602 01603 if (CCCPrintBindings && !CCGenDiagnostics) { 01604 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 01605 << " - \"" << T->getName() << "\", inputs: ["; 01606 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 01607 llvm::errs() << InputInfos[i].getAsString(); 01608 if (i + 1 != e) 01609 llvm::errs() << ", "; 01610 } 01611 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 01612 } else { 01613 T->ConstructJob(C, *JA, Result, InputInfos, 01614 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 01615 } 01616 } 01617 01618 /// \brief Create output filename based on ArgValue, which could either be a 01619 /// full filename, filename without extension, or a directory. If ArgValue 01620 /// does not provide a filename, then use BaseName, and use the extension 01621 /// suitable for FileType. 01622 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 01623 StringRef BaseName, types::ID FileType) { 01624 SmallString<128> Filename = ArgValue; 01625 01626 if (ArgValue.empty()) { 01627 // If the argument is empty, output to BaseName in the current dir. 01628 Filename = BaseName; 01629 } else if (llvm::sys::path::is_separator(Filename.back())) { 01630 // If the argument is a directory, output to BaseName in that dir. 01631 llvm::sys::path::append(Filename, BaseName); 01632 } 01633 01634 if (!llvm::sys::path::has_extension(ArgValue)) { 01635 // If the argument didn't provide an extension, then set it. 01636 const char *Extension = types::getTypeTempSuffix(FileType, true); 01637 01638 if (FileType == types::TY_Image && 01639 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 01640 // The output file is a dll. 01641 Extension = "dll"; 01642 } 01643 01644 llvm::sys::path::replace_extension(Filename, Extension); 01645 } 01646 01647 return Args.MakeArgString(Filename.c_str()); 01648 } 01649 01650 const char *Driver::GetNamedOutputPath(Compilation &C, 01651 const JobAction &JA, 01652 const char *BaseInput, 01653 const char *BoundArch, 01654 bool AtTopLevel, 01655 bool MultipleArchs) const { 01656 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 01657 // Output to a user requested destination? 01658 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && 01659 !isa<VerifyJobAction>(JA)) { 01660 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 01661 return C.addResultFile(FinalOutput->getValue(), &JA); 01662 } 01663 01664 // For /P, preprocess to file named after BaseInput. 01665 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 01666 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 01667 StringRef BaseName = llvm::sys::path::filename(BaseInput); 01668 StringRef NameArg; 01669 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi, 01670 options::OPT__SLASH_o)) 01671 NameArg = A->getValue(); 01672 return C.addResultFile(MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, 01673 types::TY_PP_C), &JA); 01674 } 01675 01676 // Default to writing to stdout? 01677 if (AtTopLevel && !CCGenDiagnostics && 01678 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 01679 return "-"; 01680 01681 // Is this the assembly listing for /FA? 01682 if (JA.getType() == types::TY_PP_Asm && 01683 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 01684 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 01685 // Use /Fa and the input filename to determine the asm file name. 01686 StringRef BaseName = llvm::sys::path::filename(BaseInput); 01687 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 01688 return C.addResultFile(MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, 01689 JA.getType()), &JA); 01690 } 01691 01692 // Output to a temporary file? 01693 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps) && 01694 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 01695 CCGenDiagnostics) { 01696 StringRef Name = llvm::sys::path::filename(BaseInput); 01697 std::pair<StringRef, StringRef> Split = Name.split('.'); 01698 std::string TmpName = 01699 GetTemporaryPath(Split.first, 01700 types::getTypeTempSuffix(JA.getType(), IsCLMode())); 01701 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 01702 } 01703 01704 SmallString<128> BasePath(BaseInput); 01705 StringRef BaseName; 01706 01707 // Dsymutil actions should use the full path. 01708 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 01709 BaseName = BasePath; 01710 else 01711 BaseName = llvm::sys::path::filename(BasePath); 01712 01713 // Determine what the derived output name should be. 01714 const char *NamedOutput; 01715 01716 if (JA.getType() == types::TY_Object && 01717 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 01718 // The /Fo or /o flag decides the object filename. 01719 StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fo, 01720 options::OPT__SLASH_o)->getValue(); 01721 NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName, 01722 types::TY_Object); 01723 } else if (JA.getType() == types::TY_Image && 01724 C.getArgs().hasArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)) { 01725 // The /Fe or /o flag names the linked file. 01726 StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fe, 01727 options::OPT__SLASH_o)->getValue(); 01728 NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName, 01729 types::TY_Image); 01730 } else if (JA.getType() == types::TY_Image) { 01731 if (IsCLMode()) { 01732 // clang-cl uses BaseName for the executable name. 01733 NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName, 01734 types::TY_Image); 01735 } else if (MultipleArchs && BoundArch) { 01736 SmallString<128> Output(DefaultImageName.c_str()); 01737 Output += "-"; 01738 Output.append(BoundArch); 01739 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 01740 } else 01741 NamedOutput = DefaultImageName.c_str(); 01742 } else { 01743 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 01744 assert(Suffix && "All types used for output should have a suffix."); 01745 01746 std::string::size_type End = std::string::npos; 01747 if (!types::appendSuffixForType(JA.getType())) 01748 End = BaseName.rfind('.'); 01749 SmallString<128> Suffixed(BaseName.substr(0, End)); 01750 if (MultipleArchs && BoundArch) { 01751 Suffixed += "-"; 01752 Suffixed.append(BoundArch); 01753 } 01754 Suffixed += '.'; 01755 Suffixed += Suffix; 01756 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 01757 } 01758 01759 // If we're saving temps and the temp file conflicts with the input file, 01760 // then avoid overwriting input file. 01761 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && 01762 NamedOutput == BaseName) { 01763 01764 bool SameFile = false; 01765 SmallString<256> Result; 01766 llvm::sys::fs::current_path(Result); 01767 llvm::sys::path::append(Result, BaseName); 01768 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 01769 // Must share the same path to conflict. 01770 if (SameFile) { 01771 StringRef Name = llvm::sys::path::filename(BaseInput); 01772 std::pair<StringRef, StringRef> Split = Name.split('.'); 01773 std::string TmpName = 01774 GetTemporaryPath(Split.first, 01775 types::getTypeTempSuffix(JA.getType(), IsCLMode())); 01776 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 01777 } 01778 } 01779 01780 // As an annoying special case, PCH generation doesn't strip the pathname. 01781 if (JA.getType() == types::TY_PCH) { 01782 llvm::sys::path::remove_filename(BasePath); 01783 if (BasePath.empty()) 01784 BasePath = NamedOutput; 01785 else 01786 llvm::sys::path::append(BasePath, NamedOutput); 01787 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 01788 } else { 01789 return C.addResultFile(NamedOutput, &JA); 01790 } 01791 } 01792 01793 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 01794 // Respect a limited subset of the '-Bprefix' functionality in GCC by 01795 // attempting to use this prefix when looking for file paths. 01796 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 01797 ie = PrefixDirs.end(); it != ie; ++it) { 01798 std::string Dir(*it); 01799 if (Dir.empty()) 01800 continue; 01801 if (Dir[0] == '=') 01802 Dir = SysRoot + Dir.substr(1); 01803 SmallString<128> P(Dir); 01804 llvm::sys::path::append(P, Name); 01805 if (llvm::sys::fs::exists(Twine(P))) 01806 return P.str(); 01807 } 01808 01809 SmallString<128> P(ResourceDir); 01810 llvm::sys::path::append(P, Name); 01811 if (llvm::sys::fs::exists(Twine(P))) 01812 return P.str(); 01813 01814 const ToolChain::path_list &List = TC.getFilePaths(); 01815 for (ToolChain::path_list::const_iterator 01816 it = List.begin(), ie = List.end(); it != ie; ++it) { 01817 std::string Dir(*it); 01818 if (Dir.empty()) 01819 continue; 01820 if (Dir[0] == '=') 01821 Dir = SysRoot + Dir.substr(1); 01822 SmallString<128> P(Dir); 01823 llvm::sys::path::append(P, Name); 01824 if (llvm::sys::fs::exists(Twine(P))) 01825 return P.str(); 01826 } 01827 01828 return Name; 01829 } 01830 01831 void 01832 Driver::generatePrefixedToolNames(const char *Tool, const ToolChain &TC, 01833 SmallVectorImpl<std::string> &Names) const { 01834 // FIXME: Needs a better variable than DefaultTargetTriple 01835 Names.push_back(DefaultTargetTriple + "-" + Tool); 01836 Names.push_back(Tool); 01837 } 01838 01839 static bool ScanDirForExecutable(SmallString<128> &Dir, 01840 ArrayRef<std::string> Names) { 01841 for (const auto &Name : Names) { 01842 llvm::sys::path::append(Dir, Name); 01843 if (llvm::sys::fs::can_execute(Twine(Dir))) 01844 return true; 01845 llvm::sys::path::remove_filename(Dir); 01846 } 01847 return false; 01848 } 01849 01850 std::string Driver::GetProgramPath(const char *Name, 01851 const ToolChain &TC) const { 01852 SmallVector<std::string, 2> TargetSpecificExecutables; 01853 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 01854 01855 // Respect a limited subset of the '-Bprefix' functionality in GCC by 01856 // attempting to use this prefix when looking for program paths. 01857 for (const auto &PrefixDir : PrefixDirs) { 01858 if (llvm::sys::fs::is_directory(PrefixDir)) { 01859 SmallString<128> P(PrefixDir); 01860 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 01861 return P.str(); 01862 } else { 01863 SmallString<128> P(PrefixDir + Name); 01864 if (llvm::sys::fs::can_execute(Twine(P))) 01865 return P.str(); 01866 } 01867 } 01868 01869 const ToolChain::path_list &List = TC.getProgramPaths(); 01870 for (const auto &Path : List) { 01871 SmallString<128> P(Path); 01872 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 01873 return P.str(); 01874 } 01875 01876 // If all else failed, search the path. 01877 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) 01878 if (llvm::ErrorOr<std::string> P = 01879 llvm::sys::findProgramByName(TargetSpecificExecutable)) 01880 return *P; 01881 01882 return Name; 01883 } 01884 01885 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) 01886 const { 01887 SmallString<128> Path; 01888 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 01889 if (EC) { 01890 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 01891 return ""; 01892 } 01893 01894 return Path.str(); 01895 } 01896 01897 /// \brief Compute target triple from args. 01898 /// 01899 /// This routine provides the logic to compute a target triple from various 01900 /// args passed to the driver and the default triple string. 01901 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple, 01902 const ArgList &Args, 01903 StringRef DarwinArchName) { 01904 // FIXME: Already done in Compilation *Driver::BuildCompilation 01905 if (const Arg *A = Args.getLastArg(options::OPT_target)) 01906 DefaultTargetTriple = A->getValue(); 01907 01908 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 01909 01910 // Handle Apple-specific options available here. 01911 if (Target.isOSBinFormatMachO()) { 01912 // If an explict Darwin arch name is given, that trumps all. 01913 if (!DarwinArchName.empty()) { 01914 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName); 01915 return Target; 01916 } 01917 01918 // Handle the Darwin '-arch' flag. 01919 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 01920 StringRef ArchName = A->getValue(); 01921 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName); 01922 } 01923 } 01924 01925 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 01926 // '-mbig-endian'/'-EB'. 01927 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 01928 options::OPT_mbig_endian)) { 01929 if (A->getOption().matches(options::OPT_mlittle_endian)) { 01930 if (Target.getArch() == llvm::Triple::mips) 01931 Target.setArch(llvm::Triple::mipsel); 01932 else if (Target.getArch() == llvm::Triple::mips64) 01933 Target.setArch(llvm::Triple::mips64el); 01934 else if (Target.getArch() == llvm::Triple::aarch64_be) 01935 Target.setArch(llvm::Triple::aarch64); 01936 } else { 01937 if (Target.getArch() == llvm::Triple::mipsel) 01938 Target.setArch(llvm::Triple::mips); 01939 else if (Target.getArch() == llvm::Triple::mips64el) 01940 Target.setArch(llvm::Triple::mips64); 01941 else if (Target.getArch() == llvm::Triple::aarch64) 01942 Target.setArch(llvm::Triple::aarch64_be); 01943 } 01944 } 01945 01946 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 01947 if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix) 01948 return Target; 01949 01950 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 01951 if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 01952 options::OPT_m32, options::OPT_m16)) { 01953 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 01954 01955 if (A->getOption().matches(options::OPT_m64)) { 01956 AT = Target.get64BitArchVariant().getArch(); 01957 if (Target.getEnvironment() == llvm::Triple::GNUX32) 01958 Target.setEnvironment(llvm::Triple::GNU); 01959 } else if (A->getOption().matches(options::OPT_mx32) && 01960 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 01961 AT = llvm::Triple::x86_64; 01962 Target.setEnvironment(llvm::Triple::GNUX32); 01963 } else if (A->getOption().matches(options::OPT_m32)) { 01964 AT = Target.get32BitArchVariant().getArch(); 01965 if (Target.getEnvironment() == llvm::Triple::GNUX32) 01966 Target.setEnvironment(llvm::Triple::GNU); 01967 } else if (A->getOption().matches(options::OPT_m16) && 01968 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 01969 AT = llvm::Triple::x86; 01970 Target.setEnvironment(llvm::Triple::CODE16); 01971 } 01972 01973 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 01974 Target.setArch(AT); 01975 } 01976 01977 return Target; 01978 } 01979 01980 const ToolChain &Driver::getToolChain(const ArgList &Args, 01981 StringRef DarwinArchName) const { 01982 llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args, 01983 DarwinArchName); 01984 01985 ToolChain *&TC = ToolChains[Target.str()]; 01986 if (!TC) { 01987 switch (Target.getOS()) { 01988 case llvm::Triple::Darwin: 01989 case llvm::Triple::MacOSX: 01990 case llvm::Triple::IOS: 01991 TC = new toolchains::DarwinClang(*this, Target, Args); 01992 break; 01993 case llvm::Triple::DragonFly: 01994 TC = new toolchains::DragonFly(*this, Target, Args); 01995 break; 01996 case llvm::Triple::OpenBSD: 01997 TC = new toolchains::OpenBSD(*this, Target, Args); 01998 break; 01999 case llvm::Triple::Bitrig: 02000 TC = new toolchains::Bitrig(*this, Target, Args); 02001 break; 02002 case llvm::Triple::NetBSD: 02003 TC = new toolchains::NetBSD(*this, Target, Args); 02004 break; 02005 case llvm::Triple::FreeBSD: 02006 TC = new toolchains::FreeBSD(*this, Target, Args); 02007 break; 02008 case llvm::Triple::Minix: 02009 TC = new toolchains::Minix(*this, Target, Args); 02010 break; 02011 case llvm::Triple::Linux: 02012 if (Target.getArch() == llvm::Triple::hexagon) 02013 TC = new toolchains::Hexagon_TC(*this, Target, Args); 02014 else 02015 TC = new toolchains::Linux(*this, Target, Args); 02016 break; 02017 case llvm::Triple::Solaris: 02018 TC = new toolchains::Solaris(*this, Target, Args); 02019 break; 02020 case llvm::Triple::Win32: 02021 switch (Target.getEnvironment()) { 02022 default: 02023 if (Target.isOSBinFormatELF()) 02024 TC = new toolchains::Generic_ELF(*this, Target, Args); 02025 else if (Target.isOSBinFormatMachO()) 02026 TC = new toolchains::MachO(*this, Target, Args); 02027 else 02028 TC = new toolchains::Generic_GCC(*this, Target, Args); 02029 break; 02030 case llvm::Triple::GNU: 02031 // FIXME: We need a MinGW toolchain. Use the default Generic_GCC 02032 // toolchain for now as the default case would below otherwise. 02033 if (Target.isOSBinFormatELF()) 02034 TC = new toolchains::Generic_ELF(*this, Target, Args); 02035 else 02036 TC = new toolchains::Generic_GCC(*this, Target, Args); 02037 break; 02038 case llvm::Triple::Itanium: 02039 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args); 02040 break; 02041 case llvm::Triple::MSVC: 02042 case llvm::Triple::UnknownEnvironment: 02043 TC = new toolchains::MSVCToolChain(*this, Target, Args); 02044 break; 02045 } 02046 break; 02047 default: 02048 // TCE is an OSless target 02049 if (Target.getArchName() == "tce") { 02050 TC = new toolchains::TCEToolChain(*this, Target, Args); 02051 break; 02052 } 02053 // If Hexagon is configured as an OSless target 02054 if (Target.getArch() == llvm::Triple::hexagon) { 02055 TC = new toolchains::Hexagon_TC(*this, Target, Args); 02056 break; 02057 } 02058 if (Target.getArch() == llvm::Triple::xcore) { 02059 TC = new toolchains::XCore(*this, Target, Args); 02060 break; 02061 } 02062 if (Target.isOSBinFormatELF()) { 02063 TC = new toolchains::Generic_ELF(*this, Target, Args); 02064 break; 02065 } 02066 if (Target.getObjectFormat() == llvm::Triple::MachO) { 02067 TC = new toolchains::MachO(*this, Target, Args); 02068 break; 02069 } 02070 TC = new toolchains::Generic_GCC(*this, Target, Args); 02071 break; 02072 } 02073 } 02074 return *TC; 02075 } 02076 02077 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 02078 // Check if user requested no clang, or clang doesn't understand this type (we 02079 // only handle single inputs for now). 02080 if (JA.size() != 1 || 02081 !types::isAcceptedByClang((*JA.begin())->getType())) 02082 return false; 02083 02084 // Otherwise make sure this is an action clang understands. 02085 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 02086 !isa<CompileJobAction>(JA)) 02087 return false; 02088 02089 return true; 02090 } 02091 02092 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 02093 /// grouped values as integers. Numbers which are not provided are set to 0. 02094 /// 02095 /// \return True if the entire string was parsed (9.2), or all groups were 02096 /// parsed (10.3.5extrastuff). 02097 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 02098 unsigned &Minor, unsigned &Micro, 02099 bool &HadExtra) { 02100 HadExtra = false; 02101 02102 Major = Minor = Micro = 0; 02103 if (*Str == '\0') 02104 return true; 02105 02106 char *End; 02107 Major = (unsigned) strtol(Str, &End, 10); 02108 if (*Str != '\0' && *End == '\0') 02109 return true; 02110 if (*End != '.') 02111 return false; 02112 02113 Str = End+1; 02114 Minor = (unsigned) strtol(Str, &End, 10); 02115 if (*Str != '\0' && *End == '\0') 02116 return true; 02117 if (*End != '.') 02118 return false; 02119 02120 Str = End+1; 02121 Micro = (unsigned) strtol(Str, &End, 10); 02122 if (*Str != '\0' && *End == '\0') 02123 return true; 02124 if (Str == End) 02125 return false; 02126 HadExtra = true; 02127 return true; 02128 } 02129 02130 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const { 02131 unsigned IncludedFlagsBitmask = 0; 02132 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 02133 02134 if (Mode == CLMode) { 02135 // Include CL and Core options. 02136 IncludedFlagsBitmask |= options::CLOption; 02137 IncludedFlagsBitmask |= options::CoreOption; 02138 } else { 02139 ExcludedFlagsBitmask |= options::CLOption; 02140 } 02141 02142 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 02143 } 02144 02145 bool clang::driver::isOptimizationLevelFast(const llvm::opt::ArgList &Args) { 02146 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 02147 }