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/AMDGPU.h" 13 #include "ToolChains/AVR.h" 14 #include "ToolChains/Ananas.h" 15 #include "ToolChains/Bitrig.h" 16 #include "ToolChains/Clang.h" 17 #include "ToolChains/CloudABI.h" 18 #include "ToolChains/Contiki.h" 19 #include "ToolChains/CrossWindows.h" 20 #include "ToolChains/Cuda.h" 21 #include "ToolChains/Darwin.h" 22 #include "ToolChains/DragonFly.h" 23 #include "ToolChains/FreeBSD.h" 24 #include "ToolChains/Fuchsia.h" 25 #include "ToolChains/Gnu.h" 26 #include "ToolChains/BareMetal.h" 27 #include "ToolChains/Haiku.h" 28 #include "ToolChains/Hexagon.h" 29 #include "ToolChains/Lanai.h" 30 #include "ToolChains/Linux.h" 31 #include "ToolChains/MinGW.h" 32 #include "ToolChains/Minix.h" 33 #include "ToolChains/MipsLinux.h" 34 #include "ToolChains/MSVC.h" 35 #include "ToolChains/Myriad.h" 36 #include "ToolChains/NaCl.h" 37 #include "ToolChains/NetBSD.h" 38 #include "ToolChains/OpenBSD.h" 39 #include "ToolChains/PS4CPU.h" 40 #include "ToolChains/Solaris.h" 41 #include "ToolChains/TCE.h" 42 #include "ToolChains/WebAssembly.h" 43 #include "ToolChains/XCore.h" 44 #include "clang/Basic/Version.h" 45 #include "clang/Basic/VirtualFileSystem.h" 46 #include "clang/Config/config.h" 47 #include "clang/Driver/Action.h" 48 #include "clang/Driver/Compilation.h" 49 #include "clang/Driver/DriverDiagnostic.h" 50 #include "clang/Driver/Job.h" 51 #include "clang/Driver/Options.h" 52 #include "clang/Driver/SanitizerArgs.h" 53 #include "clang/Driver/Tool.h" 54 #include "clang/Driver/ToolChain.h" 55 #include "llvm/ADT/ArrayRef.h" 56 #include "llvm/ADT/STLExtras.h" 57 #include "llvm/ADT/SmallSet.h" 58 #include "llvm/ADT/StringExtras.h" 59 #include "llvm/ADT/StringSet.h" 60 #include "llvm/ADT/StringSwitch.h" 61 #include "llvm/Option/Arg.h" 62 #include "llvm/Option/ArgList.h" 63 #include "llvm/Option/OptSpecifier.h" 64 #include "llvm/Option/OptTable.h" 65 #include "llvm/Option/Option.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/FileSystem.h" 68 #include "llvm/Support/Path.h" 69 #include "llvm/Support/PrettyStackTrace.h" 70 #include "llvm/Support/Process.h" 71 #include "llvm/Support/Program.h" 72 #include "llvm/Support/TargetRegistry.h" 73 #include "llvm/Support/raw_ostream.h" 74 #include <map> 75 #include <memory> 76 #include <utility> 77 #if LLVM_ON_UNIX 78 #include <unistd.h> // getpid 79 #endif 80 81 using namespace clang::driver; 82 using namespace clang; 83 using namespace llvm::opt; 84 85 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple, 86 DiagnosticsEngine &Diags, 87 IntrusiveRefCntPtr<vfs::FileSystem> VFS) 88 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)), 89 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 90 LTOMode(LTOK_None), ClangExecutable(ClangExecutable), 91 SysRoot(DEFAULT_SYSROOT), UseStdLib(true), 92 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr), 93 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr), 94 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false), 95 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple), 96 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true), 97 GenReproducer(false), SuppressMissingInputWarning(false) { 98 99 // Provide a sane fallback if no VFS is specified. 100 if (!this->VFS) 101 this->VFS = vfs::getRealFileSystem(); 102 103 Name = llvm::sys::path::filename(ClangExecutable); 104 Dir = llvm::sys::path::parent_path(ClangExecutable); 105 InstalledDir = Dir; // Provide a sensible default installed dir. 106 107 // Compute the path to the resource directory. 108 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 109 SmallString<128> P(Dir); 110 if (ClangResourceDir != "") { 111 llvm::sys::path::append(P, ClangResourceDir); 112 } else { 113 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX); 114 P = llvm::sys::path::parent_path(Dir); 115 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang", 116 CLANG_VERSION_STRING); 117 } 118 ResourceDir = P.str(); 119 } 120 121 void Driver::ParseDriverMode(StringRef ProgramName, 122 ArrayRef<const char *> Args) { 123 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName); 124 StringRef DefaultMode(Default.second); 125 setDriverModeFromOption(DefaultMode); 126 127 for (const char *ArgPtr : Args) { 128 // Ingore nullptrs, they are response file's EOL markers 129 if (ArgPtr == nullptr) 130 continue; 131 const StringRef Arg = ArgPtr; 132 setDriverModeFromOption(Arg); 133 } 134 } 135 136 void Driver::setDriverModeFromOption(StringRef Opt) { 137 const std::string OptName = 138 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 139 if (!Opt.startswith(OptName)) 140 return; 141 StringRef Value = Opt.drop_front(OptName.size()); 142 143 const unsigned M = llvm::StringSwitch<unsigned>(Value) 144 .Case("gcc", GCCMode) 145 .Case("g++", GXXMode) 146 .Case("cpp", CPPMode) 147 .Case("cl", CLMode) 148 .Default(~0U); 149 150 if (M != ~0U) 151 Mode = static_cast<DriverMode>(M); 152 else 153 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 154 } 155 156 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, 157 bool &ContainsError) { 158 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 159 ContainsError = false; 160 161 unsigned IncludedFlagsBitmask; 162 unsigned ExcludedFlagsBitmask; 163 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 164 getIncludeExcludeOptionFlagMasks(); 165 166 unsigned MissingArgIndex, MissingArgCount; 167 InputArgList Args = 168 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 169 IncludedFlagsBitmask, ExcludedFlagsBitmask); 170 171 // Check for missing argument error. 172 if (MissingArgCount) { 173 Diag(diag::err_drv_missing_argument) 174 << Args.getArgString(MissingArgIndex) << MissingArgCount; 175 ContainsError |= 176 Diags.getDiagnosticLevel(diag::err_drv_missing_argument, 177 SourceLocation()) > DiagnosticsEngine::Warning; 178 } 179 180 // Check for unsupported options. 181 for (const Arg *A : Args) { 182 if (A->getOption().hasFlag(options::Unsupported)) { 183 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args); 184 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt, 185 SourceLocation()) > 186 DiagnosticsEngine::Warning; 187 continue; 188 } 189 190 // Warn about -mcpu= without an argument. 191 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 192 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 193 ContainsError |= Diags.getDiagnosticLevel( 194 diag::warn_drv_empty_joined_argument, 195 SourceLocation()) > DiagnosticsEngine::Warning; 196 } 197 } 198 199 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) { 200 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl 201 : diag::err_drv_unknown_argument; 202 203 Diags.Report(ID) << A->getAsString(Args); 204 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) > 205 DiagnosticsEngine::Warning; 206 } 207 208 return Args; 209 } 210 211 // Determine which compilation mode we are in. We look for options which 212 // affect the phase, starting with the earliest phases, and record which 213 // option we used to determine the final phase. 214 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 215 Arg **FinalPhaseArg) const { 216 Arg *PhaseArg = nullptr; 217 phases::ID FinalPhase; 218 219 // -{E,EP,P,M,MM} only run the preprocessor. 220 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 221 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 222 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 223 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) { 224 FinalPhase = phases::Preprocess; 225 226 // --precompile only runs up to precompilation. 227 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) { 228 FinalPhase = phases::Precompile; 229 230 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 231 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 232 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 233 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 235 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 236 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 237 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 238 options::OPT__analyze_auto)) || 239 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 240 FinalPhase = phases::Compile; 241 242 // -S only runs up to the backend. 243 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 244 FinalPhase = phases::Backend; 245 246 // -c compilation only runs up to the assembler. 247 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 248 FinalPhase = phases::Assemble; 249 250 // Otherwise do everything. 251 } else 252 FinalPhase = phases::Link; 253 254 if (FinalPhaseArg) 255 *FinalPhaseArg = PhaseArg; 256 257 return FinalPhase; 258 } 259 260 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts, 261 StringRef Value) { 262 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value, 263 Args.getBaseArgs().MakeIndex(Value), Value.data()); 264 Args.AddSynthesizedArg(A); 265 A->claim(); 266 return A; 267 } 268 269 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 270 DerivedArgList *DAL = new DerivedArgList(Args); 271 272 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 273 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 274 for (Arg *A : Args) { 275 // Unfortunately, we have to parse some forwarding options (-Xassembler, 276 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 277 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 278 279 // Rewrite linker options, to replace --no-demangle with a custom internal 280 // option. 281 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 282 A->getOption().matches(options::OPT_Xlinker)) && 283 A->containsValue("--no-demangle")) { 284 // Add the rewritten no-demangle argument. 285 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 286 287 // Add the remaining values as Xlinker arguments. 288 for (StringRef Val : A->getValues()) 289 if (Val != "--no-demangle") 290 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val); 291 292 continue; 293 } 294 295 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 296 // some build systems. We don't try to be complete here because we don't 297 // care to encourage this usage model. 298 if (A->getOption().matches(options::OPT_Wp_COMMA) && 299 (A->getValue(0) == StringRef("-MD") || 300 A->getValue(0) == StringRef("-MMD"))) { 301 // Rewrite to -MD/-MMD along with -MF. 302 if (A->getValue(0) == StringRef("-MD")) 303 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 304 else 305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 306 if (A->getNumValues() == 2) 307 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 308 A->getValue(1)); 309 continue; 310 } 311 312 // Rewrite reserved library names. 313 if (A->getOption().matches(options::OPT_l)) { 314 StringRef Value = A->getValue(); 315 316 // Rewrite unless -nostdlib is present. 317 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") { 318 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx)); 319 continue; 320 } 321 322 // Rewrite unconditionally. 323 if (Value == "cc_kext") { 324 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext)); 325 continue; 326 } 327 } 328 329 // Pick up inputs via the -- option. 330 if (A->getOption().matches(options::OPT__DASH_DASH)) { 331 A->claim(); 332 for (StringRef Val : A->getValues()) 333 DAL->append(MakeInputArg(*DAL, *Opts, Val)); 334 continue; 335 } 336 337 DAL->append(A); 338 } 339 340 // Enforce -static if -miamcu is present. 341 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) 342 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static)); 343 344 // Add a default value of -mlinker-version=, if one was given and the user 345 // didn't specify one. 346 #if defined(HOST_LINK_VERSION) 347 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 348 strlen(HOST_LINK_VERSION) > 0) { 349 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 350 HOST_LINK_VERSION); 351 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 352 } 353 #endif 354 355 return DAL; 356 } 357 358 /// \brief Compute target triple from args. 359 /// 360 /// This routine provides the logic to compute a target triple from various 361 /// args passed to the driver and the default triple string. 362 static llvm::Triple computeTargetTriple(const Driver &D, 363 StringRef DefaultTargetTriple, 364 const ArgList &Args, 365 StringRef DarwinArchName = "") { 366 // FIXME: Already done in Compilation *Driver::BuildCompilation 367 if (const Arg *A = Args.getLastArg(options::OPT_target)) 368 DefaultTargetTriple = A->getValue(); 369 370 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 371 372 // Handle Apple-specific options available here. 373 if (Target.isOSBinFormatMachO()) { 374 // If an explict Darwin arch name is given, that trumps all. 375 if (!DarwinArchName.empty()) { 376 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName); 377 return Target; 378 } 379 380 // Handle the Darwin '-arch' flag. 381 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 382 StringRef ArchName = A->getValue(); 383 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName); 384 } 385 } 386 387 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 388 // '-mbig-endian'/'-EB'. 389 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 390 options::OPT_mbig_endian)) { 391 if (A->getOption().matches(options::OPT_mlittle_endian)) { 392 llvm::Triple LE = Target.getLittleEndianArchVariant(); 393 if (LE.getArch() != llvm::Triple::UnknownArch) 394 Target = std::move(LE); 395 } else { 396 llvm::Triple BE = Target.getBigEndianArchVariant(); 397 if (BE.getArch() != llvm::Triple::UnknownArch) 398 Target = std::move(BE); 399 } 400 } 401 402 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 403 if (Target.getArch() == llvm::Triple::tce || 404 Target.getOS() == llvm::Triple::Minix) 405 return Target; 406 407 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 408 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 409 options::OPT_m32, options::OPT_m16); 410 if (A) { 411 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 412 413 if (A->getOption().matches(options::OPT_m64)) { 414 AT = Target.get64BitArchVariant().getArch(); 415 if (Target.getEnvironment() == llvm::Triple::GNUX32) 416 Target.setEnvironment(llvm::Triple::GNU); 417 } else if (A->getOption().matches(options::OPT_mx32) && 418 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 419 AT = llvm::Triple::x86_64; 420 Target.setEnvironment(llvm::Triple::GNUX32); 421 } else if (A->getOption().matches(options::OPT_m32)) { 422 AT = Target.get32BitArchVariant().getArch(); 423 if (Target.getEnvironment() == llvm::Triple::GNUX32) 424 Target.setEnvironment(llvm::Triple::GNU); 425 } else if (A->getOption().matches(options::OPT_m16) && 426 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 427 AT = llvm::Triple::x86; 428 Target.setEnvironment(llvm::Triple::CODE16); 429 } 430 431 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 432 Target.setArch(AT); 433 } 434 435 // Handle -miamcu flag. 436 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 437 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 438 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 439 << Target.str(); 440 441 if (A && !A->getOption().matches(options::OPT_m32)) 442 D.Diag(diag::err_drv_argument_not_allowed_with) 443 << "-miamcu" << A->getBaseArg().getAsString(Args); 444 445 Target.setArch(llvm::Triple::x86); 446 Target.setArchName("i586"); 447 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 448 Target.setEnvironmentName(""); 449 Target.setOS(llvm::Triple::ELFIAMCU); 450 Target.setVendor(llvm::Triple::UnknownVendor); 451 Target.setVendorName("intel"); 452 } 453 454 return Target; 455 } 456 457 // \brief Parse the LTO options and record the type of LTO compilation 458 // based on which -f(no-)?lto(=.*)? option occurs last. 459 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 460 LTOMode = LTOK_None; 461 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ, 462 options::OPT_fno_lto, false)) 463 return; 464 465 StringRef LTOName("full"); 466 467 const Arg *A = Args.getLastArg(options::OPT_flto_EQ); 468 if (A) 469 LTOName = A->getValue(); 470 471 LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 472 .Case("full", LTOK_Full) 473 .Case("thin", LTOK_Thin) 474 .Default(LTOK_Unknown); 475 476 if (LTOMode == LTOK_Unknown) { 477 assert(A); 478 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName() 479 << A->getValue(); 480 } 481 } 482 483 /// Compute the desired OpenMP runtime from the flags provided. 484 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const { 485 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME); 486 487 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ); 488 if (A) 489 RuntimeName = A->getValue(); 490 491 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName) 492 .Case("libomp", OMPRT_OMP) 493 .Case("libgomp", OMPRT_GOMP) 494 .Case("libiomp5", OMPRT_IOMP5) 495 .Default(OMPRT_Unknown); 496 497 if (RT == OMPRT_Unknown) { 498 if (A) 499 Diag(diag::err_drv_unsupported_option_argument) 500 << A->getOption().getName() << A->getValue(); 501 else 502 // FIXME: We could use a nicer diagnostic here. 503 Diag(diag::err_drv_unsupported_opt) << "-fopenmp"; 504 } 505 506 return RT; 507 } 508 509 void Driver::CreateOffloadingDeviceToolChains(Compilation &C, 510 InputList &Inputs) { 511 512 // 513 // CUDA 514 // 515 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type. 516 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 517 return types::isCuda(I.first); 518 })) { 519 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 520 const llvm::Triple &HostTriple = HostTC->getTriple(); 521 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" 522 : "nvptx-nvidia-cuda"); 523 // Use the CUDA and host triples as the key into the ToolChains map, because 524 // the device toolchain we create depends on both. 525 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()]; 526 if (!CudaTC) { 527 CudaTC = llvm::make_unique<toolchains::CudaToolChain>( 528 *this, CudaTriple, *HostTC, C.getInputArgs()); 529 } 530 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda); 531 } 532 533 // 534 // OpenMP 535 // 536 // We need to generate an OpenMP toolchain if the user specified targets with 537 // the -fopenmp-targets option. 538 if (Arg *OpenMPTargets = 539 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) { 540 if (OpenMPTargets->getNumValues()) { 541 // We expect that -fopenmp-targets is always used in conjunction with the 542 // option -fopenmp specifying a valid runtime with offloading support, 543 // i.e. libomp or libiomp. 544 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag( 545 options::OPT_fopenmp, options::OPT_fopenmp_EQ, 546 options::OPT_fno_openmp, false); 547 if (HasValidOpenMPRuntime) { 548 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs()); 549 HasValidOpenMPRuntime = 550 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5; 551 } 552 553 if (HasValidOpenMPRuntime) { 554 llvm::StringMap<const char *> FoundNormalizedTriples; 555 for (const char *Val : OpenMPTargets->getValues()) { 556 llvm::Triple TT(Val); 557 std::string NormalizedName = TT.normalize(); 558 559 // Make sure we don't have a duplicate triple. 560 auto Duplicate = FoundNormalizedTriples.find(NormalizedName); 561 if (Duplicate != FoundNormalizedTriples.end()) { 562 Diag(clang::diag::warn_drv_omp_offload_target_duplicate) 563 << Val << Duplicate->second; 564 continue; 565 } 566 567 // Store the current triple so that we can check for duplicates in the 568 // following iterations. 569 FoundNormalizedTriples[NormalizedName] = Val; 570 571 // If the specified target is invalid, emit a diagnostic. 572 if (TT.getArch() == llvm::Triple::UnknownArch) 573 Diag(clang::diag::err_drv_invalid_omp_target) << Val; 574 else { 575 const ToolChain &TC = getToolChain(C.getInputArgs(), TT); 576 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP); 577 } 578 } 579 } else 580 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); 581 } else 582 Diag(clang::diag::warn_drv_empty_joined_argument) 583 << OpenMPTargets->getAsString(C.getInputArgs()); 584 } 585 586 // 587 // TODO: Add support for other offloading programming models here. 588 // 589 590 return; 591 } 592 593 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 594 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 595 596 // FIXME: Handle environment options which affect driver behavior, somewhere 597 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 598 599 if (Optional<std::string> CompilerPathValue = 600 llvm::sys::Process::GetEnv("COMPILER_PATH")) { 601 StringRef CompilerPath = *CompilerPathValue; 602 while (!CompilerPath.empty()) { 603 std::pair<StringRef, StringRef> Split = 604 CompilerPath.split(llvm::sys::EnvPathSeparator); 605 PrefixDirs.push_back(Split.first); 606 CompilerPath = Split.second; 607 } 608 } 609 610 // We look for the driver mode option early, because the mode can affect 611 // how other options are parsed. 612 ParseDriverMode(ClangExecutable, ArgList.slice(1)); 613 614 // FIXME: What are we going to do with -V and -b? 615 616 // FIXME: This stuff needs to go into the Compilation, not the driver. 617 bool CCCPrintPhases; 618 619 bool ContainsError; 620 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError); 621 622 // Silence driver warnings if requested 623 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w)); 624 625 // -no-canonical-prefixes is used very early in main. 626 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 627 628 // Ignore -pipe. 629 Args.ClaimAllArgs(options::OPT_pipe); 630 631 // Extract -ccc args. 632 // 633 // FIXME: We need to figure out where this behavior should live. Most of it 634 // should be outside in the client; the parts that aren't should have proper 635 // options, either by introducing new ones or by overloading gcc ones like -V 636 // or -b. 637 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 638 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 639 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 640 CCCGenericGCCName = A->getValue(); 641 CCCUsePCH = 642 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth); 643 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer, 644 options::OPT_fno_crash_diagnostics, 645 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")); 646 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 647 // and getToolChain is const. 648 if (IsCLMode()) { 649 // clang-cl targets MSVC-style Win32. 650 llvm::Triple T(DefaultTargetTriple); 651 T.setOS(llvm::Triple::Win32); 652 T.setVendor(llvm::Triple::PC); 653 T.setEnvironment(llvm::Triple::MSVC); 654 DefaultTargetTriple = T.str(); 655 } 656 if (const Arg *A = Args.getLastArg(options::OPT_target)) 657 DefaultTargetTriple = A->getValue(); 658 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 659 Dir = InstalledDir = A->getValue(); 660 for (const Arg *A : Args.filtered(options::OPT_B)) { 661 A->claim(); 662 PrefixDirs.push_back(A->getValue(0)); 663 } 664 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 665 SysRoot = A->getValue(); 666 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 667 DyldPrefix = A->getValue(); 668 if (Args.hasArg(options::OPT_nostdlib)) 669 UseStdLib = false; 670 671 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 672 ResourceDir = A->getValue(); 673 674 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 675 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 676 .Case("cwd", SaveTempsCwd) 677 .Case("obj", SaveTempsObj) 678 .Default(SaveTempsCwd); 679 } 680 681 setLTOMode(Args); 682 683 // Process -fembed-bitcode= flags. 684 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 685 StringRef Name = A->getValue(); 686 unsigned Model = llvm::StringSwitch<unsigned>(Name) 687 .Case("off", EmbedNone) 688 .Case("all", EmbedBitcode) 689 .Case("bitcode", EmbedBitcode) 690 .Case("marker", EmbedMarker) 691 .Default(~0U); 692 if (Model == ~0U) { 693 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 694 << Name; 695 } else 696 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 697 } 698 699 std::unique_ptr<llvm::opt::InputArgList> UArgs = 700 llvm::make_unique<InputArgList>(std::move(Args)); 701 702 // Perform the default argument translations. 703 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 704 705 // Owned by the host. 706 const ToolChain &TC = getToolChain( 707 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs)); 708 709 // The compilation takes ownership of Args. 710 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, 711 ContainsError); 712 713 if (!HandleImmediateArgs(*C)) 714 return C; 715 716 // Construct the list of inputs. 717 InputList Inputs; 718 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 719 720 // Populate the tool chains for the offloading devices, if any. 721 CreateOffloadingDeviceToolChains(*C, Inputs); 722 723 // Construct the list of abstract actions to perform for this compilation. On 724 // MachO targets this uses the driver-driver and universal actions. 725 if (TC.getTriple().isOSBinFormatMachO()) 726 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 727 else 728 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 729 730 if (CCCPrintPhases) { 731 PrintActions(*C); 732 return C; 733 } 734 735 BuildJobs(*C); 736 737 return C; 738 } 739 740 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 741 llvm::opt::ArgStringList ASL; 742 for (const auto *A : Args) 743 A->render(Args, ASL); 744 745 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 746 if (I != ASL.begin()) 747 OS << ' '; 748 Command::printArg(OS, *I, true); 749 } 750 OS << '\n'; 751 } 752 753 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename, 754 SmallString<128> &CrashDiagDir) { 755 using namespace llvm::sys; 756 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() && 757 "Only knows about .crash files on Darwin"); 758 759 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/ 760 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern 761 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash. 762 path::home_directory(CrashDiagDir); 763 if (CrashDiagDir.startswith("/var/root")) 764 CrashDiagDir = "/"; 765 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports"); 766 int PID = 767 #if LLVM_ON_UNIX 768 getpid(); 769 #else 770 0; 771 #endif 772 std::error_code EC; 773 fs::file_status FileStatus; 774 TimePoint<> LastAccessTime; 775 SmallString<128> CrashFilePath; 776 // Lookup the .crash files and get the one generated by a subprocess spawned 777 // by this driver invocation. 778 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd; 779 File != FileEnd && !EC; File.increment(EC)) { 780 StringRef FileName = path::filename(File->path()); 781 if (!FileName.startswith(Name)) 782 continue; 783 if (fs::status(File->path(), FileStatus)) 784 continue; 785 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile = 786 llvm::MemoryBuffer::getFile(File->path()); 787 if (!CrashFile) 788 continue; 789 // The first line should start with "Process:", otherwise this isn't a real 790 // .crash file. 791 StringRef Data = CrashFile.get()->getBuffer(); 792 if (!Data.startswith("Process:")) 793 continue; 794 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]" 795 size_t ParentProcPos = Data.find("Parent Process:"); 796 if (ParentProcPos == StringRef::npos) 797 continue; 798 size_t LineEnd = Data.find_first_of("\n", ParentProcPos); 799 if (LineEnd == StringRef::npos) 800 continue; 801 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim(); 802 int OpenBracket = -1, CloseBracket = -1; 803 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) { 804 if (ParentProcess[i] == '[') 805 OpenBracket = i; 806 if (ParentProcess[i] == ']') 807 CloseBracket = i; 808 } 809 // Extract the parent process PID from the .crash file and check whether 810 // it matches this driver invocation pid. 811 int CrashPID; 812 if (OpenBracket < 0 || CloseBracket < 0 || 813 ParentProcess.slice(OpenBracket + 1, CloseBracket) 814 .getAsInteger(10, CrashPID) || CrashPID != PID) { 815 continue; 816 } 817 818 // Found a .crash file matching the driver pid. To avoid getting an older 819 // and misleading crash file, continue looking for the most recent. 820 // FIXME: the driver can dispatch multiple cc1 invocations, leading to 821 // multiple crashes poiting to the same parent process. Since the driver 822 // does not collect pid information for the dispatched invocation there's 823 // currently no way to distinguish among them. 824 const auto FileAccessTime = FileStatus.getLastModificationTime(); 825 if (FileAccessTime > LastAccessTime) { 826 CrashFilePath.assign(File->path()); 827 LastAccessTime = FileAccessTime; 828 } 829 } 830 831 // If found, copy it over to the location of other reproducer files. 832 if (!CrashFilePath.empty()) { 833 EC = fs::copy_file(CrashFilePath, ReproCrashFilename); 834 if (EC) 835 return false; 836 return true; 837 } 838 839 return false; 840 } 841 842 // When clang crashes, produce diagnostic information including the fully 843 // preprocessed source file(s). Request that the developer attach the 844 // diagnostic information to a bug report. 845 void Driver::generateCompilationDiagnostics(Compilation &C, 846 const Command &FailingCommand) { 847 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 848 return; 849 850 // Don't try to generate diagnostics for link or dsymutil jobs. 851 if (FailingCommand.getCreator().isLinkJob() || 852 FailingCommand.getCreator().isDsymutilJob()) 853 return; 854 855 // Print the version of the compiler. 856 PrintVersion(C, llvm::errs()); 857 858 Diag(clang::diag::note_drv_command_failed_diag_msg) 859 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 860 "crash backtrace, preprocessed source, and associated run script."; 861 862 // Suppress driver output and emit preprocessor output to temp file. 863 Mode = CPPMode; 864 CCGenDiagnostics = true; 865 866 // Save the original job command(s). 867 Command Cmd = FailingCommand; 868 869 // Keep track of whether we produce any errors while trying to produce 870 // preprocessed sources. 871 DiagnosticErrorTrap Trap(Diags); 872 873 // Suppress tool output. 874 C.initCompilationForDiagnostics(); 875 876 // Construct the list of inputs. 877 InputList Inputs; 878 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 879 880 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 881 bool IgnoreInput = false; 882 883 // Ignore input from stdin or any inputs that cannot be preprocessed. 884 // Check type first as not all linker inputs have a value. 885 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 886 IgnoreInput = true; 887 } else if (!strcmp(it->second->getValue(), "-")) { 888 Diag(clang::diag::note_drv_command_failed_diag_msg) 889 << "Error generating preprocessed source(s) - " 890 "ignoring input from stdin."; 891 IgnoreInput = true; 892 } 893 894 if (IgnoreInput) { 895 it = Inputs.erase(it); 896 ie = Inputs.end(); 897 } else { 898 ++it; 899 } 900 } 901 902 if (Inputs.empty()) { 903 Diag(clang::diag::note_drv_command_failed_diag_msg) 904 << "Error generating preprocessed source(s) - " 905 "no preprocessable inputs."; 906 return; 907 } 908 909 // Don't attempt to generate preprocessed files if multiple -arch options are 910 // used, unless they're all duplicates. 911 llvm::StringSet<> ArchNames; 912 for (const Arg *A : C.getArgs()) { 913 if (A->getOption().matches(options::OPT_arch)) { 914 StringRef ArchName = A->getValue(); 915 ArchNames.insert(ArchName); 916 } 917 } 918 if (ArchNames.size() > 1) { 919 Diag(clang::diag::note_drv_command_failed_diag_msg) 920 << "Error generating preprocessed source(s) - cannot generate " 921 "preprocessed source with multiple -arch options."; 922 return; 923 } 924 925 // Construct the list of abstract actions to perform for this compilation. On 926 // Darwin OSes this uses the driver-driver and builds universal actions. 927 const ToolChain &TC = C.getDefaultToolChain(); 928 if (TC.getTriple().isOSBinFormatMachO()) 929 BuildUniversalActions(C, TC, Inputs); 930 else 931 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 932 933 BuildJobs(C); 934 935 // If there were errors building the compilation, quit now. 936 if (Trap.hasErrorOccurred()) { 937 Diag(clang::diag::note_drv_command_failed_diag_msg) 938 << "Error generating preprocessed source(s)."; 939 return; 940 } 941 942 // Generate preprocessed output. 943 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 944 C.ExecuteJobs(C.getJobs(), FailingCommands); 945 946 // If any of the preprocessing commands failed, clean up and exit. 947 if (!FailingCommands.empty()) { 948 if (!isSaveTempsEnabled()) 949 C.CleanupFileList(C.getTempFiles(), true); 950 951 Diag(clang::diag::note_drv_command_failed_diag_msg) 952 << "Error generating preprocessed source(s)."; 953 return; 954 } 955 956 const ArgStringList &TempFiles = C.getTempFiles(); 957 if (TempFiles.empty()) { 958 Diag(clang::diag::note_drv_command_failed_diag_msg) 959 << "Error generating preprocessed source(s)."; 960 return; 961 } 962 963 Diag(clang::diag::note_drv_command_failed_diag_msg) 964 << "\n********************\n\n" 965 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 966 "Preprocessed source(s) and associated run script(s) are located at:"; 967 968 SmallString<128> VFS; 969 SmallString<128> ReproCrashFilename; 970 for (const char *TempFile : TempFiles) { 971 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 972 if (ReproCrashFilename.empty()) { 973 ReproCrashFilename = TempFile; 974 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash"); 975 } 976 if (StringRef(TempFile).endswith(".cache")) { 977 // In some cases (modules) we'll dump extra data to help with reproducing 978 // the crash into a directory next to the output. 979 VFS = llvm::sys::path::filename(TempFile); 980 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 981 } 982 } 983 984 // Assume associated files are based off of the first temporary file. 985 CrashReportInfo CrashInfo(TempFiles[0], VFS); 986 987 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh"; 988 std::error_code EC; 989 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl); 990 if (EC) { 991 Diag(clang::diag::note_drv_command_failed_diag_msg) 992 << "Error generating run script: " + Script + " " + EC.message(); 993 } else { 994 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 995 << "# Driver args: "; 996 printArgList(ScriptOS, C.getInputArgs()); 997 ScriptOS << "# Original command: "; 998 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 999 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 1000 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 1001 } 1002 1003 // On darwin, provide information about the .crash diagnostic report. 1004 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { 1005 SmallString<128> CrashDiagDir; 1006 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) { 1007 Diag(clang::diag::note_drv_command_failed_diag_msg) 1008 << ReproCrashFilename.str(); 1009 } else { // Suggest a directory for the user to look for .crash files. 1010 llvm::sys::path::append(CrashDiagDir, Name); 1011 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash"; 1012 Diag(clang::diag::note_drv_command_failed_diag_msg) 1013 << "Crash backtrace is located in"; 1014 Diag(clang::diag::note_drv_command_failed_diag_msg) 1015 << CrashDiagDir.str(); 1016 Diag(clang::diag::note_drv_command_failed_diag_msg) 1017 << "(choose the .crash file that corresponds to your crash)"; 1018 } 1019 } 1020 1021 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file, 1022 options::OPT_frewrite_map_file_EQ)) 1023 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue(); 1024 1025 Diag(clang::diag::note_drv_command_failed_diag_msg) 1026 << "\n\n********************"; 1027 } 1028 1029 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 1030 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity 1031 // if the tool does not support response files, there is a chance/ that things 1032 // will just work without a response file, so we silently just skip it. 1033 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None || 1034 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments())) 1035 return; 1036 1037 std::string TmpName = GetTemporaryPath("response", "txt"); 1038 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName))); 1039 } 1040 1041 int Driver::ExecuteCompilation( 1042 Compilation &C, 1043 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 1044 // Just print if -### was present. 1045 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 1046 C.getJobs().Print(llvm::errs(), "\n", true); 1047 return 0; 1048 } 1049 1050 // If there were errors building the compilation, quit now. 1051 if (Diags.hasErrorOccurred()) 1052 return 1; 1053 1054 // Set up response file names for each command, if necessary 1055 for (auto &Job : C.getJobs()) 1056 setUpResponseFiles(C, Job); 1057 1058 C.ExecuteJobs(C.getJobs(), FailingCommands); 1059 1060 // Remove temp files. 1061 C.CleanupFileList(C.getTempFiles()); 1062 1063 // If the command succeeded, we are done. 1064 if (FailingCommands.empty()) 1065 return 0; 1066 1067 // Otherwise, remove result files and print extra information about abnormal 1068 // failures. 1069 for (const auto &CmdPair : FailingCommands) { 1070 int Res = CmdPair.first; 1071 const Command *FailingCommand = CmdPair.second; 1072 1073 // Remove result files if we're not saving temps. 1074 if (!isSaveTempsEnabled()) { 1075 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 1076 C.CleanupFileMap(C.getResultFiles(), JA, true); 1077 1078 // Failure result files are valid unless we crashed. 1079 if (Res < 0) 1080 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 1081 } 1082 1083 // Print extra information about abnormal failures, if possible. 1084 // 1085 // This is ad-hoc, but we don't want to be excessively noisy. If the result 1086 // status was 1, assume the command failed normally. In particular, if it 1087 // was the compiler then assume it gave a reasonable error code. Failures 1088 // in other tools are less common, and they generally have worse 1089 // diagnostics, so always print the diagnostic there. 1090 const Tool &FailingTool = FailingCommand->getCreator(); 1091 1092 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 1093 // FIXME: See FIXME above regarding result code interpretation. 1094 if (Res < 0) 1095 Diag(clang::diag::err_drv_command_signalled) 1096 << FailingTool.getShortName(); 1097 else 1098 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() 1099 << Res; 1100 } 1101 } 1102 return 0; 1103 } 1104 1105 void Driver::PrintHelp(bool ShowHidden) const { 1106 unsigned IncludedFlagsBitmask; 1107 unsigned ExcludedFlagsBitmask; 1108 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 1109 getIncludeExcludeOptionFlagMasks(); 1110 1111 ExcludedFlagsBitmask |= options::NoDriverOption; 1112 if (!ShowHidden) 1113 ExcludedFlagsBitmask |= HelpHidden; 1114 1115 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 1116 IncludedFlagsBitmask, ExcludedFlagsBitmask); 1117 } 1118 1119 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 1120 // FIXME: The following handlers should use a callback mechanism, we don't 1121 // know what the client would like to do. 1122 OS << getClangFullVersion() << '\n'; 1123 const ToolChain &TC = C.getDefaultToolChain(); 1124 OS << "Target: " << TC.getTripleString() << '\n'; 1125 1126 // Print the threading model. 1127 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 1128 // Don't print if the ToolChain would have barfed on it already 1129 if (TC.isThreadModelSupported(A->getValue())) 1130 OS << "Thread model: " << A->getValue(); 1131 } else 1132 OS << "Thread model: " << TC.getThreadModel(); 1133 OS << '\n'; 1134 1135 // Print out the install directory. 1136 OS << "InstalledDir: " << InstalledDir << '\n'; 1137 } 1138 1139 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 1140 /// option. 1141 static void PrintDiagnosticCategories(raw_ostream &OS) { 1142 // Skip the empty category. 1143 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 1144 ++i) 1145 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 1146 } 1147 1148 bool Driver::HandleImmediateArgs(const Compilation &C) { 1149 // The order these options are handled in gcc is all over the place, but we 1150 // don't expect inconsistencies w.r.t. that to matter in practice. 1151 1152 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 1153 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 1154 return false; 1155 } 1156 1157 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 1158 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 1159 // return an answer which matches our definition of __VERSION__. 1160 // 1161 // If we want to return a more correct answer some day, then we should 1162 // introduce a non-pedantically GCC compatible mode to Clang in which we 1163 // provide sensible definitions for -dumpversion, __VERSION__, etc. 1164 llvm::outs() << "4.2.1\n"; 1165 return false; 1166 } 1167 1168 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 1169 PrintDiagnosticCategories(llvm::outs()); 1170 return false; 1171 } 1172 1173 if (C.getArgs().hasArg(options::OPT_help) || 1174 C.getArgs().hasArg(options::OPT__help_hidden)) { 1175 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 1176 return false; 1177 } 1178 1179 if (C.getArgs().hasArg(options::OPT__version)) { 1180 // Follow gcc behavior and use stdout for --version and stderr for -v. 1181 PrintVersion(C, llvm::outs()); 1182 1183 // Print registered targets. 1184 llvm::outs() << '\n'; 1185 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs()); 1186 return false; 1187 } 1188 1189 if (C.getArgs().hasArg(options::OPT_v) || 1190 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 1191 PrintVersion(C, llvm::errs()); 1192 SuppressMissingInputWarning = true; 1193 } 1194 1195 const ToolChain &TC = C.getDefaultToolChain(); 1196 1197 if (C.getArgs().hasArg(options::OPT_v)) 1198 TC.printVerboseInfo(llvm::errs()); 1199 1200 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) { 1201 llvm::outs() << ResourceDir << '\n'; 1202 return false; 1203 } 1204 1205 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 1206 llvm::outs() << "programs: ="; 1207 bool separator = false; 1208 for (const std::string &Path : TC.getProgramPaths()) { 1209 if (separator) 1210 llvm::outs() << ':'; 1211 llvm::outs() << Path; 1212 separator = true; 1213 } 1214 llvm::outs() << "\n"; 1215 llvm::outs() << "libraries: =" << ResourceDir; 1216 1217 StringRef sysroot = C.getSysRoot(); 1218 1219 for (const std::string &Path : TC.getFilePaths()) { 1220 // Always print a separator. ResourceDir was the first item shown. 1221 llvm::outs() << ':'; 1222 // Interpretation of leading '=' is needed only for NetBSD. 1223 if (Path[0] == '=') 1224 llvm::outs() << sysroot << Path.substr(1); 1225 else 1226 llvm::outs() << Path; 1227 } 1228 llvm::outs() << "\n"; 1229 return false; 1230 } 1231 1232 // FIXME: The following handlers should use a callback mechanism, we don't 1233 // know what the client would like to do. 1234 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 1235 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 1236 return false; 1237 } 1238 1239 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 1240 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 1241 return false; 1242 } 1243 1244 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) { 1245 // Print out all options that start with a given argument. This is used for 1246 // shell autocompletion. 1247 StringRef PassedFlags = A->getValue(); 1248 std::vector<std::string> SuggestedCompletions; 1249 1250 if (PassedFlags.find(',') == StringRef::npos) { 1251 // If the flag is in the form of "--autocomplete=-foo", 1252 // we were requested to print out all option names that start with "-foo". 1253 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only". 1254 SuggestedCompletions = Opts->findByPrefix(PassedFlags); 1255 } else { 1256 // If the flag is in the form of "--autocomplete=foo,bar", we were 1257 // requested to print out all option values for "-foo" that start with 1258 // "bar". For example, 1259 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++". 1260 StringRef Option, Arg; 1261 std::tie(Option, Arg) = PassedFlags.split(','); 1262 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg); 1263 } 1264 1265 // Sort the autocomplete candidates so that shells print them out in a 1266 // deterministic order. We could sort in any way, but we chose 1267 // case-insensitive sorting for consistency with the -help option 1268 // which prints out options in the case-insensitive alphabetical order. 1269 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(), 1270 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; }); 1271 1272 llvm::outs() << llvm::join(SuggestedCompletions, " ") << '\n'; 1273 return false; 1274 } 1275 1276 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 1277 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs()); 1278 switch (RLT) { 1279 case ToolChain::RLT_CompilerRT: 1280 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n"; 1281 break; 1282 case ToolChain::RLT_Libgcc: 1283 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 1284 break; 1285 } 1286 return false; 1287 } 1288 1289 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 1290 for (const Multilib &Multilib : TC.getMultilibs()) 1291 llvm::outs() << Multilib << "\n"; 1292 return false; 1293 } 1294 1295 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 1296 for (const Multilib &Multilib : TC.getMultilibs()) { 1297 if (Multilib.gccSuffix().empty()) 1298 llvm::outs() << ".\n"; 1299 else { 1300 StringRef Suffix(Multilib.gccSuffix()); 1301 assert(Suffix.front() == '/'); 1302 llvm::outs() << Suffix.substr(1) << "\n"; 1303 } 1304 } 1305 return false; 1306 } 1307 return true; 1308 } 1309 1310 // Display an action graph human-readably. Action A is the "sink" node 1311 // and latest-occuring action. Traversal is in pre-order, visiting the 1312 // inputs to each action before printing the action itself. 1313 static unsigned PrintActions1(const Compilation &C, Action *A, 1314 std::map<Action *, unsigned> &Ids) { 1315 if (Ids.count(A)) // A was already visited. 1316 return Ids[A]; 1317 1318 std::string str; 1319 llvm::raw_string_ostream os(str); 1320 1321 os << Action::getClassName(A->getKind()) << ", "; 1322 if (InputAction *IA = dyn_cast<InputAction>(A)) { 1323 os << "\"" << IA->getInputArg().getValue() << "\""; 1324 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 1325 os << '"' << BIA->getArchName() << '"' << ", {" 1326 << PrintActions1(C, *BIA->input_begin(), Ids) << "}"; 1327 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 1328 bool IsFirst = true; 1329 OA->doOnEachDependence( 1330 [&](Action *A, const ToolChain *TC, const char *BoundArch) { 1331 // E.g. for two CUDA device dependences whose bound arch is sm_20 and 1332 // sm_35 this will generate: 1333 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" 1334 // (nvptx64-nvidia-cuda:sm_35) {#ID} 1335 if (!IsFirst) 1336 os << ", "; 1337 os << '"'; 1338 if (TC) 1339 os << A->getOffloadingKindPrefix(); 1340 else 1341 os << "host"; 1342 os << " ("; 1343 os << TC->getTriple().normalize(); 1344 1345 if (BoundArch) 1346 os << ":" << BoundArch; 1347 os << ")"; 1348 os << '"'; 1349 os << " {" << PrintActions1(C, A, Ids) << "}"; 1350 IsFirst = false; 1351 }); 1352 } else { 1353 const ActionList *AL = &A->getInputs(); 1354 1355 if (AL->size()) { 1356 const char *Prefix = "{"; 1357 for (Action *PreRequisite : *AL) { 1358 os << Prefix << PrintActions1(C, PreRequisite, Ids); 1359 Prefix = ", "; 1360 } 1361 os << "}"; 1362 } else 1363 os << "{}"; 1364 } 1365 1366 // Append offload info for all options other than the offloading action 1367 // itself (e.g. (cuda-device, sm_20) or (cuda-host)). 1368 std::string offload_str; 1369 llvm::raw_string_ostream offload_os(offload_str); 1370 if (!isa<OffloadAction>(A)) { 1371 auto S = A->getOffloadingKindPrefix(); 1372 if (!S.empty()) { 1373 offload_os << ", (" << S; 1374 if (A->getOffloadingArch()) 1375 offload_os << ", " << A->getOffloadingArch(); 1376 offload_os << ")"; 1377 } 1378 } 1379 1380 unsigned Id = Ids.size(); 1381 Ids[A] = Id; 1382 llvm::errs() << Id << ": " << os.str() << ", " 1383 << types::getTypeName(A->getType()) << offload_os.str() << "\n"; 1384 1385 return Id; 1386 } 1387 1388 // Print the action graphs in a compilation C. 1389 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 1390 void Driver::PrintActions(const Compilation &C) const { 1391 std::map<Action *, unsigned> Ids; 1392 for (Action *A : C.getActions()) 1393 PrintActions1(C, A, Ids); 1394 } 1395 1396 /// \brief Check whether the given input tree contains any compilation or 1397 /// assembly actions. 1398 static bool ContainsCompileOrAssembleAction(const Action *A) { 1399 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 1400 isa<AssembleJobAction>(A)) 1401 return true; 1402 1403 for (const Action *Input : A->inputs()) 1404 if (ContainsCompileOrAssembleAction(Input)) 1405 return true; 1406 1407 return false; 1408 } 1409 1410 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 1411 const InputList &BAInputs) const { 1412 DerivedArgList &Args = C.getArgs(); 1413 ActionList &Actions = C.getActions(); 1414 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 1415 // Collect the list of architectures. Duplicates are allowed, but should only 1416 // be handled once (in the order seen). 1417 llvm::StringSet<> ArchNames; 1418 SmallVector<const char *, 4> Archs; 1419 for (Arg *A : Args) { 1420 if (A->getOption().matches(options::OPT_arch)) { 1421 // Validate the option here; we don't save the type here because its 1422 // particular spelling may participate in other driver choices. 1423 llvm::Triple::ArchType Arch = 1424 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 1425 if (Arch == llvm::Triple::UnknownArch) { 1426 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 1427 continue; 1428 } 1429 1430 A->claim(); 1431 if (ArchNames.insert(A->getValue()).second) 1432 Archs.push_back(A->getValue()); 1433 } 1434 } 1435 1436 // When there is no explicit arch for this platform, make sure we still bind 1437 // the architecture (to the default) so that -Xarch_ is handled correctly. 1438 if (!Archs.size()) 1439 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 1440 1441 ActionList SingleActions; 1442 BuildActions(C, Args, BAInputs, SingleActions); 1443 1444 // Add in arch bindings for every top level action, as well as lipo and 1445 // dsymutil steps if needed. 1446 for (Action* Act : SingleActions) { 1447 // Make sure we can lipo this kind of output. If not (and it is an actual 1448 // output) then we disallow, since we can't create an output file with the 1449 // right name without overwriting it. We could remove this oddity by just 1450 // changing the output names to include the arch, which would also fix 1451 // -save-temps. Compatibility wins for now. 1452 1453 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 1454 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 1455 << types::getTypeName(Act->getType()); 1456 1457 ActionList Inputs; 1458 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 1459 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 1460 1461 // Lipo if necessary, we do it this way because we need to set the arch flag 1462 // so that -Xarch_ gets overwritten. 1463 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 1464 Actions.append(Inputs.begin(), Inputs.end()); 1465 else 1466 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 1467 1468 // Handle debug info queries. 1469 Arg *A = Args.getLastArg(options::OPT_g_Group); 1470 if (A && !A->getOption().matches(options::OPT_g0) && 1471 !A->getOption().matches(options::OPT_gstabs) && 1472 ContainsCompileOrAssembleAction(Actions.back())) { 1473 1474 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 1475 // have a compile input. We need to run 'dsymutil' ourselves in such cases 1476 // because the debug info will refer to a temporary object file which 1477 // will be removed at the end of the compilation process. 1478 if (Act->getType() == types::TY_Image) { 1479 ActionList Inputs; 1480 Inputs.push_back(Actions.back()); 1481 Actions.pop_back(); 1482 Actions.push_back( 1483 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 1484 } 1485 1486 // Verify the debug info output. 1487 if (Args.hasArg(options::OPT_verify_debug_info)) { 1488 Action* LastAction = Actions.back(); 1489 Actions.pop_back(); 1490 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 1491 LastAction, types::TY_Nothing)); 1492 } 1493 } 1494 } 1495 } 1496 1497 /// \brief Check that the file referenced by Value exists. If it doesn't, 1498 /// issue a diagnostic and return false. 1499 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, 1500 StringRef Value, types::ID Ty) { 1501 if (!D.getCheckInputsExist()) 1502 return true; 1503 1504 // stdin always exists. 1505 if (Value == "-") 1506 return true; 1507 1508 SmallString<64> Path(Value); 1509 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 1510 if (!llvm::sys::path::is_absolute(Path)) { 1511 SmallString<64> Directory(WorkDir->getValue()); 1512 llvm::sys::path::append(Directory, Value); 1513 Path.assign(Directory); 1514 } 1515 } 1516 1517 if (llvm::sys::fs::exists(Twine(Path))) 1518 return true; 1519 1520 if (D.IsCLMode()) { 1521 if (!llvm::sys::path::is_absolute(Twine(Path)) && 1522 llvm::sys::Process::FindInEnvPath("LIB", Value)) 1523 return true; 1524 1525 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) { 1526 // Arguments to the /link flag might cause the linker to search for object 1527 // and library files in paths we don't know about. Don't error in such 1528 // cases. 1529 return true; 1530 } 1531 } 1532 1533 D.Diag(clang::diag::err_drv_no_such_file) << Path; 1534 return false; 1535 } 1536 1537 // Construct a the list of inputs and their types. 1538 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 1539 InputList &Inputs) const { 1540 // Track the current user specified (-x) input. We also explicitly track the 1541 // argument used to set the type; we only want to claim the type when we 1542 // actually use it, so we warn about unused -x arguments. 1543 types::ID InputType = types::TY_Nothing; 1544 Arg *InputTypeArg = nullptr; 1545 1546 // The last /TC or /TP option sets the input type to C or C++ globally. 1547 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 1548 options::OPT__SLASH_TP)) { 1549 InputTypeArg = TCTP; 1550 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 1551 ? types::TY_C 1552 : types::TY_CXX; 1553 1554 Arg *Previous = nullptr; 1555 bool ShowNote = false; 1556 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) { 1557 if (Previous) { 1558 Diag(clang::diag::warn_drv_overriding_flag_option) 1559 << Previous->getSpelling() << A->getSpelling(); 1560 ShowNote = true; 1561 } 1562 Previous = A; 1563 } 1564 if (ShowNote) 1565 Diag(clang::diag::note_drv_t_option_is_global); 1566 1567 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 1568 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 1569 } 1570 1571 for (Arg *A : Args) { 1572 if (A->getOption().getKind() == Option::InputClass) { 1573 const char *Value = A->getValue(); 1574 types::ID Ty = types::TY_INVALID; 1575 1576 // Infer the input type if necessary. 1577 if (InputType == types::TY_Nothing) { 1578 // If there was an explicit arg for this, claim it. 1579 if (InputTypeArg) 1580 InputTypeArg->claim(); 1581 1582 // stdin must be handled specially. 1583 if (memcmp(Value, "-", 2) == 0) { 1584 // If running with -E, treat as a C input (this changes the builtin 1585 // macros, for example). This may be overridden by -ObjC below. 1586 // 1587 // Otherwise emit an error but still use a valid type to avoid 1588 // spurious errors (e.g., no inputs). 1589 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 1590 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 1591 : clang::diag::err_drv_unknown_stdin_type); 1592 Ty = types::TY_C; 1593 } else { 1594 // Otherwise lookup by extension. 1595 // Fallback is C if invoked as C preprocessor or Object otherwise. 1596 // We use a host hook here because Darwin at least has its own 1597 // idea of what .s is. 1598 if (const char *Ext = strrchr(Value, '.')) 1599 Ty = TC.LookupTypeForExtension(Ext + 1); 1600 1601 if (Ty == types::TY_INVALID) { 1602 if (CCCIsCPP()) 1603 Ty = types::TY_C; 1604 else 1605 Ty = types::TY_Object; 1606 } 1607 1608 // If the driver is invoked as C++ compiler (like clang++ or c++) it 1609 // should autodetect some input files as C++ for g++ compatibility. 1610 if (CCCIsCXX()) { 1611 types::ID OldTy = Ty; 1612 Ty = types::lookupCXXTypeForCType(Ty); 1613 1614 if (Ty != OldTy) 1615 Diag(clang::diag::warn_drv_treating_input_as_cxx) 1616 << getTypeName(OldTy) << getTypeName(Ty); 1617 } 1618 } 1619 1620 // -ObjC and -ObjC++ override the default language, but only for "source 1621 // files". We just treat everything that isn't a linker input as a 1622 // source file. 1623 // 1624 // FIXME: Clean this up if we move the phase sequence into the type. 1625 if (Ty != types::TY_Object) { 1626 if (Args.hasArg(options::OPT_ObjC)) 1627 Ty = types::TY_ObjC; 1628 else if (Args.hasArg(options::OPT_ObjCXX)) 1629 Ty = types::TY_ObjCXX; 1630 } 1631 } else { 1632 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 1633 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 1634 // If emulating cl.exe, make sure that /TC and /TP don't affect input 1635 // object files. 1636 const char *Ext = strrchr(Value, '.'); 1637 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 1638 Ty = types::TY_Object; 1639 } 1640 if (Ty == types::TY_INVALID) { 1641 Ty = InputType; 1642 InputTypeArg->claim(); 1643 } 1644 } 1645 1646 if (DiagnoseInputExistence(*this, Args, Value, Ty)) 1647 Inputs.push_back(std::make_pair(Ty, A)); 1648 1649 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 1650 StringRef Value = A->getValue(); 1651 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) { 1652 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue()); 1653 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 1654 } 1655 A->claim(); 1656 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 1657 StringRef Value = A->getValue(); 1658 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) { 1659 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue()); 1660 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 1661 } 1662 A->claim(); 1663 } else if (A->getOption().hasFlag(options::LinkerInput)) { 1664 // Just treat as object type, we could make a special type for this if 1665 // necessary. 1666 Inputs.push_back(std::make_pair(types::TY_Object, A)); 1667 1668 } else if (A->getOption().matches(options::OPT_x)) { 1669 InputTypeArg = A; 1670 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 1671 A->claim(); 1672 1673 // Follow gcc behavior and treat as linker input for invalid -x 1674 // options. Its not clear why we shouldn't just revert to unknown; but 1675 // this isn't very important, we might as well be bug compatible. 1676 if (!InputType) { 1677 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 1678 InputType = types::TY_Object; 1679 } 1680 } else if (A->getOption().getID() == options::OPT__SLASH_U) { 1681 assert(A->getNumValues() == 1 && "The /U option has one value."); 1682 StringRef Val = A->getValue(0); 1683 if (Val.find_first_of("/\\") != StringRef::npos) { 1684 // Warn about e.g. "/Users/me/myfile.c". 1685 Diag(diag::warn_slash_u_filename) << Val; 1686 Diag(diag::note_use_dashdash); 1687 } 1688 } 1689 } 1690 if (CCCIsCPP() && Inputs.empty()) { 1691 // If called as standalone preprocessor, stdin is processed 1692 // if no other input is present. 1693 Arg *A = MakeInputArg(Args, *Opts, "-"); 1694 Inputs.push_back(std::make_pair(types::TY_C, A)); 1695 } 1696 } 1697 1698 namespace { 1699 /// Provides a convenient interface for different programming models to generate 1700 /// the required device actions. 1701 class OffloadingActionBuilder final { 1702 /// Flag used to trace errors in the builder. 1703 bool IsValid = false; 1704 1705 /// The compilation that is using this builder. 1706 Compilation &C; 1707 1708 /// Map between an input argument and the offload kinds used to process it. 1709 std::map<const Arg *, unsigned> InputArgToOffloadKindMap; 1710 1711 /// Builder interface. It doesn't build anything or keep any state. 1712 class DeviceActionBuilder { 1713 public: 1714 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy; 1715 1716 enum ActionBuilderReturnCode { 1717 // The builder acted successfully on the current action. 1718 ABRT_Success, 1719 // The builder didn't have to act on the current action. 1720 ABRT_Inactive, 1721 // The builder was successful and requested the host action to not be 1722 // generated. 1723 ABRT_Ignore_Host, 1724 }; 1725 1726 protected: 1727 /// Compilation associated with this builder. 1728 Compilation &C; 1729 1730 /// Tool chains associated with this builder. The same programming 1731 /// model may have associated one or more tool chains. 1732 SmallVector<const ToolChain *, 2> ToolChains; 1733 1734 /// The derived arguments associated with this builder. 1735 DerivedArgList &Args; 1736 1737 /// The inputs associated with this builder. 1738 const Driver::InputList &Inputs; 1739 1740 /// The associated offload kind. 1741 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; 1742 1743 public: 1744 DeviceActionBuilder(Compilation &C, DerivedArgList &Args, 1745 const Driver::InputList &Inputs, 1746 Action::OffloadKind AssociatedOffloadKind) 1747 : C(C), Args(Args), Inputs(Inputs), 1748 AssociatedOffloadKind(AssociatedOffloadKind) {} 1749 virtual ~DeviceActionBuilder() {} 1750 1751 /// Fill up the array \a DA with all the device dependences that should be 1752 /// added to the provided host action \a HostAction. By default it is 1753 /// inactive. 1754 virtual ActionBuilderReturnCode 1755 getDeviceDependences(OffloadAction::DeviceDependences &DA, 1756 phases::ID CurPhase, phases::ID FinalPhase, 1757 PhasesTy &Phases) { 1758 return ABRT_Inactive; 1759 } 1760 1761 /// Update the state to include the provided host action \a HostAction as a 1762 /// dependency of the current device action. By default it is inactive. 1763 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) { 1764 return ABRT_Inactive; 1765 } 1766 1767 /// Append top level actions generated by the builder. Return true if errors 1768 /// were found. 1769 virtual void appendTopLevelActions(ActionList &AL) {} 1770 1771 /// Append linker actions generated by the builder. Return true if errors 1772 /// were found. 1773 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} 1774 1775 /// Initialize the builder. Return true if any initialization errors are 1776 /// found. 1777 virtual bool initialize() { return false; } 1778 1779 /// Return true if the builder can use bundling/unbundling. 1780 virtual bool canUseBundlerUnbundler() const { return false; } 1781 1782 /// Return true if this builder is valid. We have a valid builder if we have 1783 /// associated device tool chains. 1784 bool isValid() { return !ToolChains.empty(); } 1785 1786 /// Return the associated offload kind. 1787 Action::OffloadKind getAssociatedOffloadKind() { 1788 return AssociatedOffloadKind; 1789 } 1790 }; 1791 1792 /// \brief CUDA action builder. It injects device code in the host backend 1793 /// action. 1794 class CudaActionBuilder final : public DeviceActionBuilder { 1795 /// Flags to signal if the user requested host-only or device-only 1796 /// compilation. 1797 bool CompileHostOnly = false; 1798 bool CompileDeviceOnly = false; 1799 1800 /// List of GPU architectures to use in this compilation. 1801 SmallVector<CudaArch, 4> GpuArchList; 1802 1803 /// The CUDA actions for the current input. 1804 ActionList CudaDeviceActions; 1805 1806 /// The CUDA fat binary if it was generated for the current input. 1807 Action *CudaFatBinary = nullptr; 1808 1809 /// Flag that is set to true if this builder acted on the current input. 1810 bool IsActive = false; 1811 1812 public: 1813 CudaActionBuilder(Compilation &C, DerivedArgList &Args, 1814 const Driver::InputList &Inputs) 1815 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {} 1816 1817 ActionBuilderReturnCode 1818 getDeviceDependences(OffloadAction::DeviceDependences &DA, 1819 phases::ID CurPhase, phases::ID FinalPhase, 1820 PhasesTy &Phases) override { 1821 if (!IsActive) 1822 return ABRT_Inactive; 1823 1824 // If we don't have more CUDA actions, we don't have any dependences to 1825 // create for the host. 1826 if (CudaDeviceActions.empty()) 1827 return ABRT_Success; 1828 1829 assert(CudaDeviceActions.size() == GpuArchList.size() && 1830 "Expecting one action per GPU architecture."); 1831 assert(!CompileHostOnly && 1832 "Not expecting CUDA actions in host-only compilation."); 1833 1834 // If we are generating code for the device or we are in a backend phase, 1835 // we attempt to generate the fat binary. We compile each arch to ptx and 1836 // assemble to cubin, then feed the cubin *and* the ptx into a device 1837 // "link" action, which uses fatbinary to combine these cubins into one 1838 // fatbin. The fatbin is then an input to the host action if not in 1839 // device-only mode. 1840 if (CompileDeviceOnly || CurPhase == phases::Backend) { 1841 ActionList DeviceActions; 1842 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1843 // Produce the device action from the current phase up to the assemble 1844 // phase. 1845 for (auto Ph : Phases) { 1846 // Skip the phases that were already dealt with. 1847 if (Ph < CurPhase) 1848 continue; 1849 // We have to be consistent with the host final phase. 1850 if (Ph > FinalPhase) 1851 break; 1852 1853 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( 1854 C, Args, Ph, CudaDeviceActions[I]); 1855 1856 if (Ph == phases::Assemble) 1857 break; 1858 } 1859 1860 // If we didn't reach the assemble phase, we can't generate the fat 1861 // binary. We don't need to generate the fat binary if we are not in 1862 // device-only mode. 1863 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) || 1864 CompileDeviceOnly) 1865 continue; 1866 1867 Action *AssembleAction = CudaDeviceActions[I]; 1868 assert(AssembleAction->getType() == types::TY_Object); 1869 assert(AssembleAction->getInputs().size() == 1); 1870 1871 Action *BackendAction = AssembleAction->getInputs()[0]; 1872 assert(BackendAction->getType() == types::TY_PP_Asm); 1873 1874 for (auto &A : {AssembleAction, BackendAction}) { 1875 OffloadAction::DeviceDependences DDep; 1876 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]), 1877 Action::OFK_Cuda); 1878 DeviceActions.push_back( 1879 C.MakeAction<OffloadAction>(DDep, A->getType())); 1880 } 1881 } 1882 1883 // We generate the fat binary if we have device input actions. 1884 if (!DeviceActions.empty()) { 1885 CudaFatBinary = 1886 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 1887 1888 if (!CompileDeviceOnly) { 1889 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 1890 Action::OFK_Cuda); 1891 // Clear the fat binary, it is already a dependence to an host 1892 // action. 1893 CudaFatBinary = nullptr; 1894 } 1895 1896 // Remove the CUDA actions as they are already connected to an host 1897 // action or fat binary. 1898 CudaDeviceActions.clear(); 1899 } 1900 1901 // We avoid creating host action in device-only mode. 1902 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 1903 } else if (CurPhase > phases::Backend) { 1904 // If we are past the backend phase and still have a device action, we 1905 // don't have to do anything as this action is already a device 1906 // top-level action. 1907 return ABRT_Success; 1908 } 1909 1910 assert(CurPhase < phases::Backend && "Generating single CUDA " 1911 "instructions should only occur " 1912 "before the backend phase!"); 1913 1914 // By default, we produce an action for each device arch. 1915 for (Action *&A : CudaDeviceActions) 1916 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 1917 1918 return ABRT_Success; 1919 } 1920 1921 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 1922 // While generating code for CUDA, we only depend on the host input action 1923 // to trigger the creation of all the CUDA device actions. 1924 1925 // If we are dealing with an input action, replicate it for each GPU 1926 // architecture. If we are in host-only mode we return 'success' so that 1927 // the host uses the CUDA offload kind. 1928 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 1929 assert(!GpuArchList.empty() && 1930 "We should have at least one GPU architecture."); 1931 1932 // If the host input is not CUDA, we don't need to bother about this 1933 // input. 1934 if (IA->getType() != types::TY_CUDA) { 1935 // The builder will ignore this input. 1936 IsActive = false; 1937 return ABRT_Inactive; 1938 } 1939 1940 // Set the flag to true, so that the builder acts on the current input. 1941 IsActive = true; 1942 1943 if (CompileHostOnly) 1944 return ABRT_Success; 1945 1946 // Replicate inputs for each GPU architecture. 1947 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1948 CudaDeviceActions.push_back(C.MakeAction<InputAction>( 1949 IA->getInputArg(), types::TY_CUDA_DEVICE)); 1950 1951 return ABRT_Success; 1952 } 1953 1954 return IsActive ? ABRT_Success : ABRT_Inactive; 1955 } 1956 1957 void appendTopLevelActions(ActionList &AL) override { 1958 // Utility to append actions to the top level list. 1959 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) { 1960 OffloadAction::DeviceDependences Dep; 1961 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch), 1962 Action::OFK_Cuda); 1963 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 1964 }; 1965 1966 // If we have a fat binary, add it to the list. 1967 if (CudaFatBinary) { 1968 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN); 1969 CudaDeviceActions.clear(); 1970 CudaFatBinary = nullptr; 1971 return; 1972 } 1973 1974 if (CudaDeviceActions.empty()) 1975 return; 1976 1977 // If we have CUDA actions at this point, that's because we have a have 1978 // partial compilation, so we should have an action for each GPU 1979 // architecture. 1980 assert(CudaDeviceActions.size() == GpuArchList.size() && 1981 "Expecting one action per GPU architecture."); 1982 assert(ToolChains.size() == 1 && 1983 "Expecting to have a sing CUDA toolchain."); 1984 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1985 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); 1986 1987 CudaDeviceActions.clear(); 1988 } 1989 1990 bool initialize() override { 1991 // We don't need to support CUDA. 1992 if (!C.hasOffloadToolChain<Action::OFK_Cuda>()) 1993 return false; 1994 1995 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 1996 assert(HostTC && "No toolchain for host compilation."); 1997 if (HostTC->getTriple().isNVPTX()) { 1998 // We do not support targeting NVPTX for host compilation. Throw 1999 // an error and abort pipeline construction early so we don't trip 2000 // asserts that assume device-side compilation. 2001 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host); 2002 return true; 2003 } 2004 2005 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>()); 2006 2007 Arg *PartialCompilationArg = Args.getLastArg( 2008 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 2009 options::OPT_cuda_compile_host_device); 2010 CompileHostOnly = PartialCompilationArg && 2011 PartialCompilationArg->getOption().matches( 2012 options::OPT_cuda_host_only); 2013 CompileDeviceOnly = PartialCompilationArg && 2014 PartialCompilationArg->getOption().matches( 2015 options::OPT_cuda_device_only); 2016 2017 // Collect all cuda_gpu_arch parameters, removing duplicates. 2018 std::set<CudaArch> GpuArchs; 2019 bool Error = false; 2020 for (Arg *A : Args) { 2021 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) || 2022 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))) 2023 continue; 2024 A->claim(); 2025 2026 const StringRef ArchStr = A->getValue(); 2027 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) && 2028 ArchStr == "all") { 2029 GpuArchs.clear(); 2030 continue; 2031 } 2032 CudaArch Arch = StringToCudaArch(ArchStr); 2033 if (Arch == CudaArch::UNKNOWN) { 2034 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 2035 Error = true; 2036 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) 2037 GpuArchs.insert(Arch); 2038 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)) 2039 GpuArchs.erase(Arch); 2040 else 2041 llvm_unreachable("Unexpected option."); 2042 } 2043 2044 // Collect list of GPUs remaining in the set. 2045 for (CudaArch Arch : GpuArchs) 2046 GpuArchList.push_back(Arch); 2047 2048 // Default to sm_20 which is the lowest common denominator for 2049 // supported GPUs. sm_20 code should work correctly, if 2050 // suboptimally, on all newer GPUs. 2051 if (GpuArchList.empty()) 2052 GpuArchList.push_back(CudaArch::SM_20); 2053 2054 return Error; 2055 } 2056 }; 2057 2058 /// OpenMP action builder. The host bitcode is passed to the device frontend 2059 /// and all the device linked images are passed to the host link phase. 2060 class OpenMPActionBuilder final : public DeviceActionBuilder { 2061 /// The OpenMP actions for the current input. 2062 ActionList OpenMPDeviceActions; 2063 2064 /// The linker inputs obtained for each toolchain. 2065 SmallVector<ActionList, 8> DeviceLinkerInputs; 2066 2067 public: 2068 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args, 2069 const Driver::InputList &Inputs) 2070 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {} 2071 2072 ActionBuilderReturnCode 2073 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2074 phases::ID CurPhase, phases::ID FinalPhase, 2075 PhasesTy &Phases) override { 2076 2077 // We should always have an action for each input. 2078 assert(OpenMPDeviceActions.size() == ToolChains.size() && 2079 "Number of OpenMP actions and toolchains do not match."); 2080 2081 // The host only depends on device action in the linking phase, when all 2082 // the device images have to be embedded in the host image. 2083 if (CurPhase == phases::Link) { 2084 assert(ToolChains.size() == DeviceLinkerInputs.size() && 2085 "Toolchains and linker inputs sizes do not match."); 2086 auto LI = DeviceLinkerInputs.begin(); 2087 for (auto *A : OpenMPDeviceActions) { 2088 LI->push_back(A); 2089 ++LI; 2090 } 2091 2092 // We passed the device action as a host dependence, so we don't need to 2093 // do anything else with them. 2094 OpenMPDeviceActions.clear(); 2095 return ABRT_Success; 2096 } 2097 2098 // By default, we produce an action for each device arch. 2099 for (Action *&A : OpenMPDeviceActions) 2100 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 2101 2102 return ABRT_Success; 2103 } 2104 2105 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 2106 2107 // If this is an input action replicate it for each OpenMP toolchain. 2108 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 2109 OpenMPDeviceActions.clear(); 2110 for (unsigned I = 0; I < ToolChains.size(); ++I) 2111 OpenMPDeviceActions.push_back( 2112 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType())); 2113 return ABRT_Success; 2114 } 2115 2116 // If this is an unbundling action use it as is for each OpenMP toolchain. 2117 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 2118 OpenMPDeviceActions.clear(); 2119 for (unsigned I = 0; I < ToolChains.size(); ++I) { 2120 OpenMPDeviceActions.push_back(UA); 2121 UA->registerDependentActionInfo( 2122 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP); 2123 } 2124 return ABRT_Success; 2125 } 2126 2127 // When generating code for OpenMP we use the host compile phase result as 2128 // a dependence to the device compile phase so that it can learn what 2129 // declarations should be emitted. However, this is not the only use for 2130 // the host action, so we prevent it from being collapsed. 2131 if (isa<CompileJobAction>(HostAction)) { 2132 HostAction->setCannotBeCollapsedWithNextDependentAction(); 2133 assert(ToolChains.size() == OpenMPDeviceActions.size() && 2134 "Toolchains and device action sizes do not match."); 2135 OffloadAction::HostDependence HDep( 2136 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 2137 /*BoundArch=*/nullptr, Action::OFK_OpenMP); 2138 auto TC = ToolChains.begin(); 2139 for (Action *&A : OpenMPDeviceActions) { 2140 assert(isa<CompileJobAction>(A)); 2141 OffloadAction::DeviceDependences DDep; 2142 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 2143 A = C.MakeAction<OffloadAction>(HDep, DDep); 2144 ++TC; 2145 } 2146 } 2147 return ABRT_Success; 2148 } 2149 2150 void appendTopLevelActions(ActionList &AL) override { 2151 if (OpenMPDeviceActions.empty()) 2152 return; 2153 2154 // We should always have an action for each input. 2155 assert(OpenMPDeviceActions.size() == ToolChains.size() && 2156 "Number of OpenMP actions and toolchains do not match."); 2157 2158 // Append all device actions followed by the proper offload action. 2159 auto TI = ToolChains.begin(); 2160 for (auto *A : OpenMPDeviceActions) { 2161 OffloadAction::DeviceDependences Dep; 2162 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 2163 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 2164 ++TI; 2165 } 2166 // We no longer need the action stored in this builder. 2167 OpenMPDeviceActions.clear(); 2168 } 2169 2170 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override { 2171 assert(ToolChains.size() == DeviceLinkerInputs.size() && 2172 "Toolchains and linker inputs sizes do not match."); 2173 2174 // Append a new link action for each device. 2175 auto TC = ToolChains.begin(); 2176 for (auto &LI : DeviceLinkerInputs) { 2177 auto *DeviceLinkAction = 2178 C.MakeAction<LinkJobAction>(LI, types::TY_Image); 2179 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr, 2180 Action::OFK_OpenMP); 2181 ++TC; 2182 } 2183 } 2184 2185 bool initialize() override { 2186 // Get the OpenMP toolchains. If we don't get any, the action builder will 2187 // know there is nothing to do related to OpenMP offloading. 2188 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 2189 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE; 2190 ++TI) 2191 ToolChains.push_back(TI->second); 2192 2193 DeviceLinkerInputs.resize(ToolChains.size()); 2194 return false; 2195 } 2196 2197 bool canUseBundlerUnbundler() const override { 2198 // OpenMP should use bundled files whenever possible. 2199 return true; 2200 } 2201 }; 2202 2203 /// 2204 /// TODO: Add the implementation for other specialized builders here. 2205 /// 2206 2207 /// Specialized builders being used by this offloading action builder. 2208 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; 2209 2210 /// Flag set to true if all valid builders allow file bundling/unbundling. 2211 bool CanUseBundler; 2212 2213 public: 2214 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, 2215 const Driver::InputList &Inputs) 2216 : C(C) { 2217 // Create a specialized builder for each device toolchain. 2218 2219 IsValid = true; 2220 2221 // Create a specialized builder for CUDA. 2222 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs)); 2223 2224 // Create a specialized builder for OpenMP. 2225 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs)); 2226 2227 // 2228 // TODO: Build other specialized builders here. 2229 // 2230 2231 // Initialize all the builders, keeping track of errors. If all valid 2232 // builders agree that we can use bundling, set the flag to true. 2233 unsigned ValidBuilders = 0u; 2234 unsigned ValidBuildersSupportingBundling = 0u; 2235 for (auto *SB : SpecializedBuilders) { 2236 IsValid = IsValid && !SB->initialize(); 2237 2238 // Update the counters if the builder is valid. 2239 if (SB->isValid()) { 2240 ++ValidBuilders; 2241 if (SB->canUseBundlerUnbundler()) 2242 ++ValidBuildersSupportingBundling; 2243 } 2244 } 2245 CanUseBundler = 2246 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; 2247 } 2248 2249 ~OffloadingActionBuilder() { 2250 for (auto *SB : SpecializedBuilders) 2251 delete SB; 2252 } 2253 2254 /// Generate an action that adds device dependences (if any) to a host action. 2255 /// If no device dependence actions exist, just return the host action \a 2256 /// HostAction. If an error is found or if no builder requires the host action 2257 /// to be generated, return nullptr. 2258 Action * 2259 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, 2260 phases::ID CurPhase, phases::ID FinalPhase, 2261 DeviceActionBuilder::PhasesTy &Phases) { 2262 if (!IsValid) 2263 return nullptr; 2264 2265 if (SpecializedBuilders.empty()) 2266 return HostAction; 2267 2268 assert(HostAction && "Invalid host action!"); 2269 2270 OffloadAction::DeviceDependences DDeps; 2271 // Check if all the programming models agree we should not emit the host 2272 // action. Also, keep track of the offloading kinds employed. 2273 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 2274 unsigned InactiveBuilders = 0u; 2275 unsigned IgnoringBuilders = 0u; 2276 for (auto *SB : SpecializedBuilders) { 2277 if (!SB->isValid()) { 2278 ++InactiveBuilders; 2279 continue; 2280 } 2281 2282 auto RetCode = 2283 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases); 2284 2285 // If the builder explicitly says the host action should be ignored, 2286 // we need to increment the variable that tracks the builders that request 2287 // the host object to be ignored. 2288 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) 2289 ++IgnoringBuilders; 2290 2291 // Unless the builder was inactive for this action, we have to record the 2292 // offload kind because the host will have to use it. 2293 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 2294 OffloadKind |= SB->getAssociatedOffloadKind(); 2295 } 2296 2297 // If all builders agree that the host object should be ignored, just return 2298 // nullptr. 2299 if (IgnoringBuilders && 2300 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) 2301 return nullptr; 2302 2303 if (DDeps.getActions().empty()) 2304 return HostAction; 2305 2306 // We have dependences we need to bundle together. We use an offload action 2307 // for that. 2308 OffloadAction::HostDependence HDep( 2309 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 2310 /*BoundArch=*/nullptr, DDeps); 2311 return C.MakeAction<OffloadAction>(HDep, DDeps); 2312 } 2313 2314 /// Generate an action that adds a host dependence to a device action. The 2315 /// results will be kept in this action builder. Return true if an error was 2316 /// found. 2317 bool addHostDependenceToDeviceActions(Action *&HostAction, 2318 const Arg *InputArg) { 2319 if (!IsValid) 2320 return true; 2321 2322 // If we are supporting bundling/unbundling and the current action is an 2323 // input action of non-source file, we replace the host action by the 2324 // unbundling action. The bundler tool has the logic to detect if an input 2325 // is a bundle or not and if the input is not a bundle it assumes it is a 2326 // host file. Therefore it is safe to create an unbundling action even if 2327 // the input is not a bundle. 2328 if (CanUseBundler && isa<InputAction>(HostAction) && 2329 InputArg->getOption().getKind() == llvm::opt::Option::InputClass && 2330 !types::isSrcFile(HostAction->getType())) { 2331 auto UnbundlingHostAction = 2332 C.MakeAction<OffloadUnbundlingJobAction>(HostAction); 2333 UnbundlingHostAction->registerDependentActionInfo( 2334 C.getSingleOffloadToolChain<Action::OFK_Host>(), 2335 /*BoundArch=*/StringRef(), Action::OFK_Host); 2336 HostAction = UnbundlingHostAction; 2337 } 2338 2339 assert(HostAction && "Invalid host action!"); 2340 2341 // Register the offload kinds that are used. 2342 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 2343 for (auto *SB : SpecializedBuilders) { 2344 if (!SB->isValid()) 2345 continue; 2346 2347 auto RetCode = SB->addDeviceDepences(HostAction); 2348 2349 // Host dependences for device actions are not compatible with that same 2350 // action being ignored. 2351 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && 2352 "Host dependence not expected to be ignored.!"); 2353 2354 // Unless the builder was inactive for this action, we have to record the 2355 // offload kind because the host will have to use it. 2356 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 2357 OffloadKind |= SB->getAssociatedOffloadKind(); 2358 } 2359 2360 return false; 2361 } 2362 2363 /// Add the offloading top level actions to the provided action list. This 2364 /// function can replace the host action by a bundling action if the 2365 /// programming models allow it. 2366 bool appendTopLevelActions(ActionList &AL, Action *HostAction, 2367 const Arg *InputArg) { 2368 // Get the device actions to be appended. 2369 ActionList OffloadAL; 2370 for (auto *SB : SpecializedBuilders) { 2371 if (!SB->isValid()) 2372 continue; 2373 SB->appendTopLevelActions(OffloadAL); 2374 } 2375 2376 // If we can use the bundler, replace the host action by the bundling one in 2377 // the resulting list. Otherwise, just append the device actions. 2378 if (CanUseBundler && !OffloadAL.empty()) { 2379 // Add the host action to the list in order to create the bundling action. 2380 OffloadAL.push_back(HostAction); 2381 2382 // We expect that the host action was just appended to the action list 2383 // before this method was called. 2384 assert(HostAction == AL.back() && "Host action not in the list??"); 2385 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL); 2386 AL.back() = HostAction; 2387 } else 2388 AL.append(OffloadAL.begin(), OffloadAL.end()); 2389 2390 // Propagate to the current host action (if any) the offload information 2391 // associated with the current input. 2392 if (HostAction) 2393 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg], 2394 /*BoundArch=*/nullptr); 2395 return false; 2396 } 2397 2398 /// Processes the host linker action. This currently consists of replacing it 2399 /// with an offload action if there are device link objects and propagate to 2400 /// the host action all the offload kinds used in the current compilation. The 2401 /// resulting action is returned. 2402 Action *processHostLinkAction(Action *HostAction) { 2403 // Add all the dependences from the device linking actions. 2404 OffloadAction::DeviceDependences DDeps; 2405 for (auto *SB : SpecializedBuilders) { 2406 if (!SB->isValid()) 2407 continue; 2408 2409 SB->appendLinkDependences(DDeps); 2410 } 2411 2412 // Calculate all the offload kinds used in the current compilation. 2413 unsigned ActiveOffloadKinds = 0u; 2414 for (auto &I : InputArgToOffloadKindMap) 2415 ActiveOffloadKinds |= I.second; 2416 2417 // If we don't have device dependencies, we don't have to create an offload 2418 // action. 2419 if (DDeps.getActions().empty()) { 2420 // Propagate all the active kinds to host action. Given that it is a link 2421 // action it is assumed to depend on all actions generated so far. 2422 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds, 2423 /*BoundArch=*/nullptr); 2424 return HostAction; 2425 } 2426 2427 // Create the offload action with all dependences. When an offload action 2428 // is created the kinds are propagated to the host action, so we don't have 2429 // to do that explicitly here. 2430 OffloadAction::HostDependence HDep( 2431 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 2432 /*BoundArch*/ nullptr, ActiveOffloadKinds); 2433 return C.MakeAction<OffloadAction>(HDep, DDeps); 2434 } 2435 }; 2436 } // anonymous namespace. 2437 2438 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 2439 const InputList &Inputs, ActionList &Actions) const { 2440 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 2441 2442 if (!SuppressMissingInputWarning && Inputs.empty()) { 2443 Diag(clang::diag::err_drv_no_input_files); 2444 return; 2445 } 2446 2447 Arg *FinalPhaseArg; 2448 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 2449 2450 if (FinalPhase == phases::Link) { 2451 if (Args.hasArg(options::OPT_emit_llvm)) 2452 Diag(clang::diag::err_drv_emit_llvm_link); 2453 if (IsCLMode() && LTOMode != LTOK_None && 2454 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld")) 2455 Diag(clang::diag::err_drv_lto_without_lld); 2456 } 2457 2458 // Reject -Z* at the top level, these options should never have been exposed 2459 // by gcc. 2460 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 2461 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 2462 2463 // Diagnose misuse of /Fo. 2464 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 2465 StringRef V = A->getValue(); 2466 if (Inputs.size() > 1 && !V.empty() && 2467 !llvm::sys::path::is_separator(V.back())) { 2468 // Check whether /Fo tries to name an output file for multiple inputs. 2469 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 2470 << A->getSpelling() << V; 2471 Args.eraseArg(options::OPT__SLASH_Fo); 2472 } 2473 } 2474 2475 // Diagnose misuse of /Fa. 2476 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 2477 StringRef V = A->getValue(); 2478 if (Inputs.size() > 1 && !V.empty() && 2479 !llvm::sys::path::is_separator(V.back())) { 2480 // Check whether /Fa tries to name an asm file for multiple inputs. 2481 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 2482 << A->getSpelling() << V; 2483 Args.eraseArg(options::OPT__SLASH_Fa); 2484 } 2485 } 2486 2487 // Diagnose misuse of /o. 2488 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 2489 if (A->getValue()[0] == '\0') { 2490 // It has to have a value. 2491 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 2492 Args.eraseArg(options::OPT__SLASH_o); 2493 } 2494 } 2495 2496 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if: 2497 // * no filename after it 2498 // * both /Yc and /Yu passed but with different filenames 2499 // * corresponding file not also passed as /FI 2500 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 2501 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 2502 if (YcArg && YcArg->getValue()[0] == '\0') { 2503 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling(); 2504 Args.eraseArg(options::OPT__SLASH_Yc); 2505 YcArg = nullptr; 2506 } 2507 if (YuArg && YuArg->getValue()[0] == '\0') { 2508 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling(); 2509 Args.eraseArg(options::OPT__SLASH_Yu); 2510 YuArg = nullptr; 2511 } 2512 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 2513 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 2514 Args.eraseArg(options::OPT__SLASH_Yc); 2515 Args.eraseArg(options::OPT__SLASH_Yu); 2516 YcArg = YuArg = nullptr; 2517 } 2518 if (YcArg || YuArg) { 2519 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue(); 2520 bool FoundMatchingInclude = false; 2521 for (const Arg *Inc : Args.filtered(options::OPT_include)) { 2522 // FIXME: Do case-insensitive matching and consider / and \ as equal. 2523 if (Inc->getValue() == Val) 2524 FoundMatchingInclude = true; 2525 } 2526 if (!FoundMatchingInclude) { 2527 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl) 2528 << (YcArg ? YcArg : YuArg)->getSpelling(); 2529 Args.eraseArg(options::OPT__SLASH_Yc); 2530 Args.eraseArg(options::OPT__SLASH_Yu); 2531 YcArg = YuArg = nullptr; 2532 } 2533 } 2534 if (YcArg && Inputs.size() > 1) { 2535 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 2536 Args.eraseArg(options::OPT__SLASH_Yc); 2537 YcArg = nullptr; 2538 } 2539 if (Args.hasArg(options::OPT__SLASH_Y_)) { 2540 // /Y- disables all pch handling. Rather than check for it everywhere, 2541 // just remove clang-cl pch-related flags here. 2542 Args.eraseArg(options::OPT__SLASH_Fp); 2543 Args.eraseArg(options::OPT__SLASH_Yc); 2544 Args.eraseArg(options::OPT__SLASH_Yu); 2545 YcArg = YuArg = nullptr; 2546 } 2547 2548 // Builder to be used to build offloading actions. 2549 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs); 2550 2551 // Construct the actions to perform. 2552 ActionList LinkerInputs; 2553 2554 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 2555 for (auto &I : Inputs) { 2556 types::ID InputType = I.first; 2557 const Arg *InputArg = I.second; 2558 2559 PL.clear(); 2560 types::getCompilationPhases(InputType, PL); 2561 2562 // If the first step comes after the final phase we are doing as part of 2563 // this compilation, warn the user about it. 2564 phases::ID InitialPhase = PL[0]; 2565 if (InitialPhase > FinalPhase) { 2566 // Claim here to avoid the more general unused warning. 2567 InputArg->claim(); 2568 2569 // Suppress all unused style warnings with -Qunused-arguments 2570 if (Args.hasArg(options::OPT_Qunused_arguments)) 2571 continue; 2572 2573 // Special case when final phase determined by binary name, rather than 2574 // by a command-line argument with a corresponding Arg. 2575 if (CCCIsCPP()) 2576 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 2577 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 2578 // Special case '-E' warning on a previously preprocessed file to make 2579 // more sense. 2580 else if (InitialPhase == phases::Compile && 2581 FinalPhase == phases::Preprocess && 2582 getPreprocessedType(InputType) == types::TY_INVALID) 2583 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 2584 << InputArg->getAsString(Args) << !!FinalPhaseArg 2585 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 2586 else 2587 Diag(clang::diag::warn_drv_input_file_unused) 2588 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 2589 << !!FinalPhaseArg 2590 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 2591 continue; 2592 } 2593 2594 if (YcArg) { 2595 // Add a separate precompile phase for the compile phase. 2596 if (FinalPhase >= phases::Compile) { 2597 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType); 2598 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL; 2599 types::getCompilationPhases(HeaderType, PCHPL); 2600 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue()); 2601 2602 // Build the pipeline for the pch file. 2603 Action *ClangClPch = 2604 C.MakeAction<InputAction>(*PchInputArg, HeaderType); 2605 for (phases::ID Phase : PCHPL) 2606 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 2607 assert(ClangClPch); 2608 Actions.push_back(ClangClPch); 2609 // The driver currently exits after the first failed command. This 2610 // relies on that behavior, to make sure if the pch generation fails, 2611 // the main compilation won't run. 2612 } 2613 } 2614 2615 // Build the pipeline for this file. 2616 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 2617 2618 // Use the current host action in any of the offloading actions, if 2619 // required. 2620 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 2621 break; 2622 2623 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end(); 2624 i != e; ++i) { 2625 phases::ID Phase = *i; 2626 2627 // We are done if this step is past what the user requested. 2628 if (Phase > FinalPhase) 2629 break; 2630 2631 // Add any offload action the host action depends on. 2632 Current = OffloadBuilder.addDeviceDependencesToHostAction( 2633 Current, InputArg, Phase, FinalPhase, PL); 2634 if (!Current) 2635 break; 2636 2637 // Queue linker inputs. 2638 if (Phase == phases::Link) { 2639 assert((i + 1) == e && "linking must be final compilation step."); 2640 LinkerInputs.push_back(Current); 2641 Current = nullptr; 2642 break; 2643 } 2644 2645 // Otherwise construct the appropriate action. 2646 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 2647 2648 // We didn't create a new action, so we will just move to the next phase. 2649 if (NewCurrent == Current) 2650 continue; 2651 2652 Current = NewCurrent; 2653 2654 // Use the current host action in any of the offloading actions, if 2655 // required. 2656 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 2657 break; 2658 2659 if (Current->getType() == types::TY_Nothing) 2660 break; 2661 } 2662 2663 // If we ended with something, add to the output list. 2664 if (Current) 2665 Actions.push_back(Current); 2666 2667 // Add any top level actions generated for offloading. 2668 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg); 2669 } 2670 2671 // Add a link action if necessary. 2672 if (!LinkerInputs.empty()) { 2673 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 2674 LA = OffloadBuilder.processHostLinkAction(LA); 2675 Actions.push_back(LA); 2676 } 2677 2678 // If we are linking, claim any options which are obviously only used for 2679 // compilation. 2680 if (FinalPhase == phases::Link && PL.size() == 1) { 2681 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 2682 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 2683 } 2684 2685 // Claim ignored clang-cl options. 2686 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 2687 2688 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 2689 // to non-CUDA compilations and should not trigger warnings there. 2690 Args.ClaimAllArgs(options::OPT_cuda_host_only); 2691 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 2692 } 2693 2694 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args, 2695 phases::ID Phase, Action *Input) const { 2696 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 2697 2698 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 2699 // encode this in the steps because the intermediate type depends on 2700 // arguments. Just special case here. 2701 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 2702 return Input; 2703 2704 // Build the appropriate action. 2705 switch (Phase) { 2706 case phases::Link: 2707 llvm_unreachable("link action invalid here."); 2708 case phases::Preprocess: { 2709 types::ID OutputTy; 2710 // -{M, MM} alter the output type. 2711 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 2712 OutputTy = types::TY_Dependencies; 2713 } else { 2714 OutputTy = Input->getType(); 2715 if (!Args.hasFlag(options::OPT_frewrite_includes, 2716 options::OPT_fno_rewrite_includes, false) && 2717 !Args.hasFlag(options::OPT_frewrite_imports, 2718 options::OPT_fno_rewrite_imports, false) && 2719 !CCGenDiagnostics) 2720 OutputTy = types::getPreprocessedType(OutputTy); 2721 assert(OutputTy != types::TY_INVALID && 2722 "Cannot preprocess this input type!"); 2723 } 2724 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 2725 } 2726 case phases::Precompile: { 2727 types::ID OutputTy = getPrecompiledType(Input->getType()); 2728 assert(OutputTy != types::TY_INVALID && 2729 "Cannot precompile this input type!"); 2730 if (Args.hasArg(options::OPT_fsyntax_only)) { 2731 // Syntax checks should not emit a PCH file 2732 OutputTy = types::TY_Nothing; 2733 } 2734 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 2735 } 2736 case phases::Compile: { 2737 if (Args.hasArg(options::OPT_fsyntax_only)) 2738 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 2739 if (Args.hasArg(options::OPT_rewrite_objc)) 2740 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 2741 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 2742 return C.MakeAction<CompileJobAction>(Input, 2743 types::TY_RewrittenLegacyObjC); 2744 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) 2745 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 2746 if (Args.hasArg(options::OPT__migrate)) 2747 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 2748 if (Args.hasArg(options::OPT_emit_ast)) 2749 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 2750 if (Args.hasArg(options::OPT_module_file_info)) 2751 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 2752 if (Args.hasArg(options::OPT_verify_pch)) 2753 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 2754 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 2755 } 2756 case phases::Backend: { 2757 if (isUsingLTO()) { 2758 types::ID Output = 2759 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 2760 return C.MakeAction<BackendJobAction>(Input, Output); 2761 } 2762 if (Args.hasArg(options::OPT_emit_llvm)) { 2763 types::ID Output = 2764 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 2765 return C.MakeAction<BackendJobAction>(Input, Output); 2766 } 2767 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 2768 } 2769 case phases::Assemble: 2770 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 2771 } 2772 2773 llvm_unreachable("invalid phase in ConstructPhaseAction"); 2774 } 2775 2776 void Driver::BuildJobs(Compilation &C) const { 2777 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 2778 2779 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 2780 2781 // It is an error to provide a -o option if we are making multiple output 2782 // files. 2783 if (FinalOutput) { 2784 unsigned NumOutputs = 0; 2785 for (const Action *A : C.getActions()) 2786 if (A->getType() != types::TY_Nothing) 2787 ++NumOutputs; 2788 2789 if (NumOutputs > 1) { 2790 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 2791 FinalOutput = nullptr; 2792 } 2793 } 2794 2795 // Collect the list of architectures. 2796 llvm::StringSet<> ArchNames; 2797 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) 2798 for (const Arg *A : C.getArgs()) 2799 if (A->getOption().matches(options::OPT_arch)) 2800 ArchNames.insert(A->getValue()); 2801 2802 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 2803 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults; 2804 for (Action *A : C.getActions()) { 2805 // If we are linking an image for multiple archs then the linker wants 2806 // -arch_multiple and -final_output <final image name>. Unfortunately, this 2807 // doesn't fit in cleanly because we have to pass this information down. 2808 // 2809 // FIXME: This is a hack; find a cleaner way to integrate this into the 2810 // process. 2811 const char *LinkingOutput = nullptr; 2812 if (isa<LipoJobAction>(A)) { 2813 if (FinalOutput) 2814 LinkingOutput = FinalOutput->getValue(); 2815 else 2816 LinkingOutput = getDefaultImageName(); 2817 } 2818 2819 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 2820 /*BoundArch*/ StringRef(), 2821 /*AtTopLevel*/ true, 2822 /*MultipleArchs*/ ArchNames.size() > 1, 2823 /*LinkingOutput*/ LinkingOutput, CachedResults, 2824 /*TargetDeviceOffloadKind*/ Action::OFK_None); 2825 } 2826 2827 // If the user passed -Qunused-arguments or there were errors, don't warn 2828 // about any unused arguments. 2829 if (Diags.hasErrorOccurred() || 2830 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 2831 return; 2832 2833 // Claim -### here. 2834 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 2835 2836 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 2837 (void)C.getArgs().hasArg(options::OPT_driver_mode); 2838 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 2839 2840 for (Arg *A : C.getArgs()) { 2841 // FIXME: It would be nice to be able to send the argument to the 2842 // DiagnosticsEngine, so that extra values, position, and so on could be 2843 // printed. 2844 if (!A->isClaimed()) { 2845 if (A->getOption().hasFlag(options::NoArgumentUnused)) 2846 continue; 2847 2848 // Suppress the warning automatically if this is just a flag, and it is an 2849 // instance of an argument we already claimed. 2850 const Option &Opt = A->getOption(); 2851 if (Opt.getKind() == Option::FlagClass) { 2852 bool DuplicateClaimed = false; 2853 2854 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 2855 if (AA->isClaimed()) { 2856 DuplicateClaimed = true; 2857 break; 2858 } 2859 } 2860 2861 if (DuplicateClaimed) 2862 continue; 2863 } 2864 2865 // In clang-cl, don't mention unknown arguments here since they have 2866 // already been warned about. 2867 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 2868 Diag(clang::diag::warn_drv_unused_argument) 2869 << A->getAsString(C.getArgs()); 2870 } 2871 } 2872 } 2873 2874 namespace { 2875 /// Utility class to control the collapse of dependent actions and select the 2876 /// tools accordingly. 2877 class ToolSelector final { 2878 /// The tool chain this selector refers to. 2879 const ToolChain &TC; 2880 2881 /// The compilation this selector refers to. 2882 const Compilation &C; 2883 2884 /// The base action this selector refers to. 2885 const JobAction *BaseAction; 2886 2887 /// Set to true if the current toolchain refers to host actions. 2888 bool IsHostSelector; 2889 2890 /// Set to true if save-temps and embed-bitcode functionalities are active. 2891 bool SaveTemps; 2892 bool EmbedBitcode; 2893 2894 /// Get previous dependent action or null if that does not exist. If 2895 /// \a CanBeCollapsed is false, that action must be legal to collapse or 2896 /// null will be returned. 2897 const JobAction *getPrevDependentAction(const ActionList &Inputs, 2898 ActionList &SavedOffloadAction, 2899 bool CanBeCollapsed = true) { 2900 // An option can be collapsed only if it has a single input. 2901 if (Inputs.size() != 1) 2902 return nullptr; 2903 2904 Action *CurAction = *Inputs.begin(); 2905 if (CanBeCollapsed && 2906 !CurAction->isCollapsingWithNextDependentActionLegal()) 2907 return nullptr; 2908 2909 // If the input action is an offload action. Look through it and save any 2910 // offload action that can be dropped in the event of a collapse. 2911 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 2912 // If the dependent action is a device action, we will attempt to collapse 2913 // only with other device actions. Otherwise, we would do the same but 2914 // with host actions only. 2915 if (!IsHostSelector) { 2916 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 2917 CurAction = 2918 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 2919 if (CanBeCollapsed && 2920 !CurAction->isCollapsingWithNextDependentActionLegal()) 2921 return nullptr; 2922 SavedOffloadAction.push_back(OA); 2923 return dyn_cast<JobAction>(CurAction); 2924 } 2925 } else if (OA->hasHostDependence()) { 2926 CurAction = OA->getHostDependence(); 2927 if (CanBeCollapsed && 2928 !CurAction->isCollapsingWithNextDependentActionLegal()) 2929 return nullptr; 2930 SavedOffloadAction.push_back(OA); 2931 return dyn_cast<JobAction>(CurAction); 2932 } 2933 return nullptr; 2934 } 2935 2936 return dyn_cast<JobAction>(CurAction); 2937 } 2938 2939 /// Return true if an assemble action can be collapsed. 2940 bool canCollapseAssembleAction() const { 2941 return TC.useIntegratedAs() && !SaveTemps && 2942 !C.getArgs().hasArg(options::OPT_via_file_asm) && 2943 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 2944 !C.getArgs().hasArg(options::OPT__SLASH_Fa); 2945 } 2946 2947 /// Return true if a preprocessor action can be collapsed. 2948 bool canCollapsePreprocessorAction() const { 2949 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 2950 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 2951 !C.getArgs().hasArg(options::OPT_rewrite_objc); 2952 } 2953 2954 /// Struct that relates an action with the offload actions that would be 2955 /// collapsed with it. 2956 struct JobActionInfo final { 2957 /// The action this info refers to. 2958 const JobAction *JA = nullptr; 2959 /// The offload actions we need to take care off if this action is 2960 /// collapsed. 2961 ActionList SavedOffloadAction; 2962 }; 2963 2964 /// Append collapsed offload actions from the give nnumber of elements in the 2965 /// action info array. 2966 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 2967 ArrayRef<JobActionInfo> &ActionInfo, 2968 unsigned ElementNum) { 2969 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 2970 for (unsigned I = 0; I < ElementNum; ++I) 2971 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 2972 ActionInfo[I].SavedOffloadAction.end()); 2973 } 2974 2975 /// Functions that attempt to perform the combining. They detect if that is 2976 /// legal, and if so they update the inputs \a Inputs and the offload action 2977 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 2978 /// the combined action is returned. If the combining is not legal or if the 2979 /// tool does not exist, null is returned. 2980 /// Currently three kinds of collapsing are supported: 2981 /// - Assemble + Backend + Compile; 2982 /// - Assemble + Backend ; 2983 /// - Backend + Compile. 2984 const Tool * 2985 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 2986 const ActionList *&Inputs, 2987 ActionList &CollapsedOffloadAction) { 2988 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 2989 return nullptr; 2990 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 2991 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 2992 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 2993 if (!AJ || !BJ || !CJ) 2994 return nullptr; 2995 2996 // Get compiler tool. 2997 const Tool *T = TC.SelectTool(*CJ); 2998 if (!T) 2999 return nullptr; 3000 3001 // When using -fembed-bitcode, it is required to have the same tool (clang) 3002 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 3003 if (EmbedBitcode) { 3004 const Tool *BT = TC.SelectTool(*BJ); 3005 if (BT == T) 3006 return nullptr; 3007 } 3008 3009 if (!T->hasIntegratedAssembler()) 3010 return nullptr; 3011 3012 Inputs = &CJ->getInputs(); 3013 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 3014 /*NumElements=*/3); 3015 return T; 3016 } 3017 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 3018 const ActionList *&Inputs, 3019 ActionList &CollapsedOffloadAction) { 3020 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 3021 return nullptr; 3022 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 3023 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 3024 if (!AJ || !BJ) 3025 return nullptr; 3026 3027 // Retrieve the compile job, backend action must always be preceded by one. 3028 ActionList CompileJobOffloadActions; 3029 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions, 3030 /*CanBeCollapsed=*/false); 3031 if (!AJ || !BJ || !CJ) 3032 return nullptr; 3033 3034 assert(isa<CompileJobAction>(CJ) && 3035 "Expecting compile job preceding backend job."); 3036 3037 // Get compiler tool. 3038 const Tool *T = TC.SelectTool(*CJ); 3039 if (!T) 3040 return nullptr; 3041 3042 if (!T->hasIntegratedAssembler()) 3043 return nullptr; 3044 3045 Inputs = &BJ->getInputs(); 3046 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 3047 /*NumElements=*/2); 3048 return T; 3049 } 3050 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 3051 const ActionList *&Inputs, 3052 ActionList &CollapsedOffloadAction) { 3053 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction()) 3054 return nullptr; 3055 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 3056 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 3057 if (!BJ || !CJ) 3058 return nullptr; 3059 3060 // Get compiler tool. 3061 const Tool *T = TC.SelectTool(*CJ); 3062 if (!T) 3063 return nullptr; 3064 3065 if (T->canEmitIR() && (SaveTemps || EmbedBitcode)) 3066 return nullptr; 3067 3068 Inputs = &CJ->getInputs(); 3069 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 3070 /*NumElements=*/2); 3071 return T; 3072 } 3073 3074 /// Updates the inputs if the obtained tool supports combining with 3075 /// preprocessor action, and the current input is indeed a preprocessor 3076 /// action. If combining results in the collapse of offloading actions, those 3077 /// are appended to \a CollapsedOffloadAction. 3078 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs, 3079 ActionList &CollapsedOffloadAction) { 3080 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 3081 return; 3082 3083 // Attempt to get a preprocessor action dependence. 3084 ActionList PreprocessJobOffloadActions; 3085 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions); 3086 if (!PJ || !isa<PreprocessJobAction>(PJ)) 3087 return; 3088 3089 // This is legal to combine. Append any offload action we found and set the 3090 // current inputs to preprocessor inputs. 3091 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 3092 PreprocessJobOffloadActions.end()); 3093 Inputs = &PJ->getInputs(); 3094 } 3095 3096 public: 3097 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 3098 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 3099 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 3100 EmbedBitcode(EmbedBitcode) { 3101 assert(BaseAction && "Invalid base action."); 3102 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 3103 } 3104 3105 /// Check if a chain of actions can be combined and return the tool that can 3106 /// handle the combination of actions. The pointer to the current inputs \a 3107 /// Inputs and the list of offload actions \a CollapsedOffloadActions 3108 /// connected to collapsed actions are updated accordingly. The latter enables 3109 /// the caller of the selector to process them afterwards instead of just 3110 /// dropping them. If no suitable tool is found, null will be returned. 3111 const Tool *getTool(const ActionList *&Inputs, 3112 ActionList &CollapsedOffloadAction) { 3113 // 3114 // Get the largest chain of actions that we could combine. 3115 // 3116 3117 SmallVector<JobActionInfo, 5> ActionChain(1); 3118 ActionChain.back().JA = BaseAction; 3119 while (ActionChain.back().JA) { 3120 const Action *CurAction = ActionChain.back().JA; 3121 3122 // Grow the chain by one element. 3123 ActionChain.resize(ActionChain.size() + 1); 3124 JobActionInfo &AI = ActionChain.back(); 3125 3126 // Attempt to fill it with the 3127 AI.JA = 3128 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 3129 } 3130 3131 // Pop the last action info as it could not be filled. 3132 ActionChain.pop_back(); 3133 3134 // 3135 // Attempt to combine actions. If all combining attempts failed, just return 3136 // the tool of the provided action. At the end we attempt to combine the 3137 // action with any preprocessor action it may depend on. 3138 // 3139 3140 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 3141 CollapsedOffloadAction); 3142 if (!T) 3143 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 3144 if (!T) 3145 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 3146 if (!T) { 3147 Inputs = &BaseAction->getInputs(); 3148 T = TC.SelectTool(*BaseAction); 3149 } 3150 3151 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 3152 return T; 3153 } 3154 }; 3155 } 3156 3157 /// Return a string that uniquely identifies the result of a job. The bound arch 3158 /// is not necessarily represented in the toolchain's triple -- for example, 3159 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 3160 /// Also, we need to add the offloading device kind, as the same tool chain can 3161 /// be used for host and device for some programming models, e.g. OpenMP. 3162 static std::string GetTriplePlusArchString(const ToolChain *TC, 3163 StringRef BoundArch, 3164 Action::OffloadKind OffloadKind) { 3165 std::string TriplePlusArch = TC->getTriple().normalize(); 3166 if (!BoundArch.empty()) { 3167 TriplePlusArch += "-"; 3168 TriplePlusArch += BoundArch; 3169 } 3170 TriplePlusArch += "-"; 3171 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 3172 return TriplePlusArch; 3173 } 3174 3175 InputInfo Driver::BuildJobsForAction( 3176 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 3177 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 3178 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 3179 Action::OffloadKind TargetDeviceOffloadKind) const { 3180 std::pair<const Action *, std::string> ActionTC = { 3181 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 3182 auto CachedResult = CachedResults.find(ActionTC); 3183 if (CachedResult != CachedResults.end()) { 3184 return CachedResult->second; 3185 } 3186 InputInfo Result = BuildJobsForActionNoCache( 3187 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 3188 CachedResults, TargetDeviceOffloadKind); 3189 CachedResults[ActionTC] = Result; 3190 return Result; 3191 } 3192 3193 InputInfo Driver::BuildJobsForActionNoCache( 3194 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 3195 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 3196 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 3197 Action::OffloadKind TargetDeviceOffloadKind) const { 3198 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 3199 3200 InputInfoList OffloadDependencesInputInfo; 3201 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 3202 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 3203 // The offload action is expected to be used in four different situations. 3204 // 3205 // a) Set a toolchain/architecture/kind for a host action: 3206 // Host Action 1 -> OffloadAction -> Host Action 2 3207 // 3208 // b) Set a toolchain/architecture/kind for a device action; 3209 // Device Action 1 -> OffloadAction -> Device Action 2 3210 // 3211 // c) Specify a device dependence to a host action; 3212 // Device Action 1 _ 3213 // \ 3214 // Host Action 1 ---> OffloadAction -> Host Action 2 3215 // 3216 // d) Specify a host dependence to a device action. 3217 // Host Action 1 _ 3218 // \ 3219 // Device Action 1 ---> OffloadAction -> Device Action 2 3220 // 3221 // For a) and b), we just return the job generated for the dependence. For 3222 // c) and d) we override the current action with the host/device dependence 3223 // if the current toolchain is host/device and set the offload dependences 3224 // info with the jobs obtained from the device/host dependence(s). 3225 3226 // If there is a single device option, just generate the job for it. 3227 if (OA->hasSingleDeviceDependence()) { 3228 InputInfo DevA; 3229 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 3230 const char *DepBoundArch) { 3231 DevA = 3232 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 3233 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 3234 CachedResults, DepA->getOffloadingDeviceKind()); 3235 }); 3236 return DevA; 3237 } 3238 3239 // If 'Action 2' is host, we generate jobs for the device dependences and 3240 // override the current action with the host dependence. Otherwise, we 3241 // generate the host dependences and override the action with the device 3242 // dependence. The dependences can't therefore be a top-level action. 3243 OA->doOnEachDependence( 3244 /*IsHostDependence=*/BuildingForOffloadDevice, 3245 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 3246 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 3247 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 3248 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 3249 DepA->getOffloadingDeviceKind())); 3250 }); 3251 3252 A = BuildingForOffloadDevice 3253 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 3254 : OA->getHostDependence(); 3255 } 3256 3257 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 3258 // FIXME: It would be nice to not claim this here; maybe the old scheme of 3259 // just using Args was better? 3260 const Arg &Input = IA->getInputArg(); 3261 Input.claim(); 3262 if (Input.getOption().matches(options::OPT_INPUT)) { 3263 const char *Name = Input.getValue(); 3264 return InputInfo(A, Name, /* BaseInput = */ Name); 3265 } 3266 return InputInfo(A, &Input, /* BaseInput = */ ""); 3267 } 3268 3269 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 3270 const ToolChain *TC; 3271 StringRef ArchName = BAA->getArchName(); 3272 3273 if (!ArchName.empty()) 3274 TC = &getToolChain(C.getArgs(), 3275 computeTargetTriple(*this, DefaultTargetTriple, 3276 C.getArgs(), ArchName)); 3277 else 3278 TC = &C.getDefaultToolChain(); 3279 3280 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 3281 MultipleArchs, LinkingOutput, CachedResults, 3282 TargetDeviceOffloadKind); 3283 } 3284 3285 3286 const ActionList *Inputs = &A->getInputs(); 3287 3288 const JobAction *JA = cast<JobAction>(A); 3289 ActionList CollapsedOffloadActions; 3290 3291 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 3292 embedBitcodeInObject() && !isUsingLTO()); 3293 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 3294 3295 if (!T) 3296 return InputInfo(); 3297 3298 // If we've collapsed action list that contained OffloadAction we 3299 // need to build jobs for host/device-side inputs it may have held. 3300 for (const auto *OA : CollapsedOffloadActions) 3301 cast<OffloadAction>(OA)->doOnEachDependence( 3302 /*IsHostDependence=*/BuildingForOffloadDevice, 3303 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 3304 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 3305 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 3306 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 3307 DepA->getOffloadingDeviceKind())); 3308 }); 3309 3310 // Only use pipes when there is exactly one input. 3311 InputInfoList InputInfos; 3312 for (const Action *Input : *Inputs) { 3313 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 3314 // shouldn't get temporary output names. 3315 // FIXME: Clean this up. 3316 bool SubJobAtTopLevel = 3317 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 3318 InputInfos.push_back(BuildJobsForAction( 3319 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 3320 CachedResults, A->getOffloadingDeviceKind())); 3321 } 3322 3323 // Always use the first input as the base input. 3324 const char *BaseInput = InputInfos[0].getBaseInput(); 3325 3326 // ... except dsymutil actions, which use their actual input as the base 3327 // input. 3328 if (JA->getType() == types::TY_dSYM) 3329 BaseInput = InputInfos[0].getFilename(); 3330 3331 // Append outputs of offload device jobs to the input list 3332 if (!OffloadDependencesInputInfo.empty()) 3333 InputInfos.append(OffloadDependencesInputInfo.begin(), 3334 OffloadDependencesInputInfo.end()); 3335 3336 // Set the effective triple of the toolchain for the duration of this job. 3337 llvm::Triple EffectiveTriple; 3338 const ToolChain &ToolTC = T->getToolChain(); 3339 const ArgList &Args = 3340 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 3341 if (InputInfos.size() != 1) { 3342 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 3343 } else { 3344 // Pass along the input type if it can be unambiguously determined. 3345 EffectiveTriple = llvm::Triple( 3346 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 3347 } 3348 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 3349 3350 // Determine the place to write output to, if any. 3351 InputInfo Result; 3352 InputInfoList UnbundlingResults; 3353 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 3354 // If we have an unbundling job, we need to create results for all the 3355 // outputs. We also update the results cache so that other actions using 3356 // this unbundling action can get the right results. 3357 for (auto &UI : UA->getDependentActionsInfo()) { 3358 assert(UI.DependentOffloadKind != Action::OFK_None && 3359 "Unbundling with no offloading??"); 3360 3361 // Unbundling actions are never at the top level. When we generate the 3362 // offloading prefix, we also do that for the host file because the 3363 // unbundling action does not change the type of the output which can 3364 // cause a overwrite. 3365 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 3366 UI.DependentOffloadKind, 3367 UI.DependentToolChain->getTriple().normalize(), 3368 /*CreatePrefixForHost=*/true); 3369 auto CurI = InputInfo( 3370 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 3371 /*AtTopLevel=*/false, MultipleArchs, 3372 OffloadingPrefix), 3373 BaseInput); 3374 // Save the unbundling result. 3375 UnbundlingResults.push_back(CurI); 3376 3377 // Get the unique string identifier for this dependence and cache the 3378 // result. 3379 CachedResults[{A, GetTriplePlusArchString( 3380 UI.DependentToolChain, UI.DependentBoundArch, 3381 UI.DependentOffloadKind)}] = CurI; 3382 } 3383 3384 // Now that we have all the results generated, select the one that should be 3385 // returned for the current depending action. 3386 std::pair<const Action *, std::string> ActionTC = { 3387 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 3388 assert(CachedResults.find(ActionTC) != CachedResults.end() && 3389 "Result does not exist??"); 3390 Result = CachedResults[ActionTC]; 3391 } else if (JA->getType() == types::TY_Nothing) 3392 Result = InputInfo(A, BaseInput); 3393 else { 3394 // We only have to generate a prefix for the host if this is not a top-level 3395 // action. 3396 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 3397 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 3398 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() && 3399 !AtTopLevel); 3400 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 3401 AtTopLevel, MultipleArchs, 3402 OffloadingPrefix), 3403 BaseInput); 3404 } 3405 3406 if (CCCPrintBindings && !CCGenDiagnostics) { 3407 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 3408 << " - \"" << T->getName() << "\", inputs: ["; 3409 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 3410 llvm::errs() << InputInfos[i].getAsString(); 3411 if (i + 1 != e) 3412 llvm::errs() << ", "; 3413 } 3414 if (UnbundlingResults.empty()) 3415 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 3416 else { 3417 llvm::errs() << "], outputs: ["; 3418 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 3419 llvm::errs() << UnbundlingResults[i].getAsString(); 3420 if (i + 1 != e) 3421 llvm::errs() << ", "; 3422 } 3423 llvm::errs() << "] \n"; 3424 } 3425 } else { 3426 if (UnbundlingResults.empty()) 3427 T->ConstructJob( 3428 C, *JA, Result, InputInfos, 3429 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 3430 LinkingOutput); 3431 else 3432 T->ConstructJobMultipleOutputs( 3433 C, *JA, UnbundlingResults, InputInfos, 3434 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 3435 LinkingOutput); 3436 } 3437 return Result; 3438 } 3439 3440 const char *Driver::getDefaultImageName() const { 3441 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 3442 return Target.isOSWindows() ? "a.exe" : "a.out"; 3443 } 3444 3445 /// \brief Create output filename based on ArgValue, which could either be a 3446 /// full filename, filename without extension, or a directory. If ArgValue 3447 /// does not provide a filename, then use BaseName, and use the extension 3448 /// suitable for FileType. 3449 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 3450 StringRef BaseName, 3451 types::ID FileType) { 3452 SmallString<128> Filename = ArgValue; 3453 3454 if (ArgValue.empty()) { 3455 // If the argument is empty, output to BaseName in the current dir. 3456 Filename = BaseName; 3457 } else if (llvm::sys::path::is_separator(Filename.back())) { 3458 // If the argument is a directory, output to BaseName in that dir. 3459 llvm::sys::path::append(Filename, BaseName); 3460 } 3461 3462 if (!llvm::sys::path::has_extension(ArgValue)) { 3463 // If the argument didn't provide an extension, then set it. 3464 const char *Extension = types::getTypeTempSuffix(FileType, true); 3465 3466 if (FileType == types::TY_Image && 3467 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 3468 // The output file is a dll. 3469 Extension = "dll"; 3470 } 3471 3472 llvm::sys::path::replace_extension(Filename, Extension); 3473 } 3474 3475 return Args.MakeArgString(Filename.c_str()); 3476 } 3477 3478 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 3479 const char *BaseInput, 3480 StringRef BoundArch, bool AtTopLevel, 3481 bool MultipleArchs, 3482 StringRef OffloadingPrefix) const { 3483 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 3484 // Output to a user requested destination? 3485 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 3486 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 3487 return C.addResultFile(FinalOutput->getValue(), &JA); 3488 } 3489 3490 // For /P, preprocess to file named after BaseInput. 3491 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 3492 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 3493 StringRef BaseName = llvm::sys::path::filename(BaseInput); 3494 StringRef NameArg; 3495 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 3496 NameArg = A->getValue(); 3497 return C.addResultFile( 3498 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 3499 &JA); 3500 } 3501 3502 // Default to writing to stdout? 3503 if (AtTopLevel && !CCGenDiagnostics && 3504 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 3505 return "-"; 3506 3507 // Is this the assembly listing for /FA? 3508 if (JA.getType() == types::TY_PP_Asm && 3509 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 3510 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 3511 // Use /Fa and the input filename to determine the asm file name. 3512 StringRef BaseName = llvm::sys::path::filename(BaseInput); 3513 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 3514 return C.addResultFile( 3515 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 3516 &JA); 3517 } 3518 3519 // Output to a temporary file? 3520 if ((!AtTopLevel && !isSaveTempsEnabled() && 3521 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 3522 CCGenDiagnostics) { 3523 StringRef Name = llvm::sys::path::filename(BaseInput); 3524 std::pair<StringRef, StringRef> Split = Name.split('.'); 3525 std::string TmpName = GetTemporaryPath( 3526 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 3527 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 3528 } 3529 3530 SmallString<128> BasePath(BaseInput); 3531 StringRef BaseName; 3532 3533 // Dsymutil actions should use the full path. 3534 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 3535 BaseName = BasePath; 3536 else 3537 BaseName = llvm::sys::path::filename(BasePath); 3538 3539 // Determine what the derived output name should be. 3540 const char *NamedOutput; 3541 3542 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 3543 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 3544 // The /Fo or /o flag decides the object filename. 3545 StringRef Val = 3546 C.getArgs() 3547 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 3548 ->getValue(); 3549 NamedOutput = 3550 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 3551 } else if (JA.getType() == types::TY_Image && 3552 C.getArgs().hasArg(options::OPT__SLASH_Fe, 3553 options::OPT__SLASH_o)) { 3554 // The /Fe or /o flag names the linked file. 3555 StringRef Val = 3556 C.getArgs() 3557 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 3558 ->getValue(); 3559 NamedOutput = 3560 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 3561 } else if (JA.getType() == types::TY_Image) { 3562 if (IsCLMode()) { 3563 // clang-cl uses BaseName for the executable name. 3564 NamedOutput = 3565 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 3566 } else { 3567 SmallString<128> Output(getDefaultImageName()); 3568 Output += OffloadingPrefix; 3569 if (MultipleArchs && !BoundArch.empty()) { 3570 Output += "-"; 3571 Output.append(BoundArch); 3572 } 3573 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 3574 } 3575 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 3576 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 3577 } else { 3578 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 3579 assert(Suffix && "All types used for output should have a suffix."); 3580 3581 std::string::size_type End = std::string::npos; 3582 if (!types::appendSuffixForType(JA.getType())) 3583 End = BaseName.rfind('.'); 3584 SmallString<128> Suffixed(BaseName.substr(0, End)); 3585 Suffixed += OffloadingPrefix; 3586 if (MultipleArchs && !BoundArch.empty()) { 3587 Suffixed += "-"; 3588 Suffixed.append(BoundArch); 3589 } 3590 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 3591 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 3592 // optimized bitcode output. 3593 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) && 3594 JA.getType() == types::TY_LLVM_BC) 3595 Suffixed += ".tmp"; 3596 Suffixed += '.'; 3597 Suffixed += Suffix; 3598 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 3599 } 3600 3601 // Prepend object file path if -save-temps=obj 3602 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 3603 JA.getType() != types::TY_PCH) { 3604 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 3605 SmallString<128> TempPath(FinalOutput->getValue()); 3606 llvm::sys::path::remove_filename(TempPath); 3607 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 3608 llvm::sys::path::append(TempPath, OutputFileName); 3609 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 3610 } 3611 3612 // If we're saving temps and the temp file conflicts with the input file, 3613 // then avoid overwriting input file. 3614 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 3615 bool SameFile = false; 3616 SmallString<256> Result; 3617 llvm::sys::fs::current_path(Result); 3618 llvm::sys::path::append(Result, BaseName); 3619 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 3620 // Must share the same path to conflict. 3621 if (SameFile) { 3622 StringRef Name = llvm::sys::path::filename(BaseInput); 3623 std::pair<StringRef, StringRef> Split = Name.split('.'); 3624 std::string TmpName = GetTemporaryPath( 3625 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 3626 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 3627 } 3628 } 3629 3630 // As an annoying special case, PCH generation doesn't strip the pathname. 3631 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 3632 llvm::sys::path::remove_filename(BasePath); 3633 if (BasePath.empty()) 3634 BasePath = NamedOutput; 3635 else 3636 llvm::sys::path::append(BasePath, NamedOutput); 3637 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 3638 } else { 3639 return C.addResultFile(NamedOutput, &JA); 3640 } 3641 } 3642 3643 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 3644 // Respect a limited subset of the '-Bprefix' functionality in GCC by 3645 // attempting to use this prefix when looking for file paths. 3646 for (const std::string &Dir : PrefixDirs) { 3647 if (Dir.empty()) 3648 continue; 3649 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 3650 llvm::sys::path::append(P, Name); 3651 if (llvm::sys::fs::exists(Twine(P))) 3652 return P.str(); 3653 } 3654 3655 SmallString<128> P(ResourceDir); 3656 llvm::sys::path::append(P, Name); 3657 if (llvm::sys::fs::exists(Twine(P))) 3658 return P.str(); 3659 3660 for (const std::string &Dir : TC.getFilePaths()) { 3661 if (Dir.empty()) 3662 continue; 3663 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 3664 llvm::sys::path::append(P, Name); 3665 if (llvm::sys::fs::exists(Twine(P))) 3666 return P.str(); 3667 } 3668 3669 return Name; 3670 } 3671 3672 void Driver::generatePrefixedToolNames( 3673 StringRef Tool, const ToolChain &TC, 3674 SmallVectorImpl<std::string> &Names) const { 3675 // FIXME: Needs a better variable than DefaultTargetTriple 3676 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str()); 3677 Names.emplace_back(Tool); 3678 3679 // Allow the discovery of tools prefixed with LLVM's default target triple. 3680 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple(); 3681 if (LLVMDefaultTargetTriple != DefaultTargetTriple) 3682 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str()); 3683 } 3684 3685 static bool ScanDirForExecutable(SmallString<128> &Dir, 3686 ArrayRef<std::string> Names) { 3687 for (const auto &Name : Names) { 3688 llvm::sys::path::append(Dir, Name); 3689 if (llvm::sys::fs::can_execute(Twine(Dir))) 3690 return true; 3691 llvm::sys::path::remove_filename(Dir); 3692 } 3693 return false; 3694 } 3695 3696 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 3697 SmallVector<std::string, 2> TargetSpecificExecutables; 3698 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 3699 3700 // Respect a limited subset of the '-Bprefix' functionality in GCC by 3701 // attempting to use this prefix when looking for program paths. 3702 for (const auto &PrefixDir : PrefixDirs) { 3703 if (llvm::sys::fs::is_directory(PrefixDir)) { 3704 SmallString<128> P(PrefixDir); 3705 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 3706 return P.str(); 3707 } else { 3708 SmallString<128> P((PrefixDir + Name).str()); 3709 if (llvm::sys::fs::can_execute(Twine(P))) 3710 return P.str(); 3711 } 3712 } 3713 3714 const ToolChain::path_list &List = TC.getProgramPaths(); 3715 for (const auto &Path : List) { 3716 SmallString<128> P(Path); 3717 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 3718 return P.str(); 3719 } 3720 3721 // If all else failed, search the path. 3722 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) 3723 if (llvm::ErrorOr<std::string> P = 3724 llvm::sys::findProgramByName(TargetSpecificExecutable)) 3725 return *P; 3726 3727 return Name; 3728 } 3729 3730 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 3731 SmallString<128> Path; 3732 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 3733 if (EC) { 3734 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 3735 return ""; 3736 } 3737 3738 return Path.str(); 3739 } 3740 3741 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 3742 SmallString<128> Output; 3743 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 3744 // FIXME: If anybody needs it, implement this obscure rule: 3745 // "If you specify a directory without a file name, the default file name 3746 // is VCx0.pch., where x is the major version of Visual C++ in use." 3747 Output = FpArg->getValue(); 3748 3749 // "If you do not specify an extension as part of the path name, an 3750 // extension of .pch is assumed. " 3751 if (!llvm::sys::path::has_extension(Output)) 3752 Output += ".pch"; 3753 } else { 3754 Output = BaseName; 3755 llvm::sys::path::replace_extension(Output, ".pch"); 3756 } 3757 return Output.str(); 3758 } 3759 3760 const ToolChain &Driver::getToolChain(const ArgList &Args, 3761 const llvm::Triple &Target) const { 3762 3763 auto &TC = ToolChains[Target.str()]; 3764 if (!TC) { 3765 switch (Target.getOS()) { 3766 case llvm::Triple::Haiku: 3767 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args); 3768 break; 3769 case llvm::Triple::Ananas: 3770 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args); 3771 break; 3772 case llvm::Triple::CloudABI: 3773 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args); 3774 break; 3775 case llvm::Triple::Darwin: 3776 case llvm::Triple::MacOSX: 3777 case llvm::Triple::IOS: 3778 case llvm::Triple::TvOS: 3779 case llvm::Triple::WatchOS: 3780 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args); 3781 break; 3782 case llvm::Triple::DragonFly: 3783 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args); 3784 break; 3785 case llvm::Triple::OpenBSD: 3786 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args); 3787 break; 3788 case llvm::Triple::Bitrig: 3789 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args); 3790 break; 3791 case llvm::Triple::NetBSD: 3792 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args); 3793 break; 3794 case llvm::Triple::FreeBSD: 3795 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args); 3796 break; 3797 case llvm::Triple::Minix: 3798 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args); 3799 break; 3800 case llvm::Triple::Linux: 3801 case llvm::Triple::ELFIAMCU: 3802 if (Target.getArch() == llvm::Triple::hexagon) 3803 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target, 3804 Args); 3805 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 3806 !Target.hasEnvironment()) 3807 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 3808 Args); 3809 else 3810 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args); 3811 break; 3812 case llvm::Triple::NaCl: 3813 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 3814 break; 3815 case llvm::Triple::Fuchsia: 3816 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args); 3817 break; 3818 case llvm::Triple::Solaris: 3819 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args); 3820 break; 3821 case llvm::Triple::AMDHSA: 3822 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 3823 break; 3824 case llvm::Triple::Win32: 3825 switch (Target.getEnvironment()) { 3826 default: 3827 if (Target.isOSBinFormatELF()) 3828 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 3829 else if (Target.isOSBinFormatMachO()) 3830 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args); 3831 else 3832 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 3833 break; 3834 case llvm::Triple::GNU: 3835 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args); 3836 break; 3837 case llvm::Triple::Itanium: 3838 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 3839 Args); 3840 break; 3841 case llvm::Triple::MSVC: 3842 case llvm::Triple::UnknownEnvironment: 3843 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 3844 break; 3845 } 3846 break; 3847 case llvm::Triple::PS4: 3848 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args); 3849 break; 3850 case llvm::Triple::Contiki: 3851 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args); 3852 break; 3853 default: 3854 // Of these targets, Hexagon is the only one that might have 3855 // an OS of Linux, in which case it got handled above already. 3856 switch (Target.getArch()) { 3857 case llvm::Triple::tce: 3858 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 3859 break; 3860 case llvm::Triple::tcele: 3861 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 3862 break; 3863 case llvm::Triple::hexagon: 3864 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target, 3865 Args); 3866 break; 3867 case llvm::Triple::lanai: 3868 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 3869 break; 3870 case llvm::Triple::xcore: 3871 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 3872 break; 3873 case llvm::Triple::wasm32: 3874 case llvm::Triple::wasm64: 3875 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args); 3876 break; 3877 case llvm::Triple::avr: 3878 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 3879 break; 3880 default: 3881 if (Target.getVendor() == llvm::Triple::Myriad) 3882 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target, 3883 Args); 3884 else if (toolchains::BareMetal::handlesTarget(Target)) 3885 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args); 3886 else if (Target.isOSBinFormatELF()) 3887 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 3888 else if (Target.isOSBinFormatMachO()) 3889 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args); 3890 else 3891 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 3892 } 3893 } 3894 } 3895 3896 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA 3897 // compiles always need two toolchains, the CUDA toolchain and the host 3898 // toolchain. So the only valid way to create a CUDA toolchain is via 3899 // CreateOffloadingDeviceToolChains. 3900 3901 return *TC; 3902 } 3903 3904 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 3905 // Say "no" if there is not exactly one input of a type clang understands. 3906 if (JA.size() != 1 || 3907 !types::isAcceptedByClang((*JA.input_begin())->getType())) 3908 return false; 3909 3910 // And say "no" if this is not a kind of action clang understands. 3911 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 3912 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 3913 return false; 3914 3915 return true; 3916 } 3917 3918 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 3919 /// grouped values as integers. Numbers which are not provided are set to 0. 3920 /// 3921 /// \return True if the entire string was parsed (9.2), or all groups were 3922 /// parsed (10.3.5extrastuff). 3923 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 3924 unsigned &Micro, bool &HadExtra) { 3925 HadExtra = false; 3926 3927 Major = Minor = Micro = 0; 3928 if (Str.empty()) 3929 return false; 3930 3931 if (Str.consumeInteger(10, Major)) 3932 return false; 3933 if (Str.empty()) 3934 return true; 3935 if (Str[0] != '.') 3936 return false; 3937 3938 Str = Str.drop_front(1); 3939 3940 if (Str.consumeInteger(10, Minor)) 3941 return false; 3942 if (Str.empty()) 3943 return true; 3944 if (Str[0] != '.') 3945 return false; 3946 Str = Str.drop_front(1); 3947 3948 if (Str.consumeInteger(10, Micro)) 3949 return false; 3950 if (!Str.empty()) 3951 HadExtra = true; 3952 return true; 3953 } 3954 3955 /// Parse digits from a string \p Str and fulfill \p Digits with 3956 /// the parsed numbers. This method assumes that the max number of 3957 /// digits to look for is equal to Digits.size(). 3958 /// 3959 /// \return True if the entire string was parsed and there are 3960 /// no extra characters remaining at the end. 3961 bool Driver::GetReleaseVersion(StringRef Str, 3962 MutableArrayRef<unsigned> Digits) { 3963 if (Str.empty()) 3964 return false; 3965 3966 unsigned CurDigit = 0; 3967 while (CurDigit < Digits.size()) { 3968 unsigned Digit; 3969 if (Str.consumeInteger(10, Digit)) 3970 return false; 3971 Digits[CurDigit] = Digit; 3972 if (Str.empty()) 3973 return true; 3974 if (Str[0] != '.') 3975 return false; 3976 Str = Str.drop_front(1); 3977 CurDigit++; 3978 } 3979 3980 // More digits than requested, bail out... 3981 return false; 3982 } 3983 3984 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const { 3985 unsigned IncludedFlagsBitmask = 0; 3986 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 3987 3988 if (Mode == CLMode) { 3989 // Include CL and Core options. 3990 IncludedFlagsBitmask |= options::CLOption; 3991 IncludedFlagsBitmask |= options::CoreOption; 3992 } else { 3993 ExcludedFlagsBitmask |= options::CLOption; 3994 } 3995 3996 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 3997 } 3998 3999 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 4000 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 4001 } 4002