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