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