Bug Summary

File:llvm/include/llvm/ADT/Twine.h
Warning:line 272, column 11
Array access (from variable 'Str') results in a null pointer dereference

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Driver.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Driver -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Driver -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Driver/Driver.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Driver/Driver.cpp

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

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/Twine.h

1//===- Twine.h - Fast Temporary String Concatenation ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_ADT_TWINE_H
10#define LLVM_ADT_TWINE_H
11
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/ErrorHandling.h"
15#include <cassert>
16#include <cstdint>
17#include <string>
18#if __cplusplus201402L > 201402L
19#include <string_view>
20#endif
21
22namespace llvm {
23
24 class formatv_object_base;
25 class raw_ostream;
26
27 /// Twine - A lightweight data structure for efficiently representing the
28 /// concatenation of temporary values as strings.
29 ///
30 /// A Twine is a kind of rope, it represents a concatenated string using a
31 /// binary-tree, where the string is the preorder of the nodes. Since the
32 /// Twine can be efficiently rendered into a buffer when its result is used,
33 /// it avoids the cost of generating temporary values for intermediate string
34 /// results -- particularly in cases when the Twine result is never
35 /// required. By explicitly tracking the type of leaf nodes, we can also avoid
36 /// the creation of temporary strings for conversions operations (such as
37 /// appending an integer to a string).
38 ///
39 /// A Twine is not intended for use directly and should not be stored, its
40 /// implementation relies on the ability to store pointers to temporary stack
41 /// objects which may be deallocated at the end of a statement. Twines should
42 /// only be used accepted as const references in arguments, when an API wishes
43 /// to accept possibly-concatenated strings.
44 ///
45 /// Twines support a special 'null' value, which always concatenates to form
46 /// itself, and renders as an empty string. This can be returned from APIs to
47 /// effectively nullify any concatenations performed on the result.
48 ///
49 /// \b Implementation
50 ///
51 /// Given the nature of a Twine, it is not possible for the Twine's
52 /// concatenation method to construct interior nodes; the result must be
53 /// represented inside the returned value. For this reason a Twine object
54 /// actually holds two values, the left- and right-hand sides of a
55 /// concatenation. We also have nullary Twine objects, which are effectively
56 /// sentinel values that represent empty strings.
57 ///
58 /// Thus, a Twine can effectively have zero, one, or two children. The \see
59 /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
60 /// testing the number of children.
61 ///
62 /// We maintain a number of invariants on Twine objects (FIXME: Why):
63 /// - Nullary twines are always represented with their Kind on the left-hand
64 /// side, and the Empty kind on the right-hand side.
65 /// - Unary twines are always represented with the value on the left-hand
66 /// side, and the Empty kind on the right-hand side.
67 /// - If a Twine has another Twine as a child, that child should always be
68 /// binary (otherwise it could have been folded into the parent).
69 ///
70 /// These invariants are check by \see isValid().
71 ///
72 /// \b Efficiency Considerations
73 ///
74 /// The Twine is designed to yield efficient and small code for common
75 /// situations. For this reason, the concat() method is inlined so that
76 /// concatenations of leaf nodes can be optimized into stores directly into a
77 /// single stack allocated object.
78 ///
79 /// In practice, not all compilers can be trusted to optimize concat() fully,
80 /// so we provide two additional methods (and accompanying operator+
81 /// overloads) to guarantee that particularly important cases (cstring plus
82 /// StringRef) codegen as desired.
83 class Twine {
84 /// NodeKind - Represent the type of an argument.
85 enum NodeKind : unsigned char {
86 /// An empty string; the result of concatenating anything with it is also
87 /// empty.
88 NullKind,
89
90 /// The empty string.
91 EmptyKind,
92
93 /// A pointer to a Twine instance.
94 TwineKind,
95
96 /// A pointer to a C string instance.
97 CStringKind,
98
99 /// A pointer to an std::string instance.
100 StdStringKind,
101
102 /// A Pointer and Length representation. Used for std::string_view,
103 /// StringRef, and SmallString. Can't use a StringRef here
104 /// because they are not trivally constructible.
105 PtrAndLengthKind,
106
107 /// A pointer to a formatv_object_base instance.
108 FormatvObjectKind,
109
110 /// A char value, to render as a character.
111 CharKind,
112
113 /// An unsigned int value, to render as an unsigned decimal integer.
114 DecUIKind,
115
116 /// An int value, to render as a signed decimal integer.
117 DecIKind,
118
119 /// A pointer to an unsigned long value, to render as an unsigned decimal
120 /// integer.
121 DecULKind,
122
123 /// A pointer to a long value, to render as a signed decimal integer.
124 DecLKind,
125
126 /// A pointer to an unsigned long long value, to render as an unsigned
127 /// decimal integer.
128 DecULLKind,
129
130 /// A pointer to a long long value, to render as a signed decimal integer.
131 DecLLKind,
132
133 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
134 /// integer.
135 UHexKind
136 };
137
138 union Child
139 {
140 const Twine *twine;
141 const char *cString;
142 const std::string *stdString;
143 struct {
144 const char *ptr;
145 size_t length;
146 } ptrAndLength;
147 const formatv_object_base *formatvObject;
148 char character;
149 unsigned int decUI;
150 int decI;
151 const unsigned long *decUL;
152 const long *decL;
153 const unsigned long long *decULL;
154 const long long *decLL;
155 const uint64_t *uHex;
156 };
157
158 /// LHS - The prefix in the concatenation, which may be uninitialized for
159 /// Null or Empty kinds.
160 Child LHS;
161
162 /// RHS - The suffix in the concatenation, which may be uninitialized for
163 /// Null or Empty kinds.
164 Child RHS;
165
166 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
167 NodeKind LHSKind = EmptyKind;
168
169 /// RHSKind - The NodeKind of the right hand side, \see getRHSKind().
170 NodeKind RHSKind = EmptyKind;
171
172 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
173 explicit Twine(NodeKind Kind) : LHSKind(Kind) {
174 assert(isNullary() && "Invalid kind!")(static_cast <bool> (isNullary() && "Invalid kind!"
) ? void (0) : __assert_fail ("isNullary() && \"Invalid kind!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/Twine.h"
, 174, __extension__ __PRETTY_FUNCTION__))
;
175 }
176
177 /// Construct a binary twine.
178 explicit Twine(const Twine &LHS, const Twine &RHS)
179 : LHSKind(TwineKind), RHSKind(TwineKind) {
180 this->LHS.twine = &LHS;
181 this->RHS.twine = &RHS;
182 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/Twine.h"
, 182, __extension__ __PRETTY_FUNCTION__))
;
183 }
184
185 /// Construct a twine from explicit values.
186 explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind)
187 : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) {
188 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/Twine.h"
, 188, __extension__ __PRETTY_FUNCTION__))
;
189 }
190
191 /// Check for the null twine.
192 bool isNull() const {
193 return getLHSKind() == NullKind;
194 }
195
196 /// Check for the empty twine.
197 bool isEmpty() const {
198 return getLHSKind() == EmptyKind;
199 }
200
201 /// Check if this is a nullary twine (null or empty).
202 bool isNullary() const {
203 return isNull() || isEmpty();
204 }
205
206 /// Check if this is a unary twine.
207 bool isUnary() const {
208 return getRHSKind() == EmptyKind && !isNullary();
209 }
210
211 /// Check if this is a binary twine.
212 bool isBinary() const {
213 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
214 }
215
216 /// Check if this is a valid twine (satisfying the invariants on
217 /// order and number of arguments).
218 bool isValid() const {
219 // Nullary twines always have Empty on the RHS.
220 if (isNullary() && getRHSKind() != EmptyKind)
221 return false;
222
223 // Null should never appear on the RHS.
224 if (getRHSKind() == NullKind)
225 return false;
226
227 // The RHS cannot be non-empty if the LHS is empty.
228 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
229 return false;
230
231 // A twine child should always be binary.
232 if (getLHSKind() == TwineKind &&
233 !LHS.twine->isBinary())
234 return false;
235 if (getRHSKind() == TwineKind &&
236 !RHS.twine->isBinary())
237 return false;
238
239 return true;
240 }
241
242 /// Get the NodeKind of the left-hand side.
243 NodeKind getLHSKind() const { return LHSKind; }
244
245 /// Get the NodeKind of the right-hand side.
246 NodeKind getRHSKind() const { return RHSKind; }
247
248 /// Print one child from a twine.
249 void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
250
251 /// Print the representation of one child from a twine.
252 void printOneChildRepr(raw_ostream &OS, Child Ptr,
253 NodeKind Kind) const;
254
255 public:
256 /// @name Constructors
257 /// @{
258
259 /// Construct from an empty string.
260 /*implicit*/ Twine() {
261 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/Twi