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