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