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