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