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