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