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