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