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