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