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