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