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