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