Bug Summary

File:tools/clang/lib/Driver/Driver.cpp
Warning:line 1834, column 17
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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