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