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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -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~++20220126101029+f487a76430a0/clang/lib/Driver -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -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~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -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-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Driver/Driver.cpp

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

/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/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