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