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