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