Bug Summary

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

Annotated Source Code

1//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Driver/Driver.h"
11#include "InputInfo.h"
12#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
14#include "ToolChains/Bitrig.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/Haiku.h"
26#include "ToolChains/Hexagon.h"
27#include "ToolChains/Lanai.h"
28#include "ToolChains/Linux.h"
29#include "ToolChains/MinGW.h"
30#include "ToolChains/Minix.h"
31#include "ToolChains/MipsLinux.h"
32#include "ToolChains/MSVC.h"
33#include "ToolChains/Myriad.h"
34#include "ToolChains/NaCl.h"
35#include "ToolChains/NetBSD.h"
36#include "ToolChains/OpenBSD.h"
37#include "ToolChains/PS4CPU.h"
38#include "ToolChains/Solaris.h"
39#include "ToolChains/TCE.h"
40#include "ToolChains/WebAssembly.h"
41#include "ToolChains/XCore.h"
42#include "clang/Basic/Version.h"
43#include "clang/Basic/VirtualFileSystem.h"
44#include "clang/Config/config.h"
45#include "clang/Driver/Action.h"
46#include "clang/Driver/Compilation.h"
47#include "clang/Driver/DriverDiagnostic.h"
48#include "clang/Driver/Job.h"
49#include "clang/Driver/Options.h"
50#include "clang/Driver/SanitizerArgs.h"
51#include "clang/Driver/Tool.h"
52#include "clang/Driver/ToolChain.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/SmallSet.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/ADT/StringSet.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/Option/Arg.h"
60#include "llvm/Option/ArgList.h"
61#include "llvm/Option/OptSpecifier.h"
62#include "llvm/Option/OptTable.h"
63#include "llvm/Option/Option.h"
64#include "llvm/Support/ErrorHandling.h"
65#include "llvm/Support/FileSystem.h"
66#include "llvm/Support/Path.h"
67#include "llvm/Support/PrettyStackTrace.h"
68#include "llvm/Support/Process.h"
69#include "llvm/Support/Program.h"
70#include "llvm/Support/raw_ostream.h"
71#include <map>
72#include <memory>
73#include <utility>
74#if LLVM_ON_UNIX1
75#include <unistd.h> // getpid
76#endif
77
78using namespace clang::driver;
79using namespace clang;
80using namespace llvm::opt;
81
82Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
83 DiagnosticsEngine &Diags,
84 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
85 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
86 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
87 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
88 SysRoot(DEFAULT_SYSROOT""), UseStdLib(true),
89 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
90 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
91 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
92 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
93 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
94 GenReproducer(false), SuppressMissingInputWarning(false) {
95
96 // Provide a sane fallback if no VFS is specified.
97 if (!this->VFS)
98 this->VFS = vfs::getRealFileSystem();
99
100 Name = llvm::sys::path::filename(ClangExecutable);
101 Dir = llvm::sys::path::parent_path(ClangExecutable);
102 InstalledDir = Dir; // Provide a sensible default installed dir.
103
104 // Compute the path to the resource directory.
105 StringRef ClangResourceDir(CLANG_RESOURCE_DIR"");
106 SmallString<128> P(Dir);
107 if (ClangResourceDir != "") {
108 llvm::sys::path::append(P, ClangResourceDir);
109 } else {
110 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX"");
111 P = llvm::sys::path::parent_path(Dir);
112 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
113 CLANG_VERSION_STRING"5.0.0");
114 }
115 ResourceDir = P.str();
116}
117
118void Driver::ParseDriverMode(StringRef ProgramName,
119 ArrayRef<const char *> Args) {
120 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
121 StringRef DefaultMode(Default.second);
122 setDriverModeFromOption(DefaultMode);
123
124 for (const char *ArgPtr : Args) {
125 // Ingore nullptrs, they are response file's EOL markers
126 if (ArgPtr == nullptr)
127 continue;
128 const StringRef Arg = ArgPtr;
129 setDriverModeFromOption(Arg);
130 }
131}
132
133void Driver::setDriverModeFromOption(StringRef Opt) {
134 const std::string OptName =
135 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
136 if (!Opt.startswith(OptName))
137 return;
138 StringRef Value = Opt.drop_front(OptName.size());
139
140 const unsigned M = llvm::StringSwitch<unsigned>(Value)
141 .Case("gcc", GCCMode)
142 .Case("g++", GXXMode)
143 .Case("cpp", CPPMode)
144 .Case("cl", CLMode)
145 .Default(~0U);
146
147 if (M != ~0U)
148 Mode = static_cast<DriverMode>(M);
149 else
150 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
151}
152
153InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
154 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
155
156 unsigned IncludedFlagsBitmask;
157 unsigned ExcludedFlagsBitmask;
158 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
159 getIncludeExcludeOptionFlagMasks();
160
161 unsigned MissingArgIndex, MissingArgCount;
162 InputArgList Args =
163 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
164 IncludedFlagsBitmask, ExcludedFlagsBitmask);
165
166 // Check for missing argument error.
167 if (MissingArgCount)
168 Diag(clang::diag::err_drv_missing_argument)
169 << Args.getArgString(MissingArgIndex) << MissingArgCount;
170
171 // Check for unsupported options.
172 for (const Arg *A : Args) {
173 if (A->getOption().hasFlag(options::Unsupported)) {
174 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
175 continue;
176 }
177
178 // Warn about -mcpu= without an argument.
179 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
180 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
181 }
182 }
183
184 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
185 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
186 diag::err_drv_unknown_argument)
187 << A->getAsString(Args);
188
189 return Args;
190}
191
192// Determine which compilation mode we are in. We look for options which
193// affect the phase, starting with the earliest phases, and record which
194// option we used to determine the final phase.
195phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
196 Arg **FinalPhaseArg) const {
197 Arg *PhaseArg = nullptr;
198 phases::ID FinalPhase;
199
200 // -{E,EP,P,M,MM} only run the preprocessor.
201 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
202 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
203 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
204 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
205 FinalPhase = phases::Preprocess;
206
207 // --precompile only runs up to precompilation.
208 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
209 FinalPhase = phases::Precompile;
210
211 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
212 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
213 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
214 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
215 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
216 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
217 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
218 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
219 options::OPT__analyze_auto)) ||
220 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
221 FinalPhase = phases::Compile;
222
223 // -S only runs up to the backend.
224 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
225 FinalPhase = phases::Backend;
226
227 // -c compilation only runs up to the assembler.
228 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
229 FinalPhase = phases::Assemble;
230
231 // Otherwise do everything.
232 } else
233 FinalPhase = phases::Link;
234
235 if (FinalPhaseArg)
236 *FinalPhaseArg = PhaseArg;
237
238 return FinalPhase;
239}
240
241static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
242 StringRef Value) {
243 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
244 Args.getBaseArgs().MakeIndex(Value), Value.data());
245 Args.AddSynthesizedArg(A);
246 A->claim();
247 return A;
248}
249
250DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
251 DerivedArgList *DAL = new DerivedArgList(Args);
252
253 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
254 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
255 for (Arg *A : Args) {
256 // Unfortunately, we have to parse some forwarding options (-Xassembler,
257 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
258 // (assembler and preprocessor), or bypass a previous driver ('collect2').
259
260 // Rewrite linker options, to replace --no-demangle with a custom internal
261 // option.
262 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
263 A->getOption().matches(options::OPT_Xlinker)) &&
264 A->containsValue("--no-demangle")) {
265 // Add the rewritten no-demangle argument.
266 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
267
268 // Add the remaining values as Xlinker arguments.
269 for (StringRef Val : A->getValues())
270 if (Val != "--no-demangle")
271 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
272
273 continue;
274 }
275
276 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
277 // some build systems. We don't try to be complete here because we don't
278 // care to encourage this usage model.
279 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
280 (A->getValue(0) == StringRef("-MD") ||
281 A->getValue(0) == StringRef("-MMD"))) {
282 // Rewrite to -MD/-MMD along with -MF.
283 if (A->getValue(0) == StringRef("-MD"))
284 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
285 else
286 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
287 if (A->getNumValues() == 2)
288 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
289 A->getValue(1));
290 continue;
291 }
292
293 // Rewrite reserved library names.
294 if (A->getOption().matches(options::OPT_l)) {
295 StringRef Value = A->getValue();
296
297 // Rewrite unless -nostdlib is present.
298 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
299 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
300 continue;
301 }
302
303 // Rewrite unconditionally.
304 if (Value == "cc_kext") {
305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
306 continue;
307 }
308 }
309
310 // Pick up inputs via the -- option.
311 if (A->getOption().matches(options::OPT__DASH_DASH)) {
312 A->claim();
313 for (StringRef Val : A->getValues())
314 DAL->append(MakeInputArg(*DAL, *Opts, Val));
315 continue;
316 }
317
318 DAL->append(A);
319 }
320
321 // Enforce -static if -miamcu is present.
322 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
323 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
324
325// Add a default value of -mlinker-version=, if one was given and the user
326// didn't specify one.
327#if defined(HOST_LINK_VERSION)
328 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
329 strlen(HOST_LINK_VERSION) > 0) {
330 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
331 HOST_LINK_VERSION);
332 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
333 }
334#endif
335
336 return DAL;
337}
338
339/// \brief Compute target triple from args.
340///
341/// This routine provides the logic to compute a target triple from various
342/// args passed to the driver and the default triple string.
343static llvm::Triple computeTargetTriple(const Driver &D,
344 StringRef DefaultTargetTriple,
345 const ArgList &Args,
346 StringRef DarwinArchName = "") {
347 // FIXME: Already done in Compilation *Driver::BuildCompilation
348 if (const Arg *A = Args.getLastArg(options::OPT_target))
349 DefaultTargetTriple = A->getValue();
350
351 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
352
353 // Handle Apple-specific options available here.
354 if (Target.isOSBinFormatMachO()) {
355 // If an explict Darwin arch name is given, that trumps all.
356 if (!DarwinArchName.empty()) {
357 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
358 return Target;
359 }
360
361 // Handle the Darwin '-arch' flag.
362 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
363 StringRef ArchName = A->getValue();
364 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
365 }
366 }
367
368 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
369 // '-mbig-endian'/'-EB'.
370 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
371 options::OPT_mbig_endian)) {
372 if (A->getOption().matches(options::OPT_mlittle_endian)) {
373 llvm::Triple LE = Target.getLittleEndianArchVariant();
374 if (LE.getArch() != llvm::Triple::UnknownArch)
375 Target = std::move(LE);
376 } else {
377 llvm::Triple BE = Target.getBigEndianArchVariant();
378 if (BE.getArch() != llvm::Triple::UnknownArch)
379 Target = std::move(BE);
380 }
381 }
382
383 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
384 if (Target.getArch() == llvm::Triple::tce ||
385 Target.getOS() == llvm::Triple::Minix)
386 return Target;
387
388 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
389 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
390 options::OPT_m32, options::OPT_m16);
391 if (A) {
392 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
393
394 if (A->getOption().matches(options::OPT_m64)) {
395 AT = Target.get64BitArchVariant().getArch();
396 if (Target.getEnvironment() == llvm::Triple::GNUX32)
397 Target.setEnvironment(llvm::Triple::GNU);
398 } else if (A->getOption().matches(options::OPT_mx32) &&
399 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
400 AT = llvm::Triple::x86_64;
401 Target.setEnvironment(llvm::Triple::GNUX32);
402 } else if (A->getOption().matches(options::OPT_m32)) {
403 AT = Target.get32BitArchVariant().getArch();
404 if (Target.getEnvironment() == llvm::Triple::GNUX32)
405 Target.setEnvironment(llvm::Triple::GNU);
406 } else if (A->getOption().matches(options::OPT_m16) &&
407 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
408 AT = llvm::Triple::x86;
409 Target.setEnvironment(llvm::Triple::CODE16);
410 }
411
412 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
413 Target.setArch(AT);
414 }
415
416 // Handle -miamcu flag.
417 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
418 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
419 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
420 << Target.str();
421
422 if (A && !A->getOption().matches(options::OPT_m32))
423 D.Diag(diag::err_drv_argument_not_allowed_with)
424 << "-miamcu" << A->getBaseArg().getAsString(Args);
425
426 Target.setArch(llvm::Triple::x86);
427 Target.setArchName("i586");
428 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
429 Target.setEnvironmentName("");
430 Target.setOS(llvm::Triple::ELFIAMCU);
431 Target.setVendor(llvm::Triple::UnknownVendor);
432 Target.setVendorName("intel");
433 }
434
435 return Target;
436}
437
438// \brief Parse the LTO options and record the type of LTO compilation
439// based on which -f(no-)?lto(=.*)? option occurs last.
440void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
441 LTOMode = LTOK_None;
442 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
443 options::OPT_fno_lto, false))
444 return;
445
446 StringRef LTOName("full");
447
448 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
449 if (A)
450 LTOName = A->getValue();
451
452 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
453 .Case("full", LTOK_Full)
454 .Case("thin", LTOK_Thin)
455 .Default(LTOK_Unknown);
456
457 if (LTOMode == LTOK_Unknown) {
458 assert(A)((A) ? static_cast<void> (0) : __assert_fail ("A", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 458, __PRETTY_FUNCTION__))
;
459 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
460 << A->getValue();
461 }
462}
463
464/// Compute the desired OpenMP runtime from the flags provided.
465Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
466 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME"libomp");
467
468 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
469 if (A)
470 RuntimeName = A->getValue();
471
472 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
473 .Case("libomp", OMPRT_OMP)
474 .Case("libgomp", OMPRT_GOMP)
475 .Case("libiomp5", OMPRT_IOMP5)
476 .Default(OMPRT_Unknown);
477
478 if (RT == OMPRT_Unknown) {
479 if (A)
480 Diag(diag::err_drv_unsupported_option_argument)
481 << A->getOption().getName() << A->getValue();
482 else
483 // FIXME: We could use a nicer diagnostic here.
484 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
485 }
486
487 return RT;
488}
489
490void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
491 InputList &Inputs) {
492
493 //
494 // CUDA
495 //
496 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
497 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
498 return types::isCuda(I.first);
499 })) {
500 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
501 const llvm::Triple &HostTriple = HostTC->getTriple();
502 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
503 : "nvptx-nvidia-cuda");
504 // Use the CUDA and host triples as the key into the ToolChains map, because
505 // the device toolchain we create depends on both.
506 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
507 if (!CudaTC) {
508 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
509 *this, CudaTriple, *HostTC, C.getInputArgs());
510 }
511 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
512 }
513
514 //
515 // OpenMP
516 //
517 // We need to generate an OpenMP toolchain if the user specified targets with
518 // the -fopenmp-targets option.
519 if (Arg *OpenMPTargets =
520 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
521 if (OpenMPTargets->getNumValues()) {
522 // We expect that -fopenmp-targets is always used in conjunction with the
523 // option -fopenmp specifying a valid runtime with offloading support,
524 // i.e. libomp or libiomp.
525 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
526 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
527 options::OPT_fno_openmp, false);
528 if (HasValidOpenMPRuntime) {
529 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
530 HasValidOpenMPRuntime =
531 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
532 }
533
534 if (HasValidOpenMPRuntime) {
535 llvm::StringMap<const char *> FoundNormalizedTriples;
536 for (const char *Val : OpenMPTargets->getValues()) {
537 llvm::Triple TT(Val);
538 std::string NormalizedName = TT.normalize();
539
540 // Make sure we don't have a duplicate triple.
541 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
542 if (Duplicate != FoundNormalizedTriples.end()) {
543 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
544 << Val << Duplicate->second;
545 continue;
546 }
547
548 // Store the current triple so that we can check for duplicates in the
549 // following iterations.
550 FoundNormalizedTriples[NormalizedName] = Val;
551
552 // If the specified target is invalid, emit a diagnostic.
553 if (TT.getArch() == llvm::Triple::UnknownArch)
554 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
555 else {
556 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
557 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
558 }
559 }
560 } else
561 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
562 } else
563 Diag(clang::diag::warn_drv_empty_joined_argument)
564 << OpenMPTargets->getAsString(C.getInputArgs());
565 }
566
567 //
568 // TODO: Add support for other offloading programming models here.
569 //
570
571 return;
572}
573
574Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
575 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
576
577 // FIXME: Handle environment options which affect driver behavior, somewhere
578 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
579
580 if (Optional<std::string> CompilerPathValue =
581 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
582 StringRef CompilerPath = *CompilerPathValue;
583 while (!CompilerPath.empty()) {
584 std::pair<StringRef, StringRef> Split =
585 CompilerPath.split(llvm::sys::EnvPathSeparator);
586 PrefixDirs.push_back(Split.first);
587 CompilerPath = Split.second;
588 }
589 }
590
591 // We look for the driver mode option early, because the mode can affect
592 // how other options are parsed.
593 ParseDriverMode(ClangExecutable, ArgList.slice(1));
594
595 // FIXME: What are we going to do with -V and -b?
596
597 // FIXME: This stuff needs to go into the Compilation, not the driver.
598 bool CCCPrintPhases;
599
600 InputArgList Args = ParseArgStrings(ArgList.slice(1));
601
602 // Silence driver warnings if requested
603 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
604
605 // -no-canonical-prefixes is used very early in main.
606 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
607
608 // Ignore -pipe.
609 Args.ClaimAllArgs(options::OPT_pipe);
610
611 // Extract -ccc args.
612 //
613 // FIXME: We need to figure out where this behavior should live. Most of it
614 // should be outside in the client; the parts that aren't should have proper
615 // options, either by introducing new ones or by overloading gcc ones like -V
616 // or -b.
617 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
618 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
619 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
620 CCCGenericGCCName = A->getValue();
621 CCCUsePCH =
622 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
623 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
624 options::OPT_fno_crash_diagnostics,
625 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
626 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
627 // and getToolChain is const.
628 if (IsCLMode()) {
629 // clang-cl targets MSVC-style Win32.
630 llvm::Triple T(DefaultTargetTriple);
631 T.setOS(llvm::Triple::Win32);
632 T.setVendor(llvm::Triple::PC);
633 T.setEnvironment(llvm::Triple::MSVC);
634 DefaultTargetTriple = T.str();
635 }
636 if (const Arg *A = Args.getLastArg(options::OPT_target))
637 DefaultTargetTriple = A->getValue();
638 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
639 Dir = InstalledDir = A->getValue();
640 for (const Arg *A : Args.filtered(options::OPT_B)) {
641 A->claim();
642 PrefixDirs.push_back(A->getValue(0));
643 }
644 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
645 SysRoot = A->getValue();
646 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
647 DyldPrefix = A->getValue();
648 if (Args.hasArg(options::OPT_nostdlib))
649 UseStdLib = false;
650
651 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
652 ResourceDir = A->getValue();
653
654 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
655 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
656 .Case("cwd", SaveTempsCwd)
657 .Case("obj", SaveTempsObj)
658 .Default(SaveTempsCwd);
659 }
660
661 setLTOMode(Args);
662
663 // Process -fembed-bitcode= flags.
664 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
665 StringRef Name = A->getValue();
666 unsigned Model = llvm::StringSwitch<unsigned>(Name)
667 .Case("off", EmbedNone)
668 .Case("all", EmbedBitcode)
669 .Case("bitcode", EmbedBitcode)
670 .Case("marker", EmbedMarker)
671 .Default(~0U);
672 if (Model == ~0U) {
673 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
674 << Name;
675 } else
676 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
677 }
678
679 std::unique_ptr<llvm::opt::InputArgList> UArgs =
680 llvm::make_unique<InputArgList>(std::move(Args));
681
682 // Perform the default argument translations.
683 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
684
685 // Owned by the host.
686 const ToolChain &TC = getToolChain(
687 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
688
689 // The compilation takes ownership of Args.
690 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
691
692 if (!HandleImmediateArgs(*C))
693 return C;
694
695 // Construct the list of inputs.
696 InputList Inputs;
697 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
698
699 // Populate the tool chains for the offloading devices, if any.
700 CreateOffloadingDeviceToolChains(*C, Inputs);
701
702 // Construct the list of abstract actions to perform for this compilation. On
703 // MachO targets this uses the driver-driver and universal actions.
704 if (TC.getTriple().isOSBinFormatMachO())
705 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
706 else
707 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
708
709 if (CCCPrintPhases) {
710 PrintActions(*C);
711 return C;
712 }
713
714 BuildJobs(*C);
715
716 return C;
717}
718
719static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
720 llvm::opt::ArgStringList ASL;
721 for (const auto *A : Args)
722 A->render(Args, ASL);
723
724 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
725 if (I != ASL.begin())
726 OS << ' ';
727 Command::printArg(OS, *I, true);
728 }
729 OS << '\n';
730}
731
732bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
733 SmallString<128> &CrashDiagDir) {
734 using namespace llvm::sys;
735 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 736, __PRETTY_FUNCTION__))
736 "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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 736, __PRETTY_FUNCTION__))
;
737
738 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
739 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
740 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
741 path::home_directory(CrashDiagDir);
742 if (CrashDiagDir.startswith("/var/root"))
743 CrashDiagDir = "/";
744 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
745 int PID =
746#if LLVM_ON_UNIX1
747 getpid();
748#else
749 0;
750#endif
751 std::error_code EC;
752 fs::file_status FileStatus;
753 TimePoint<> LastAccessTime;
754 SmallString<128> CrashFilePath;
755 // Lookup the .crash files and get the one generated by a subprocess spawned
756 // by this driver invocation.
757 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
758 File != FileEnd && !EC; File.increment(EC)) {
759 StringRef FileName = path::filename(File->path());
760 if (!FileName.startswith(Name))
761 continue;
762 if (fs::status(File->path(), FileStatus))
763 continue;
764 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
765 llvm::MemoryBuffer::getFile(File->path());
766 if (!CrashFile)
767 continue;
768 // The first line should start with "Process:", otherwise this isn't a real
769 // .crash file.
770 StringRef Data = CrashFile.get()->getBuffer();
771 if (!Data.startswith("Process:"))
772 continue;
773 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
774 size_t ParentProcPos = Data.find("Parent Process:");
775 if (ParentProcPos == StringRef::npos)
776 continue;
777 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
778 if (LineEnd == StringRef::npos)
779 continue;
780 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
781 int OpenBracket = -1, CloseBracket = -1;
782 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
783 if (ParentProcess[i] == '[')
784 OpenBracket = i;
785 if (ParentProcess[i] == ']')
786 CloseBracket = i;
787 }
788 // Extract the parent process PID from the .crash file and check whether
789 // it matches this driver invocation pid.
790 int CrashPID;
791 if (OpenBracket < 0 || CloseBracket < 0 ||
792 ParentProcess.slice(OpenBracket + 1, CloseBracket)
793 .getAsInteger(10, CrashPID) || CrashPID != PID) {
794 continue;
795 }
796
797 // Found a .crash file matching the driver pid. To avoid getting an older
798 // and misleading crash file, continue looking for the most recent.
799 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
800 // multiple crashes poiting to the same parent process. Since the driver
801 // does not collect pid information for the dispatched invocation there's
802 // currently no way to distinguish among them.
803 const auto FileAccessTime = FileStatus.getLastModificationTime();
804 if (FileAccessTime > LastAccessTime) {
805 CrashFilePath.assign(File->path());
806 LastAccessTime = FileAccessTime;
807 }
808 }
809
810 // If found, copy it over to the location of other reproducer files.
811 if (!CrashFilePath.empty()) {
812 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
813 if (EC)
814 return false;
815 return true;
816 }
817
818 return false;
819}
820
821// When clang crashes, produce diagnostic information including the fully
822// preprocessed source file(s). Request that the developer attach the
823// diagnostic information to a bug report.
824void Driver::generateCompilationDiagnostics(Compilation &C,
825 const Command &FailingCommand) {
826 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
827 return;
828
829 // Don't try to generate diagnostics for link or dsymutil jobs.
830 if (FailingCommand.getCreator().isLinkJob() ||
831 FailingCommand.getCreator().isDsymutilJob())
832 return;
833
834 // Print the version of the compiler.
835 PrintVersion(C, llvm::errs());
836
837 Diag(clang::diag::note_drv_command_failed_diag_msg)
838 << "PLEASE submit a bug report to " BUG_REPORT_URL"http://llvm.org/bugs/" " and include the "
839 "crash backtrace, preprocessed source, and associated run script.";
840
841 // Suppress driver output and emit preprocessor output to temp file.
842 Mode = CPPMode;
843 CCGenDiagnostics = true;
844
845 // Save the original job command(s).
846 Command Cmd = FailingCommand;
847
848 // Keep track of whether we produce any errors while trying to produce
849 // preprocessed sources.
850 DiagnosticErrorTrap Trap(Diags);
851
852 // Suppress tool output.
853 C.initCompilationForDiagnostics();
854
855 // Construct the list of inputs.
856 InputList Inputs;
857 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
858
859 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
860 bool IgnoreInput = false;
861
862 // Ignore input from stdin or any inputs that cannot be preprocessed.
863 // Check type first as not all linker inputs have a value.
864 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
865 IgnoreInput = true;
866 } else if (!strcmp(it->second->getValue(), "-")) {
867 Diag(clang::diag::note_drv_command_failed_diag_msg)
868 << "Error generating preprocessed source(s) - "
869 "ignoring input from stdin.";
870 IgnoreInput = true;
871 }
872
873 if (IgnoreInput) {
874 it = Inputs.erase(it);
875 ie = Inputs.end();
876 } else {
877 ++it;
878 }
879 }
880
881 if (Inputs.empty()) {
882 Diag(clang::diag::note_drv_command_failed_diag_msg)
883 << "Error generating preprocessed source(s) - "
884 "no preprocessable inputs.";
885 return;
886 }
887
888 // Don't attempt to generate preprocessed files if multiple -arch options are
889 // used, unless they're all duplicates.
890 llvm::StringSet<> ArchNames;
891 for (const Arg *A : C.getArgs()) {
892 if (A->getOption().matches(options::OPT_arch)) {
893 StringRef ArchName = A->getValue();
894 ArchNames.insert(ArchName);
895 }
896 }
897 if (ArchNames.size() > 1) {
898 Diag(clang::diag::note_drv_command_failed_diag_msg)
899 << "Error generating preprocessed source(s) - cannot generate "
900 "preprocessed source with multiple -arch options.";
901 return;
902 }
903
904 // Construct the list of abstract actions to perform for this compilation. On
905 // Darwin OSes this uses the driver-driver and builds universal actions.
906 const ToolChain &TC = C.getDefaultToolChain();
907 if (TC.getTriple().isOSBinFormatMachO())
908 BuildUniversalActions(C, TC, Inputs);
909 else
910 BuildActions(C, C.getArgs(), Inputs, C.getActions());
911
912 BuildJobs(C);
913
914 // If there were errors building the compilation, quit now.
915 if (Trap.hasErrorOccurred()) {
916 Diag(clang::diag::note_drv_command_failed_diag_msg)
917 << "Error generating preprocessed source(s).";
918 return;
919 }
920
921 // Generate preprocessed output.
922 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
923 C.ExecuteJobs(C.getJobs(), FailingCommands);
924
925 // If any of the preprocessing commands failed, clean up and exit.
926 if (!FailingCommands.empty()) {
927 if (!isSaveTempsEnabled())
928 C.CleanupFileList(C.getTempFiles(), true);
929
930 Diag(clang::diag::note_drv_command_failed_diag_msg)
931 << "Error generating preprocessed source(s).";
932 return;
933 }
934
935 const ArgStringList &TempFiles = C.getTempFiles();
936 if (TempFiles.empty()) {
937 Diag(clang::diag::note_drv_command_failed_diag_msg)
938 << "Error generating preprocessed source(s).";
939 return;
940 }
941
942 Diag(clang::diag::note_drv_command_failed_diag_msg)
943 << "\n********************\n\n"
944 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
945 "Preprocessed source(s) and associated run script(s) are located at:";
946
947 SmallString<128> VFS;
948 SmallString<128> ReproCrashFilename;
949 for (const char *TempFile : TempFiles) {
950 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
951 if (ReproCrashFilename.empty()) {
952 ReproCrashFilename = TempFile;
953 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
954 }
955 if (StringRef(TempFile).endswith(".cache")) {
956 // In some cases (modules) we'll dump extra data to help with reproducing
957 // the crash into a directory next to the output.
958 VFS = llvm::sys::path::filename(TempFile);
959 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
960 }
961 }
962
963 // Assume associated files are based off of the first temporary file.
964 CrashReportInfo CrashInfo(TempFiles[0], VFS);
965
966 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
967 std::error_code EC;
968 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
969 if (EC) {
970 Diag(clang::diag::note_drv_command_failed_diag_msg)
971 << "Error generating run script: " + Script + " " + EC.message();
972 } else {
973 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
974 << "# Driver args: ";
975 printArgList(ScriptOS, C.getInputArgs());
976 ScriptOS << "# Original command: ";
977 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
978 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
979 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
980 }
981
982 // On darwin, provide information about the .crash diagnostic report.
983 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
984 SmallString<128> CrashDiagDir;
985 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
986 Diag(clang::diag::note_drv_command_failed_diag_msg)
987 << ReproCrashFilename.str();
988 } else { // Suggest a directory for the user to look for .crash files.
989 llvm::sys::path::append(CrashDiagDir, Name);
990 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
991 Diag(clang::diag::note_drv_command_failed_diag_msg)
992 << "Crash backtrace is located in";
993 Diag(clang::diag::note_drv_command_failed_diag_msg)
994 << CrashDiagDir.str();
995 Diag(clang::diag::note_drv_command_failed_diag_msg)
996 << "(choose the .crash file that corresponds to your crash)";
997 }
998 }
999
1000 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1001 options::OPT_frewrite_map_file_EQ))
1002 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1003
1004 Diag(clang::diag::note_drv_command_failed_diag_msg)
1005 << "\n\n********************";
1006}
1007
1008void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1009 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1010 // if the tool does not support response files, there is a chance/ that things
1011 // will just work without a response file, so we silently just skip it.
1012 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1013 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1014 return;
1015
1016 std::string TmpName = GetTemporaryPath("response", "txt");
1017 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1018}
1019
1020int Driver::ExecuteCompilation(
1021 Compilation &C,
1022 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1023 // Just print if -### was present.
1024 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1025 C.getJobs().Print(llvm::errs(), "\n", true);
1026 return 0;
1027 }
1028
1029 // If there were errors building the compilation, quit now.
1030 if (Diags.hasErrorOccurred())
1031 return 1;
1032
1033 // Set up response file names for each command, if necessary
1034 for (auto &Job : C.getJobs())
1035 setUpResponseFiles(C, Job);
1036
1037 C.ExecuteJobs(C.getJobs(), FailingCommands);
1038
1039 // Remove temp files.
1040 C.CleanupFileList(C.getTempFiles());
1041
1042 // If the command succeeded, we are done.
1043 if (FailingCommands.empty())
1044 return 0;
1045
1046 // Otherwise, remove result files and print extra information about abnormal
1047 // failures.
1048 for (const auto &CmdPair : FailingCommands) {
1049 int Res = CmdPair.first;
1050 const Command *FailingCommand = CmdPair.second;
1051
1052 // Remove result files if we're not saving temps.
1053 if (!isSaveTempsEnabled()) {
1054 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1055 C.CleanupFileMap(C.getResultFiles(), JA, true);
1056
1057 // Failure result files are valid unless we crashed.
1058 if (Res < 0)
1059 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1060 }
1061
1062 // Print extra information about abnormal failures, if possible.
1063 //
1064 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1065 // status was 1, assume the command failed normally. In particular, if it
1066 // was the compiler then assume it gave a reasonable error code. Failures
1067 // in other tools are less common, and they generally have worse
1068 // diagnostics, so always print the diagnostic there.
1069 const Tool &FailingTool = FailingCommand->getCreator();
1070
1071 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1072 // FIXME: See FIXME above regarding result code interpretation.
1073 if (Res < 0)
1074 Diag(clang::diag::err_drv_command_signalled)
1075 << FailingTool.getShortName();
1076 else
1077 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1078 << Res;
1079 }
1080 }
1081 return 0;
1082}
1083
1084void Driver::PrintHelp(bool ShowHidden) const {
1085 unsigned IncludedFlagsBitmask;
1086 unsigned ExcludedFlagsBitmask;
1087 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1088 getIncludeExcludeOptionFlagMasks();
1089
1090 ExcludedFlagsBitmask |= options::NoDriverOption;
1091 if (!ShowHidden)
1092 ExcludedFlagsBitmask |= HelpHidden;
1093
1094 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1095 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1096}
1097
1098void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1099 // FIXME: The following handlers should use a callback mechanism, we don't
1100 // know what the client would like to do.
1101 OS << getClangFullVersion() << '\n';
1102 const ToolChain &TC = C.getDefaultToolChain();
1103 OS << "Target: " << TC.getTripleString() << '\n';
1104
1105 // Print the threading model.
1106 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1107 // Don't print if the ToolChain would have barfed on it already
1108 if (TC.isThreadModelSupported(A->getValue()))
1109 OS << "Thread model: " << A->getValue();
1110 } else
1111 OS << "Thread model: " << TC.getThreadModel();
1112 OS << '\n';
1113
1114 // Print out the install directory.
1115 OS << "InstalledDir: " << InstalledDir << '\n';
1116}
1117
1118/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1119/// option.
1120static void PrintDiagnosticCategories(raw_ostream &OS) {
1121 // Skip the empty category.
1122 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1123 ++i)
1124 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1125}
1126
1127bool Driver::HandleImmediateArgs(const Compilation &C) {
1128 // The order these options are handled in gcc is all over the place, but we
1129 // don't expect inconsistencies w.r.t. that to matter in practice.
1130
1131 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1132 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1133 return false;
1134 }
1135
1136 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1137 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1138 // return an answer which matches our definition of __VERSION__.
1139 //
1140 // If we want to return a more correct answer some day, then we should
1141 // introduce a non-pedantically GCC compatible mode to Clang in which we
1142 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1143 llvm::outs() << "4.2.1\n";
1144 return false;
1145 }
1146
1147 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1148 PrintDiagnosticCategories(llvm::outs());
1149 return false;
1150 }
1151
1152 if (C.getArgs().hasArg(options::OPT_help) ||
1153 C.getArgs().hasArg(options::OPT__help_hidden)) {
1154 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1155 return false;
1156 }
1157
1158 if (C.getArgs().hasArg(options::OPT__version)) {
1159 // Follow gcc behavior and use stdout for --version and stderr for -v.
1160 PrintVersion(C, llvm::outs());
1161 return false;
1162 }
1163
1164 if (C.getArgs().hasArg(options::OPT_v) ||
1165 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1166 PrintVersion(C, llvm::errs());
1167 SuppressMissingInputWarning = true;
1168 }
1169
1170 const ToolChain &TC = C.getDefaultToolChain();
1171
1172 if (C.getArgs().hasArg(options::OPT_v))
1173 TC.printVerboseInfo(llvm::errs());
1174
1175 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1176 llvm::outs() << ResourceDir << '\n';
1177 return false;
1178 }
1179
1180 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1181 llvm::outs() << "programs: =";
1182 bool separator = false;
1183 for (const std::string &Path : TC.getProgramPaths()) {
1184 if (separator)
1185 llvm::outs() << ':';
1186 llvm::outs() << Path;
1187 separator = true;
1188 }
1189 llvm::outs() << "\n";
1190 llvm::outs() << "libraries: =" << ResourceDir;
1191
1192 StringRef sysroot = C.getSysRoot();
1193
1194 for (const std::string &Path : TC.getFilePaths()) {
1195 // Always print a separator. ResourceDir was the first item shown.
1196 llvm::outs() << ':';
1197 // Interpretation of leading '=' is needed only for NetBSD.
1198 if (Path[0] == '=')
1199 llvm::outs() << sysroot << Path.substr(1);
1200 else
1201 llvm::outs() << Path;
1202 }
1203 llvm::outs() << "\n";
1204 return false;
1205 }
1206
1207 // FIXME: The following handlers should use a callback mechanism, we don't
1208 // know what the client would like to do.
1209 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1210 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1211 return false;
1212 }
1213
1214 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1215 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1216 return false;
1217 }
1218
1219 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1220 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1221 switch (RLT) {
1222 case ToolChain::RLT_CompilerRT:
1223 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1224 break;
1225 case ToolChain::RLT_Libgcc:
1226 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1227 break;
1228 }
1229 return false;
1230 }
1231
1232 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1233 for (const Multilib &Multilib : TC.getMultilibs())
1234 llvm::outs() << Multilib << "\n";
1235 return false;
1236 }
1237
1238 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1239 for (const Multilib &Multilib : TC.getMultilibs()) {
1240 if (Multilib.gccSuffix().empty())
1241 llvm::outs() << ".\n";
1242 else {
1243 StringRef Suffix(Multilib.gccSuffix());
1244 assert(Suffix.front() == '/')((Suffix.front() == '/') ? static_cast<void> (0) : __assert_fail
("Suffix.front() == '/'", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1244, __PRETTY_FUNCTION__))
;
1245 llvm::outs() << Suffix.substr(1) << "\n";
1246 }
1247 }
1248 return false;
1249 }
1250 return true;
1251}
1252
1253// Display an action graph human-readably. Action A is the "sink" node
1254// and latest-occuring action. Traversal is in pre-order, visiting the
1255// inputs to each action before printing the action itself.
1256static unsigned PrintActions1(const Compilation &C, Action *A,
1257 std::map<Action *, unsigned> &Ids) {
1258 if (Ids.count(A)) // A was already visited.
1259 return Ids[A];
1260
1261 std::string str;
1262 llvm::raw_string_ostream os(str);
1263
1264 os << Action::getClassName(A->getKind()) << ", ";
1265 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1266 os << "\"" << IA->getInputArg().getValue() << "\"";
1267 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1268 os << '"' << BIA->getArchName() << '"' << ", {"
1269 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1270 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1271 bool IsFirst = true;
1272 OA->doOnEachDependence(
1273 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1274 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1275 // sm_35 this will generate:
1276 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1277 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1278 if (!IsFirst)
1
Assuming 'IsFirst' is not equal to 0
2
Taking false branch
1279 os << ", ";
1280 os << '"';
1281 if (TC)
3
Assuming 'TC' is null
4
Taking false branch
1282 os << A->getOffloadingKindPrefix();
1283 else
1284 os << "host";
1285 os << " (";
1286 os << TC->getTriple().normalize();
5
Called C++ object pointer is null
1287
1288 if (BoundArch)
1289 os << ":" << BoundArch;
1290 os << ")";
1291 os << '"';
1292 os << " {" << PrintActions1(C, A, Ids) << "}";
1293 IsFirst = false;
1294 });
1295 } else {
1296 const ActionList *AL = &A->getInputs();
1297
1298 if (AL->size()) {
1299 const char *Prefix = "{";
1300 for (Action *PreRequisite : *AL) {
1301 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1302 Prefix = ", ";
1303 }
1304 os << "}";
1305 } else
1306 os << "{}";
1307 }
1308
1309 // Append offload info for all options other than the offloading action
1310 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1311 std::string offload_str;
1312 llvm::raw_string_ostream offload_os(offload_str);
1313 if (!isa<OffloadAction>(A)) {
1314 auto S = A->getOffloadingKindPrefix();
1315 if (!S.empty()) {
1316 offload_os << ", (" << S;
1317 if (A->getOffloadingArch())
1318 offload_os << ", " << A->getOffloadingArch();
1319 offload_os << ")";
1320 }
1321 }
1322
1323 unsigned Id = Ids.size();
1324 Ids[A] = Id;
1325 llvm::errs() << Id << ": " << os.str() << ", "
1326 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1327
1328 return Id;
1329}
1330
1331// Print the action graphs in a compilation C.
1332// For example "clang -c file1.c file2.c" is composed of two subgraphs.
1333void Driver::PrintActions(const Compilation &C) const {
1334 std::map<Action *, unsigned> Ids;
1335 for (Action *A : C.getActions())
1336 PrintActions1(C, A, Ids);
1337}
1338
1339/// \brief Check whether the given input tree contains any compilation or
1340/// assembly actions.
1341static bool ContainsCompileOrAssembleAction(const Action *A) {
1342 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1343 isa<AssembleJobAction>(A))
1344 return true;
1345
1346 for (const Action *Input : A->inputs())
1347 if (ContainsCompileOrAssembleAction(Input))
1348 return true;
1349
1350 return false;
1351}
1352
1353void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1354 const InputList &BAInputs) const {
1355 DerivedArgList &Args = C.getArgs();
1356 ActionList &Actions = C.getActions();
1357 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1358 // Collect the list of architectures. Duplicates are allowed, but should only
1359 // be handled once (in the order seen).
1360 llvm::StringSet<> ArchNames;
1361 SmallVector<const char *, 4> Archs;
1362 for (Arg *A : Args) {
1363 if (A->getOption().matches(options::OPT_arch)) {
1364 // Validate the option here; we don't save the type here because its
1365 // particular spelling may participate in other driver choices.
1366 llvm::Triple::ArchType Arch =
1367 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1368 if (Arch == llvm::Triple::UnknownArch) {
1369 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1370 continue;
1371 }
1372
1373 A->claim();
1374 if (ArchNames.insert(A->getValue()).second)
1375 Archs.push_back(A->getValue());
1376 }
1377 }
1378
1379 // When there is no explicit arch for this platform, make sure we still bind
1380 // the architecture (to the default) so that -Xarch_ is handled correctly.
1381 if (!Archs.size())
1382 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1383
1384 ActionList SingleActions;
1385 BuildActions(C, Args, BAInputs, SingleActions);
1386
1387 // Add in arch bindings for every top level action, as well as lipo and
1388 // dsymutil steps if needed.
1389 for (Action* Act : SingleActions) {
1390 // Make sure we can lipo this kind of output. If not (and it is an actual
1391 // output) then we disallow, since we can't create an output file with the
1392 // right name without overwriting it. We could remove this oddity by just
1393 // changing the output names to include the arch, which would also fix
1394 // -save-temps. Compatibility wins for now.
1395
1396 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1397 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1398 << types::getTypeName(Act->getType());
1399
1400 ActionList Inputs;
1401 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1402 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1403
1404 // Lipo if necessary, we do it this way because we need to set the arch flag
1405 // so that -Xarch_ gets overwritten.
1406 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1407 Actions.append(Inputs.begin(), Inputs.end());
1408 else
1409 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1410
1411 // Handle debug info queries.
1412 Arg *A = Args.getLastArg(options::OPT_g_Group);
1413 if (A && !A->getOption().matches(options::OPT_g0) &&
1414 !A->getOption().matches(options::OPT_gstabs) &&
1415 ContainsCompileOrAssembleAction(Actions.back())) {
1416
1417 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1418 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1419 // because the debug info will refer to a temporary object file which
1420 // will be removed at the end of the compilation process.
1421 if (Act->getType() == types::TY_Image) {
1422 ActionList Inputs;
1423 Inputs.push_back(Actions.back());
1424 Actions.pop_back();
1425 Actions.push_back(
1426 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1427 }
1428
1429 // Verify the debug info output.
1430 if (Args.hasArg(options::OPT_verify_debug_info)) {
1431 Action* LastAction = Actions.back();
1432 Actions.pop_back();
1433 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1434 LastAction, types::TY_Nothing));
1435 }
1436 }
1437 }
1438}
1439
1440/// \brief Check that the file referenced by Value exists. If it doesn't,
1441/// issue a diagnostic and return false.
1442static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1443 StringRef Value, types::ID Ty) {
1444 if (!D.getCheckInputsExist())
1445 return true;
1446
1447 // stdin always exists.
1448 if (Value == "-")
1449 return true;
1450
1451 SmallString<64> Path(Value);
1452 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1453 if (!llvm::sys::path::is_absolute(Path)) {
1454 SmallString<64> Directory(WorkDir->getValue());
1455 llvm::sys::path::append(Directory, Value);
1456 Path.assign(Directory);
1457 }
1458 }
1459
1460 if (llvm::sys::fs::exists(Twine(Path)))
1461 return true;
1462
1463 if (D.IsCLMode()) {
1464 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1465 llvm::sys::Process::FindInEnvPath("LIB", Value))
1466 return true;
1467
1468 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1469 // Arguments to the /link flag might cause the linker to search for object
1470 // and library files in paths we don't know about. Don't error in such
1471 // cases.
1472 return true;
1473 }
1474 }
1475
1476 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1477 return false;
1478}
1479
1480// Construct a the list of inputs and their types.
1481void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1482 InputList &Inputs) const {
1483 // Track the current user specified (-x) input. We also explicitly track the
1484 // argument used to set the type; we only want to claim the type when we
1485 // actually use it, so we warn about unused -x arguments.
1486 types::ID InputType = types::TY_Nothing;
1487 Arg *InputTypeArg = nullptr;
1488
1489 // The last /TC or /TP option sets the input type to C or C++ globally.
1490 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1491 options::OPT__SLASH_TP)) {
1492 InputTypeArg = TCTP;
1493 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1494 ? types::TY_C
1495 : types::TY_CXX;
1496
1497 Arg *Previous = nullptr;
1498 bool ShowNote = false;
1499 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1500 if (Previous) {
1501 Diag(clang::diag::warn_drv_overriding_flag_option)
1502 << Previous->getSpelling() << A->getSpelling();
1503 ShowNote = true;
1504 }
1505 Previous = A;
1506 }
1507 if (ShowNote)
1508 Diag(clang::diag::note_drv_t_option_is_global);
1509
1510 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1511 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1511, __PRETTY_FUNCTION__))
;
1512 }
1513
1514 for (Arg *A : Args) {
1515 if (A->getOption().getKind() == Option::InputClass) {
1516 const char *Value = A->getValue();
1517 types::ID Ty = types::TY_INVALID;
1518
1519 // Infer the input type if necessary.
1520 if (InputType == types::TY_Nothing) {
1521 // If there was an explicit arg for this, claim it.
1522 if (InputTypeArg)
1523 InputTypeArg->claim();
1524
1525 // stdin must be handled specially.
1526 if (memcmp(Value, "-", 2) == 0) {
1527 // If running with -E, treat as a C input (this changes the builtin
1528 // macros, for example). This may be overridden by -ObjC below.
1529 //
1530 // Otherwise emit an error but still use a valid type to avoid
1531 // spurious errors (e.g., no inputs).
1532 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1533 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1534 : clang::diag::err_drv_unknown_stdin_type);
1535 Ty = types::TY_C;
1536 } else {
1537 // Otherwise lookup by extension.
1538 // Fallback is C if invoked as C preprocessor or Object otherwise.
1539 // We use a host hook here because Darwin at least has its own
1540 // idea of what .s is.
1541 if (const char *Ext = strrchr(Value, '.'))
1542 Ty = TC.LookupTypeForExtension(Ext + 1);
1543
1544 if (Ty == types::TY_INVALID) {
1545 if (CCCIsCPP())
1546 Ty = types::TY_C;
1547 else
1548 Ty = types::TY_Object;
1549 }
1550
1551 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1552 // should autodetect some input files as C++ for g++ compatibility.
1553 if (CCCIsCXX()) {
1554 types::ID OldTy = Ty;
1555 Ty = types::lookupCXXTypeForCType(Ty);
1556
1557 if (Ty != OldTy)
1558 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1559 << getTypeName(OldTy) << getTypeName(Ty);
1560 }
1561 }
1562
1563 // -ObjC and -ObjC++ override the default language, but only for "source
1564 // files". We just treat everything that isn't a linker input as a
1565 // source file.
1566 //
1567 // FIXME: Clean this up if we move the phase sequence into the type.
1568 if (Ty != types::TY_Object) {
1569 if (Args.hasArg(options::OPT_ObjC))
1570 Ty = types::TY_ObjC;
1571 else if (Args.hasArg(options::OPT_ObjCXX))
1572 Ty = types::TY_ObjCXX;
1573 }
1574 } else {
1575 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1575, __PRETTY_FUNCTION__))
;
1576 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1577 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1578 // object files.
1579 const char *Ext = strrchr(Value, '.');
1580 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1581 Ty = types::TY_Object;
1582 }
1583 if (Ty == types::TY_INVALID) {
1584 Ty = InputType;
1585 InputTypeArg->claim();
1586 }
1587 }
1588
1589 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1590 Inputs.push_back(std::make_pair(Ty, A));
1591
1592 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1593 StringRef Value = A->getValue();
1594 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1595 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1596 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1597 }
1598 A->claim();
1599 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1600 StringRef Value = A->getValue();
1601 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1602 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1603 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1604 }
1605 A->claim();
1606 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1607 // Just treat as object type, we could make a special type for this if
1608 // necessary.
1609 Inputs.push_back(std::make_pair(types::TY_Object, A));
1610
1611 } else if (A->getOption().matches(options::OPT_x)) {
1612 InputTypeArg = A;
1613 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1614 A->claim();
1615
1616 // Follow gcc behavior and treat as linker input for invalid -x
1617 // options. Its not clear why we shouldn't just revert to unknown; but
1618 // this isn't very important, we might as well be bug compatible.
1619 if (!InputType) {
1620 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1621 InputType = types::TY_Object;
1622 }
1623 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1624 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1624, __PRETTY_FUNCTION__))
;
1625 StringRef Val = A->getValue(0);
1626 if (Val.find_first_of("/\\") != StringRef::npos) {
1627 // Warn about e.g. "/Users/me/myfile.c".
1628 Diag(diag::warn_slash_u_filename) << Val;
1629 Diag(diag::note_use_dashdash);
1630 }
1631 }
1632 }
1633 if (CCCIsCPP() && Inputs.empty()) {
1634 // If called as standalone preprocessor, stdin is processed
1635 // if no other input is present.
1636 Arg *A = MakeInputArg(Args, *Opts, "-");
1637 Inputs.push_back(std::make_pair(types::TY_C, A));
1638 }
1639}
1640
1641namespace {
1642/// Provides a convenient interface for different programming models to generate
1643/// the required device actions.
1644class OffloadingActionBuilder final {
1645 /// Flag used to trace errors in the builder.
1646 bool IsValid = false;
1647
1648 /// The compilation that is using this builder.
1649 Compilation &C;
1650
1651 /// Map between an input argument and the offload kinds used to process it.
1652 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1653
1654 /// Builder interface. It doesn't build anything or keep any state.
1655 class DeviceActionBuilder {
1656 public:
1657 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1658
1659 enum ActionBuilderReturnCode {
1660 // The builder acted successfully on the current action.
1661 ABRT_Success,
1662 // The builder didn't have to act on the current action.
1663 ABRT_Inactive,
1664 // The builder was successful and requested the host action to not be
1665 // generated.
1666 ABRT_Ignore_Host,
1667 };
1668
1669 protected:
1670 /// Compilation associated with this builder.
1671 Compilation &C;
1672
1673 /// Tool chains associated with this builder. The same programming
1674 /// model may have associated one or more tool chains.
1675 SmallVector<const ToolChain *, 2> ToolChains;
1676
1677 /// The derived arguments associated with this builder.
1678 DerivedArgList &Args;
1679
1680 /// The inputs associated with this builder.
1681 const Driver::InputList &Inputs;
1682
1683 /// The associated offload kind.
1684 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1685
1686 public:
1687 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1688 const Driver::InputList &Inputs,
1689 Action::OffloadKind AssociatedOffloadKind)
1690 : C(C), Args(Args), Inputs(Inputs),
1691 AssociatedOffloadKind(AssociatedOffloadKind) {}
1692 virtual ~DeviceActionBuilder() {}
1693
1694 /// Fill up the array \a DA with all the device dependences that should be
1695 /// added to the provided host action \a HostAction. By default it is
1696 /// inactive.
1697 virtual ActionBuilderReturnCode
1698 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1699 phases::ID CurPhase, phases::ID FinalPhase,
1700 PhasesTy &Phases) {
1701 return ABRT_Inactive;
1702 }
1703
1704 /// Update the state to include the provided host action \a HostAction as a
1705 /// dependency of the current device action. By default it is inactive.
1706 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1707 return ABRT_Inactive;
1708 }
1709
1710 /// Append top level actions generated by the builder. Return true if errors
1711 /// were found.
1712 virtual void appendTopLevelActions(ActionList &AL) {}
1713
1714 /// Append linker actions generated by the builder. Return true if errors
1715 /// were found.
1716 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1717
1718 /// Initialize the builder. Return true if any initialization errors are
1719 /// found.
1720 virtual bool initialize() { return false; }
1721
1722 /// Return true if the builder can use bundling/unbundling.
1723 virtual bool canUseBundlerUnbundler() const { return false; }
1724
1725 /// Return true if this builder is valid. We have a valid builder if we have
1726 /// associated device tool chains.
1727 bool isValid() { return !ToolChains.empty(); }
1728
1729 /// Return the associated offload kind.
1730 Action::OffloadKind getAssociatedOffloadKind() {
1731 return AssociatedOffloadKind;
1732 }
1733 };
1734
1735 /// \brief CUDA action builder. It injects device code in the host backend
1736 /// action.
1737 class CudaActionBuilder final : public DeviceActionBuilder {
1738 /// Flags to signal if the user requested host-only or device-only
1739 /// compilation.
1740 bool CompileHostOnly = false;
1741 bool CompileDeviceOnly = false;
1742
1743 /// List of GPU architectures to use in this compilation.
1744 SmallVector<CudaArch, 4> GpuArchList;
1745
1746 /// The CUDA actions for the current input.
1747 ActionList CudaDeviceActions;
1748
1749 /// The CUDA fat binary if it was generated for the current input.
1750 Action *CudaFatBinary = nullptr;
1751
1752 /// Flag that is set to true if this builder acted on the current input.
1753 bool IsActive = false;
1754
1755 public:
1756 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1757 const Driver::InputList &Inputs)
1758 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1759
1760 ActionBuilderReturnCode
1761 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1762 phases::ID CurPhase, phases::ID FinalPhase,
1763 PhasesTy &Phases) override {
1764 if (!IsActive)
1765 return ABRT_Inactive;
1766
1767 // If we don't have more CUDA actions, we don't have any dependences to
1768 // create for the host.
1769 if (CudaDeviceActions.empty())
1770 return ABRT_Success;
1771
1772 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1773, __PRETTY_FUNCTION__))
1773 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1773, __PRETTY_FUNCTION__))
;
1774 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1775, __PRETTY_FUNCTION__))
1775 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1775, __PRETTY_FUNCTION__))
;
1776
1777 // If we are generating code for the device or we are in a backend phase,
1778 // we attempt to generate the fat binary. We compile each arch to ptx and
1779 // assemble to cubin, then feed the cubin *and* the ptx into a device
1780 // "link" action, which uses fatbinary to combine these cubins into one
1781 // fatbin. The fatbin is then an input to the host action if not in
1782 // device-only mode.
1783 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1784 ActionList DeviceActions;
1785 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1786 // Produce the device action from the current phase up to the assemble
1787 // phase.
1788 for (auto Ph : Phases) {
1789 // Skip the phases that were already dealt with.
1790 if (Ph < CurPhase)
1791 continue;
1792 // We have to be consistent with the host final phase.
1793 if (Ph > FinalPhase)
1794 break;
1795
1796 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1797 C, Args, Ph, CudaDeviceActions[I]);
1798
1799 if (Ph == phases::Assemble)
1800 break;
1801 }
1802
1803 // If we didn't reach the assemble phase, we can't generate the fat
1804 // binary. We don't need to generate the fat binary if we are not in
1805 // device-only mode.
1806 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1807 CompileDeviceOnly)
1808 continue;
1809
1810 Action *AssembleAction = CudaDeviceActions[I];
1811 assert(AssembleAction->getType() == types::TY_Object)((AssembleAction->getType() == types::TY_Object) ? static_cast
<void> (0) : __assert_fail ("AssembleAction->getType() == types::TY_Object"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1811, __PRETTY_FUNCTION__))
;
1812 assert(AssembleAction->getInputs().size() == 1)((AssembleAction->getInputs().size() == 1) ? static_cast<
void> (0) : __assert_fail ("AssembleAction->getInputs().size() == 1"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1812, __PRETTY_FUNCTION__))
;
1813
1814 Action *BackendAction = AssembleAction->getInputs()[0];
1815 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"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1815, __PRETTY_FUNCTION__))
;
1816
1817 for (auto &A : {AssembleAction, BackendAction}) {
1818 OffloadAction::DeviceDependences DDep;
1819 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1820 Action::OFK_Cuda);
1821 DeviceActions.push_back(
1822 C.MakeAction<OffloadAction>(DDep, A->getType()));
1823 }
1824 }
1825
1826 // We generate the fat binary if we have device input actions.
1827 if (!DeviceActions.empty()) {
1828 CudaFatBinary =
1829 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1830
1831 if (!CompileDeviceOnly) {
1832 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1833 Action::OFK_Cuda);
1834 // Clear the fat binary, it is already a dependence to an host
1835 // action.
1836 CudaFatBinary = nullptr;
1837 }
1838
1839 // Remove the CUDA actions as they are already connected to an host
1840 // action or fat binary.
1841 CudaDeviceActions.clear();
1842 }
1843
1844 // We avoid creating host action in device-only mode.
1845 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1846 } else if (CurPhase > phases::Backend) {
1847 // If we are past the backend phase and still have a device action, we
1848 // don't have to do anything as this action is already a device
1849 // top-level action.
1850 return ABRT_Success;
1851 }
1852
1853 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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1855, __PRETTY_FUNCTION__))
1854 "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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1855, __PRETTY_FUNCTION__))
1855 "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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1855, __PRETTY_FUNCTION__))
;
1856
1857 // By default, we produce an action for each device arch.
1858 for (Action *&A : CudaDeviceActions)
1859 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1860
1861 return ABRT_Success;
1862 }
1863
1864 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1865 // While generating code for CUDA, we only depend on the host input action
1866 // to trigger the creation of all the CUDA device actions.
1867
1868 // If we are dealing with an input action, replicate it for each GPU
1869 // architecture. If we are in host-only mode we return 'success' so that
1870 // the host uses the CUDA offload kind.
1871 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1872 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1873, __PRETTY_FUNCTION__))
1873 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1873, __PRETTY_FUNCTION__))
;
1874
1875 // If the host input is not CUDA, we don't need to bother about this
1876 // input.
1877 if (IA->getType() != types::TY_CUDA) {
1878 // The builder will ignore this input.
1879 IsActive = false;
1880 return ABRT_Inactive;
1881 }
1882
1883 // Set the flag to true, so that the builder acts on the current input.
1884 IsActive = true;
1885
1886 if (CompileHostOnly)
1887 return ABRT_Success;
1888
1889 // Replicate inputs for each GPU architecture.
1890 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1891 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1892 IA->getInputArg(), types::TY_CUDA_DEVICE));
1893
1894 return ABRT_Success;
1895 }
1896
1897 return IsActive ? ABRT_Success : ABRT_Inactive;
1898 }
1899
1900 void appendTopLevelActions(ActionList &AL) override {
1901 // Utility to append actions to the top level list.
1902 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1903 OffloadAction::DeviceDependences Dep;
1904 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1905 Action::OFK_Cuda);
1906 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1907 };
1908
1909 // If we have a fat binary, add it to the list.
1910 if (CudaFatBinary) {
1911 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1912 CudaDeviceActions.clear();
1913 CudaFatBinary = nullptr;
1914 return;
1915 }
1916
1917 if (CudaDeviceActions.empty())
1918 return;
1919
1920 // If we have CUDA actions at this point, that's because we have a have
1921 // partial compilation, so we should have an action for each GPU
1922 // architecture.
1923 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1924, __PRETTY_FUNCTION__))
1924 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1924, __PRETTY_FUNCTION__))
;
1925 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1926, __PRETTY_FUNCTION__))
1926 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1926, __PRETTY_FUNCTION__))
;
1927 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1928 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1929
1930 CudaDeviceActions.clear();
1931 }
1932
1933 bool initialize() override {
1934 // We don't need to support CUDA.
1935 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1936 return false;
1937
1938 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1939 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1939, __PRETTY_FUNCTION__))
;
1940 if (HostTC->getTriple().isNVPTX()) {
1941 // We do not support targeting NVPTX for host compilation. Throw
1942 // an error and abort pipeline construction early so we don't trip
1943 // asserts that assume device-side compilation.
1944 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1945 return true;
1946 }
1947
1948 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1949
1950 Arg *PartialCompilationArg = Args.getLastArg(
1951 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1952 options::OPT_cuda_compile_host_device);
1953 CompileHostOnly = PartialCompilationArg &&
1954 PartialCompilationArg->getOption().matches(
1955 options::OPT_cuda_host_only);
1956 CompileDeviceOnly = PartialCompilationArg &&
1957 PartialCompilationArg->getOption().matches(
1958 options::OPT_cuda_device_only);
1959
1960 // Collect all cuda_gpu_arch parameters, removing duplicates.
1961 std::set<CudaArch> GpuArchs;
1962 bool Error = false;
1963 for (Arg *A : Args) {
1964 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1965 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
1966 continue;
1967 A->claim();
1968
1969 const StringRef ArchStr = A->getValue();
1970 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1971 ArchStr == "all") {
1972 GpuArchs.clear();
1973 continue;
1974 }
1975 CudaArch Arch = StringToCudaArch(ArchStr);
1976 if (Arch == CudaArch::UNKNOWN) {
1977 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1978 Error = true;
1979 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1980 GpuArchs.insert(Arch);
1981 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1982 GpuArchs.erase(Arch);
1983 else
1984 llvm_unreachable("Unexpected option.")::llvm::llvm_unreachable_internal("Unexpected option.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 1984)
;
1985 }
1986
1987 // Collect list of GPUs remaining in the set.
1988 for (CudaArch Arch : GpuArchs)
1989 GpuArchList.push_back(Arch);
1990
1991 // Default to sm_20 which is the lowest common denominator for
1992 // supported GPUs. sm_20 code should work correctly, if
1993 // suboptimally, on all newer GPUs.
1994 if (GpuArchList.empty())
1995 GpuArchList.push_back(CudaArch::SM_20);
1996
1997 return Error;
1998 }
1999 };
2000
2001 /// OpenMP action builder. The host bitcode is passed to the device frontend
2002 /// and all the device linked images are passed to the host link phase.
2003 class OpenMPActionBuilder final : public DeviceActionBuilder {
2004 /// The OpenMP actions for the current input.
2005 ActionList OpenMPDeviceActions;
2006
2007 /// The linker inputs obtained for each toolchain.
2008 SmallVector<ActionList, 8> DeviceLinkerInputs;
2009
2010 public:
2011 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2012 const Driver::InputList &Inputs)
2013 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2014
2015 ActionBuilderReturnCode
2016 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2017 phases::ID CurPhase, phases::ID FinalPhase,
2018 PhasesTy &Phases) override {
2019
2020 // We should always have an action for each input.
2021 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2022, __PRETTY_FUNCTION__))
2022 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2022, __PRETTY_FUNCTION__))
;
2023
2024 // The host only depends on device action in the linking phase, when all
2025 // the device images have to be embedded in the host image.
2026 if (CurPhase == phases::Link) {
2027 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2028, __PRETTY_FUNCTION__))
2028 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2028, __PRETTY_FUNCTION__))
;
2029 auto LI = DeviceLinkerInputs.begin();
2030 for (auto *A : OpenMPDeviceActions) {
2031 LI->push_back(A);
2032 ++LI;
2033 }
2034
2035 // We passed the device action as a host dependence, so we don't need to
2036 // do anything else with them.
2037 OpenMPDeviceActions.clear();
2038 return ABRT_Success;
2039 }
2040
2041 // By default, we produce an action for each device arch.
2042 for (Action *&A : OpenMPDeviceActions)
2043 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2044
2045 return ABRT_Success;
2046 }
2047
2048 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2049
2050 // If this is an input action replicate it for each OpenMP toolchain.
2051 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2052 OpenMPDeviceActions.clear();
2053 for (unsigned I = 0; I < ToolChains.size(); ++I)
2054 OpenMPDeviceActions.push_back(
2055 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2056 return ABRT_Success;
2057 }
2058
2059 // If this is an unbundling action use it as is for each OpenMP toolchain.
2060 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2061 OpenMPDeviceActions.clear();
2062 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2063 OpenMPDeviceActions.push_back(UA);
2064 UA->registerDependentActionInfo(
2065 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2066 }
2067 return ABRT_Success;
2068 }
2069
2070 // When generating code for OpenMP we use the host compile phase result as
2071 // a dependence to the device compile phase so that it can learn what
2072 // declarations should be emitted. However, this is not the only use for
2073 // the host action, so we prevent it from being collapsed.
2074 if (isa<CompileJobAction>(HostAction)) {
2075 HostAction->setCannotBeCollapsedWithNextDependentAction();
2076 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2077, __PRETTY_FUNCTION__))
2077 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2077, __PRETTY_FUNCTION__))
;
2078 OffloadAction::HostDependence HDep(
2079 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2080 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2081 auto TC = ToolChains.begin();
2082 for (Action *&A : OpenMPDeviceActions) {
2083 assert(isa<CompileJobAction>(A))((isa<CompileJobAction>(A)) ? static_cast<void> (
0) : __assert_fail ("isa<CompileJobAction>(A)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2083, __PRETTY_FUNCTION__))
;
2084 OffloadAction::DeviceDependences DDep;
2085 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2086 A = C.MakeAction<OffloadAction>(HDep, DDep);
2087 ++TC;
2088 }
2089 }
2090 return ABRT_Success;
2091 }
2092
2093 void appendTopLevelActions(ActionList &AL) override {
2094 if (OpenMPDeviceActions.empty())
2095 return;
2096
2097 // We should always have an action for each input.
2098 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2099, __PRETTY_FUNCTION__))
2099 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2099, __PRETTY_FUNCTION__))
;
2100
2101 // Append all device actions followed by the proper offload action.
2102 auto TI = ToolChains.begin();
2103 for (auto *A : OpenMPDeviceActions) {
2104 OffloadAction::DeviceDependences Dep;
2105 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2106 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2107 ++TI;
2108 }
2109 // We no longer need the action stored in this builder.
2110 OpenMPDeviceActions.clear();
2111 }
2112
2113 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2114 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2115, __PRETTY_FUNCTION__))
2115 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2115, __PRETTY_FUNCTION__))
;
2116
2117 // Append a new link action for each device.
2118 auto TC = ToolChains.begin();
2119 for (auto &LI : DeviceLinkerInputs) {
2120 auto *DeviceLinkAction =
2121 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2122 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2123 Action::OFK_OpenMP);
2124 ++TC;
2125 }
2126 }
2127
2128 bool initialize() override {
2129 // Get the OpenMP toolchains. If we don't get any, the action builder will
2130 // know there is nothing to do related to OpenMP offloading.
2131 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2132 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2133 ++TI)
2134 ToolChains.push_back(TI->second);
2135
2136 DeviceLinkerInputs.resize(ToolChains.size());
2137 return false;
2138 }
2139
2140 bool canUseBundlerUnbundler() const override {
2141 // OpenMP should use bundled files whenever possible.
2142 return true;
2143 }
2144 };
2145
2146 ///
2147 /// TODO: Add the implementation for other specialized builders here.
2148 ///
2149
2150 /// Specialized builders being used by this offloading action builder.
2151 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2152
2153 /// Flag set to true if all valid builders allow file bundling/unbundling.
2154 bool CanUseBundler;
2155
2156public:
2157 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2158 const Driver::InputList &Inputs)
2159 : C(C) {
2160 // Create a specialized builder for each device toolchain.
2161
2162 IsValid = true;
2163
2164 // Create a specialized builder for CUDA.
2165 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2166
2167 // Create a specialized builder for OpenMP.
2168 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2169
2170 //
2171 // TODO: Build other specialized builders here.
2172 //
2173
2174 // Initialize all the builders, keeping track of errors. If all valid
2175 // builders agree that we can use bundling, set the flag to true.
2176 unsigned ValidBuilders = 0u;
2177 unsigned ValidBuildersSupportingBundling = 0u;
2178 for (auto *SB : SpecializedBuilders) {
2179 IsValid = IsValid && !SB->initialize();
2180
2181 // Update the counters if the builder is valid.
2182 if (SB->isValid()) {
2183 ++ValidBuilders;
2184 if (SB->canUseBundlerUnbundler())
2185 ++ValidBuildersSupportingBundling;
2186 }
2187 }
2188 CanUseBundler =
2189 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2190 }
2191
2192 ~OffloadingActionBuilder() {
2193 for (auto *SB : SpecializedBuilders)
2194 delete SB;
2195 }
2196
2197 /// Generate an action that adds device dependences (if any) to a host action.
2198 /// If no device dependence actions exist, just return the host action \a
2199 /// HostAction. If an error is found or if no builder requires the host action
2200 /// to be generated, return nullptr.
2201 Action *
2202 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2203 phases::ID CurPhase, phases::ID FinalPhase,
2204 DeviceActionBuilder::PhasesTy &Phases) {
2205 if (!IsValid)
2206 return nullptr;
2207
2208 if (SpecializedBuilders.empty())
2209 return HostAction;
2210
2211 assert(HostAction && "Invalid host action!")((HostAction && "Invalid host action!") ? static_cast
<void> (0) : __assert_fail ("HostAction && \"Invalid host action!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2211, __PRETTY_FUNCTION__))
;
2212
2213 OffloadAction::DeviceDependences DDeps;
2214 // Check if all the programming models agree we should not emit the host
2215 // action. Also, keep track of the offloading kinds employed.
2216 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2217 unsigned InactiveBuilders = 0u;
2218 unsigned IgnoringBuilders = 0u;
2219 for (auto *SB : SpecializedBuilders) {
2220 if (!SB->isValid()) {
2221 ++InactiveBuilders;
2222 continue;
2223 }
2224
2225 auto RetCode =
2226 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2227
2228 // If the builder explicitly says the host action should be ignored,
2229 // we need to increment the variable that tracks the builders that request
2230 // the host object to be ignored.
2231 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2232 ++IgnoringBuilders;
2233
2234 // Unless the builder was inactive for this action, we have to record the
2235 // offload kind because the host will have to use it.
2236 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2237 OffloadKind |= SB->getAssociatedOffloadKind();
2238 }
2239
2240 // If all builders agree that the host object should be ignored, just return
2241 // nullptr.
2242 if (IgnoringBuilders &&
2243 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2244 return nullptr;
2245
2246 if (DDeps.getActions().empty())
2247 return HostAction;
2248
2249 // We have dependences we need to bundle together. We use an offload action
2250 // for that.
2251 OffloadAction::HostDependence HDep(
2252 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2253 /*BoundArch=*/nullptr, DDeps);
2254 return C.MakeAction<OffloadAction>(HDep, DDeps);
2255 }
2256
2257 /// Generate an action that adds a host dependence to a device action. The
2258 /// results will be kept in this action builder. Return true if an error was
2259 /// found.
2260 bool addHostDependenceToDeviceActions(Action *&HostAction,
2261 const Arg *InputArg) {
2262 if (!IsValid)
2263 return true;
2264
2265 // If we are supporting bundling/unbundling and the current action is an
2266 // input action of non-source file, we replace the host action by the
2267 // unbundling action. The bundler tool has the logic to detect if an input
2268 // is a bundle or not and if the input is not a bundle it assumes it is a
2269 // host file. Therefore it is safe to create an unbundling action even if
2270 // the input is not a bundle.
2271 if (CanUseBundler && isa<InputAction>(HostAction) &&
2272 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2273 !types::isSrcFile(HostAction->getType())) {
2274 auto UnbundlingHostAction =
2275 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2276 UnbundlingHostAction->registerDependentActionInfo(
2277 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2278 /*BoundArch=*/StringRef(), Action::OFK_Host);
2279 HostAction = UnbundlingHostAction;
2280 }
2281
2282 assert(HostAction && "Invalid host action!")((HostAction && "Invalid host action!") ? static_cast
<void> (0) : __assert_fail ("HostAction && \"Invalid host action!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2282, __PRETTY_FUNCTION__))
;
2283
2284 // Register the offload kinds that are used.
2285 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2286 for (auto *SB : SpecializedBuilders) {
2287 if (!SB->isValid())
2288 continue;
2289
2290 auto RetCode = SB->addDeviceDepences(HostAction);
2291
2292 // Host dependences for device actions are not compatible with that same
2293 // action being ignored.
2294 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.!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2295, __PRETTY_FUNCTION__))
2295 "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.!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2295, __PRETTY_FUNCTION__))
;
2296
2297 // Unless the builder was inactive for this action, we have to record the
2298 // offload kind because the host will have to use it.
2299 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2300 OffloadKind |= SB->getAssociatedOffloadKind();
2301 }
2302
2303 return false;
2304 }
2305
2306 /// Add the offloading top level actions to the provided action list. This
2307 /// function can replace the host action by a bundling action if the
2308 /// programming models allow it.
2309 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2310 const Arg *InputArg) {
2311 // Get the device actions to be appended.
2312 ActionList OffloadAL;
2313 for (auto *SB : SpecializedBuilders) {
2314 if (!SB->isValid())
2315 continue;
2316 SB->appendTopLevelActions(OffloadAL);
2317 }
2318
2319 // If we can use the bundler, replace the host action by the bundling one in
2320 // the resulting list. Otherwise, just append the device actions.
2321 if (CanUseBundler && !OffloadAL.empty()) {
2322 // Add the host action to the list in order to create the bundling action.
2323 OffloadAL.push_back(HostAction);
2324
2325 // We expect that the host action was just appended to the action list
2326 // before this method was called.
2327 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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2327, __PRETTY_FUNCTION__))
;
2328 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2329 AL.back() = HostAction;
2330 } else
2331 AL.append(OffloadAL.begin(), OffloadAL.end());
2332
2333 // Propagate to the current host action (if any) the offload information
2334 // associated with the current input.
2335 if (HostAction)
2336 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2337 /*BoundArch=*/nullptr);
2338 return false;
2339 }
2340
2341 /// Processes the host linker action. This currently consists of replacing it
2342 /// with an offload action if there are device link objects and propagate to
2343 /// the host action all the offload kinds used in the current compilation. The
2344 /// resulting action is returned.
2345 Action *processHostLinkAction(Action *HostAction) {
2346 // Add all the dependences from the device linking actions.
2347 OffloadAction::DeviceDependences DDeps;
2348 for (auto *SB : SpecializedBuilders) {
2349 if (!SB->isValid())
2350 continue;
2351
2352 SB->appendLinkDependences(DDeps);
2353 }
2354
2355 // Calculate all the offload kinds used in the current compilation.
2356 unsigned ActiveOffloadKinds = 0u;
2357 for (auto &I : InputArgToOffloadKindMap)
2358 ActiveOffloadKinds |= I.second;
2359
2360 // If we don't have device dependencies, we don't have to create an offload
2361 // action.
2362 if (DDeps.getActions().empty()) {
2363 // Propagate all the active kinds to host action. Given that it is a link
2364 // action it is assumed to depend on all actions generated so far.
2365 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2366 /*BoundArch=*/nullptr);
2367 return HostAction;
2368 }
2369
2370 // Create the offload action with all dependences. When an offload action
2371 // is created the kinds are propagated to the host action, so we don't have
2372 // to do that explicitly here.
2373 OffloadAction::HostDependence HDep(
2374 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2375 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2376 return C.MakeAction<OffloadAction>(HDep, DDeps);
2377 }
2378};
2379} // anonymous namespace.
2380
2381void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2382 const InputList &Inputs, ActionList &Actions) const {
2383 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2384
2385 if (!SuppressMissingInputWarning && Inputs.empty()) {
2386 Diag(clang::diag::err_drv_no_input_files);
2387 return;
2388 }
2389
2390 Arg *FinalPhaseArg;
2391 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2392
2393 if (FinalPhase == phases::Link) {
2394 if (Args.hasArg(options::OPT_emit_llvm))
2395 Diag(clang::diag::err_drv_emit_llvm_link);
2396 if (IsCLMode() && LTOMode != LTOK_None &&
2397 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2398 Diag(clang::diag::err_drv_lto_without_lld);
2399 }
2400
2401 // Reject -Z* at the top level, these options should never have been exposed
2402 // by gcc.
2403 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2404 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2405
2406 // Diagnose misuse of /Fo.
2407 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2408 StringRef V = A->getValue();
2409 if (Inputs.size() > 1 && !V.empty() &&
2410 !llvm::sys::path::is_separator(V.back())) {
2411 // Check whether /Fo tries to name an output file for multiple inputs.
2412 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2413 << A->getSpelling() << V;
2414 Args.eraseArg(options::OPT__SLASH_Fo);
2415 }
2416 }
2417
2418 // Diagnose misuse of /Fa.
2419 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2420 StringRef V = A->getValue();
2421 if (Inputs.size() > 1 && !V.empty() &&
2422 !llvm::sys::path::is_separator(V.back())) {
2423 // Check whether /Fa tries to name an asm file for multiple inputs.
2424 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2425 << A->getSpelling() << V;
2426 Args.eraseArg(options::OPT__SLASH_Fa);
2427 }
2428 }
2429
2430 // Diagnose misuse of /o.
2431 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2432 if (A->getValue()[0] == '\0') {
2433 // It has to have a value.
2434 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2435 Args.eraseArg(options::OPT__SLASH_o);
2436 }
2437 }
2438
2439 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2440 // * no filename after it
2441 // * both /Yc and /Yu passed but with different filenames
2442 // * corresponding file not also passed as /FI
2443 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2444 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2445 if (YcArg && YcArg->getValue()[0] == '\0') {
2446 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2447 Args.eraseArg(options::OPT__SLASH_Yc);
2448 YcArg = nullptr;
2449 }
2450 if (YuArg && YuArg->getValue()[0] == '\0') {
2451 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2452 Args.eraseArg(options::OPT__SLASH_Yu);
2453 YuArg = nullptr;
2454 }
2455 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2456 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2457 Args.eraseArg(options::OPT__SLASH_Yc);
2458 Args.eraseArg(options::OPT__SLASH_Yu);
2459 YcArg = YuArg = nullptr;
2460 }
2461 if (YcArg || YuArg) {
2462 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2463 bool FoundMatchingInclude = false;
2464 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2465 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2466 if (Inc->getValue() == Val)
2467 FoundMatchingInclude = true;
2468 }
2469 if (!FoundMatchingInclude) {
2470 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2471 << (YcArg ? YcArg : YuArg)->getSpelling();
2472 Args.eraseArg(options::OPT__SLASH_Yc);
2473 Args.eraseArg(options::OPT__SLASH_Yu);
2474 YcArg = YuArg = nullptr;
2475 }
2476 }
2477 if (YcArg && Inputs.size() > 1) {
2478 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2479 Args.eraseArg(options::OPT__SLASH_Yc);
2480 YcArg = nullptr;
2481 }
2482 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2483 // /Y- disables all pch handling. Rather than check for it everywhere,
2484 // just remove clang-cl pch-related flags here.
2485 Args.eraseArg(options::OPT__SLASH_Fp);
2486 Args.eraseArg(options::OPT__SLASH_Yc);
2487 Args.eraseArg(options::OPT__SLASH_Yu);
2488 YcArg = YuArg = nullptr;
2489 }
2490
2491 // Builder to be used to build offloading actions.
2492 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2493
2494 // Construct the actions to perform.
2495 ActionList LinkerInputs;
2496
2497 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2498 for (auto &I : Inputs) {
2499 types::ID InputType = I.first;
2500 const Arg *InputArg = I.second;
2501
2502 PL.clear();
2503 types::getCompilationPhases(InputType, PL);
2504
2505 // If the first step comes after the final phase we are doing as part of
2506 // this compilation, warn the user about it.
2507 phases::ID InitialPhase = PL[0];
2508 if (InitialPhase > FinalPhase) {
2509 // Claim here to avoid the more general unused warning.
2510 InputArg->claim();
2511
2512 // Suppress all unused style warnings with -Qunused-arguments
2513 if (Args.hasArg(options::OPT_Qunused_arguments))
2514 continue;
2515
2516 // Special case when final phase determined by binary name, rather than
2517 // by a command-line argument with a corresponding Arg.
2518 if (CCCIsCPP())
2519 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2520 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2521 // Special case '-E' warning on a previously preprocessed file to make
2522 // more sense.
2523 else if (InitialPhase == phases::Compile &&
2524 FinalPhase == phases::Preprocess &&
2525 getPreprocessedType(InputType) == types::TY_INVALID)
2526 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2527 << InputArg->getAsString(Args) << !!FinalPhaseArg
2528 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2529 else
2530 Diag(clang::diag::warn_drv_input_file_unused)
2531 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2532 << !!FinalPhaseArg
2533 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2534 continue;
2535 }
2536
2537 if (YcArg) {
2538 // Add a separate precompile phase for the compile phase.
2539 if (FinalPhase >= phases::Compile) {
2540 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2541 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2542 types::getCompilationPhases(HeaderType, PCHPL);
2543 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2544
2545 // Build the pipeline for the pch file.
2546 Action *ClangClPch =
2547 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2548 for (phases::ID Phase : PCHPL)
2549 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2550 assert(ClangClPch)((ClangClPch) ? static_cast<void> (0) : __assert_fail (
"ClangClPch", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2550, __PRETTY_FUNCTION__))
;
2551 Actions.push_back(ClangClPch);
2552 // The driver currently exits after the first failed command. This
2553 // relies on that behavior, to make sure if the pch generation fails,
2554 // the main compilation won't run.
2555 }
2556 }
2557
2558 // Build the pipeline for this file.
2559 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2560
2561 // Use the current host action in any of the offloading actions, if
2562 // required.
2563 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2564 break;
2565
2566 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2567 i != e; ++i) {
2568 phases::ID Phase = *i;
2569
2570 // We are done if this step is past what the user requested.
2571 if (Phase > FinalPhase)
2572 break;
2573
2574 // Add any offload action the host action depends on.
2575 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2576 Current, InputArg, Phase, FinalPhase, PL);
2577 if (!Current)
2578 break;
2579
2580 // Queue linker inputs.
2581 if (Phase == phases::Link) {
2582 assert((i + 1) == e && "linking must be final compilation step.")(((i + 1) == e && "linking must be final compilation step."
) ? static_cast<void> (0) : __assert_fail ("(i + 1) == e && \"linking must be final compilation step.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2582, __PRETTY_FUNCTION__))
;
2583 LinkerInputs.push_back(Current);
2584 Current = nullptr;
2585 break;
2586 }
2587
2588 // Otherwise construct the appropriate action.
2589 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2590
2591 // We didn't create a new action, so we will just move to the next phase.
2592 if (NewCurrent == Current)
2593 continue;
2594
2595 Current = NewCurrent;
2596
2597 // Use the current host action in any of the offloading actions, if
2598 // required.
2599 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2600 break;
2601
2602 if (Current->getType() == types::TY_Nothing)
2603 break;
2604 }
2605
2606 // If we ended with something, add to the output list.
2607 if (Current)
2608 Actions.push_back(Current);
2609
2610 // Add any top level actions generated for offloading.
2611 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2612 }
2613
2614 // Add a link action if necessary.
2615 if (!LinkerInputs.empty()) {
2616 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2617 LA = OffloadBuilder.processHostLinkAction(LA);
2618 Actions.push_back(LA);
2619 }
2620
2621 // If we are linking, claim any options which are obviously only used for
2622 // compilation.
2623 if (FinalPhase == phases::Link && PL.size() == 1) {
2624 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2625 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2626 }
2627
2628 // Claim ignored clang-cl options.
2629 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2630
2631 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2632 // to non-CUDA compilations and should not trigger warnings there.
2633 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2634 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2635}
2636
2637Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2638 phases::ID Phase, Action *Input) const {
2639 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2640
2641 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2642 // encode this in the steps because the intermediate type depends on
2643 // arguments. Just special case here.
2644 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2645 return Input;
2646
2647 // Build the appropriate action.
2648 switch (Phase) {
2649 case phases::Link:
2650 llvm_unreachable("link action invalid here.")::llvm::llvm_unreachable_internal("link action invalid here."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2650)
;
2651 case phases::Preprocess: {
2652 types::ID OutputTy;
2653 // -{M, MM} alter the output type.
2654 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2655 OutputTy = types::TY_Dependencies;
2656 } else {
2657 OutputTy = Input->getType();
2658 if (!Args.hasFlag(options::OPT_frewrite_includes,
2659 options::OPT_fno_rewrite_includes, false) &&
2660 !CCGenDiagnostics)
2661 OutputTy = types::getPreprocessedType(OutputTy);
2662 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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2663, __PRETTY_FUNCTION__))
2663 "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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2663, __PRETTY_FUNCTION__))
;
2664 }
2665 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2666 }
2667 case phases::Precompile: {
2668 types::ID OutputTy = getPrecompiledType(Input->getType());
2669 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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2670, __PRETTY_FUNCTION__))
2670 "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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2670, __PRETTY_FUNCTION__))
;
2671 if (Args.hasArg(options::OPT_fsyntax_only)) {
2672 // Syntax checks should not emit a PCH file
2673 OutputTy = types::TY_Nothing;
2674 }
2675 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2676 }
2677 case phases::Compile: {
2678 if (Args.hasArg(options::OPT_fsyntax_only))
2679 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2680 if (Args.hasArg(options::OPT_rewrite_objc))
2681 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2682 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2683 return C.MakeAction<CompileJobAction>(Input,
2684 types::TY_RewrittenLegacyObjC);
2685 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2686 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2687 if (Args.hasArg(options::OPT__migrate))
2688 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2689 if (Args.hasArg(options::OPT_emit_ast))
2690 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2691 if (Args.hasArg(options::OPT_module_file_info))
2692 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2693 if (Args.hasArg(options::OPT_verify_pch))
2694 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2695 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2696 }
2697 case phases::Backend: {
2698 if (isUsingLTO()) {
2699 types::ID Output =
2700 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2701 return C.MakeAction<BackendJobAction>(Input, Output);
2702 }
2703 if (Args.hasArg(options::OPT_emit_llvm)) {
2704 types::ID Output =
2705 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2706 return C.MakeAction<BackendJobAction>(Input, Output);
2707 }
2708 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2709 }
2710 case phases::Assemble:
2711 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2712 }
2713
2714 llvm_unreachable("invalid phase in ConstructPhaseAction")::llvm::llvm_unreachable_internal("invalid phase in ConstructPhaseAction"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2714)
;
2715}
2716
2717void Driver::BuildJobs(Compilation &C) const {
2718 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2719
2720 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2721
2722 // It is an error to provide a -o option if we are making multiple output
2723 // files.
2724 if (FinalOutput) {
2725 unsigned NumOutputs = 0;
2726 for (const Action *A : C.getActions())
2727 if (A->getType() != types::TY_Nothing)
2728 ++NumOutputs;
2729
2730 if (NumOutputs > 1) {
2731 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2732 FinalOutput = nullptr;
2733 }
2734 }
2735
2736 // Collect the list of architectures.
2737 llvm::StringSet<> ArchNames;
2738 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2739 for (const Arg *A : C.getArgs())
2740 if (A->getOption().matches(options::OPT_arch))
2741 ArchNames.insert(A->getValue());
2742
2743 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2744 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2745 for (Action *A : C.getActions()) {
2746 // If we are linking an image for multiple archs then the linker wants
2747 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2748 // doesn't fit in cleanly because we have to pass this information down.
2749 //
2750 // FIXME: This is a hack; find a cleaner way to integrate this into the
2751 // process.
2752 const char *LinkingOutput = nullptr;
2753 if (isa<LipoJobAction>(A)) {
2754 if (FinalOutput)
2755 LinkingOutput = FinalOutput->getValue();
2756 else
2757 LinkingOutput = getDefaultImageName();
2758 }
2759
2760 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2761 /*BoundArch*/ StringRef(),
2762 /*AtTopLevel*/ true,
2763 /*MultipleArchs*/ ArchNames.size() > 1,
2764 /*LinkingOutput*/ LinkingOutput, CachedResults,
2765 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2766 }
2767
2768 // If the user passed -Qunused-arguments or there were errors, don't warn
2769 // about any unused arguments.
2770 if (Diags.hasErrorOccurred() ||
2771 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2772 return;
2773
2774 // Claim -### here.
2775 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2776
2777 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2778 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2779 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2780
2781 for (Arg *A : C.getArgs()) {
2782 // FIXME: It would be nice to be able to send the argument to the
2783 // DiagnosticsEngine, so that extra values, position, and so on could be
2784 // printed.
2785 if (!A->isClaimed()) {
2786 if (A->getOption().hasFlag(options::NoArgumentUnused))
2787 continue;
2788
2789 // Suppress the warning automatically if this is just a flag, and it is an
2790 // instance of an argument we already claimed.
2791 const Option &Opt = A->getOption();
2792 if (Opt.getKind() == Option::FlagClass) {
2793 bool DuplicateClaimed = false;
2794
2795 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2796 if (AA->isClaimed()) {
2797 DuplicateClaimed = true;
2798 break;
2799 }
2800 }
2801
2802 if (DuplicateClaimed)
2803 continue;
2804 }
2805
2806 // In clang-cl, don't mention unknown arguments here since they have
2807 // already been warned about.
2808 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2809 Diag(clang::diag::warn_drv_unused_argument)
2810 << A->getAsString(C.getArgs());
2811 }
2812 }
2813}
2814
2815namespace {
2816/// Utility class to control the collapse of dependent actions and select the
2817/// tools accordingly.
2818class ToolSelector final {
2819 /// The tool chain this selector refers to.
2820 const ToolChain &TC;
2821
2822 /// The compilation this selector refers to.
2823 const Compilation &C;
2824
2825 /// The base action this selector refers to.
2826 const JobAction *BaseAction;
2827
2828 /// Set to true if the current toolchain refers to host actions.
2829 bool IsHostSelector;
2830
2831 /// Set to true if save-temps and embed-bitcode functionalities are active.
2832 bool SaveTemps;
2833 bool EmbedBitcode;
2834
2835 /// Get previous dependent action or null if that does not exist. If
2836 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2837 /// null will be returned.
2838 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2839 ActionList &SavedOffloadAction,
2840 bool CanBeCollapsed = true) {
2841 // An option can be collapsed only if it has a single input.
2842 if (Inputs.size() != 1)
2843 return nullptr;
2844
2845 Action *CurAction = *Inputs.begin();
2846 if (CanBeCollapsed &&
2847 !CurAction->isCollapsingWithNextDependentActionLegal())
2848 return nullptr;
2849
2850 // If the input action is an offload action. Look through it and save any
2851 // offload action that can be dropped in the event of a collapse.
2852 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2853 // If the dependent action is a device action, we will attempt to collapse
2854 // only with other device actions. Otherwise, we would do the same but
2855 // with host actions only.
2856 if (!IsHostSelector) {
2857 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2858 CurAction =
2859 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2860 if (CanBeCollapsed &&
2861 !CurAction->isCollapsingWithNextDependentActionLegal())
2862 return nullptr;
2863 SavedOffloadAction.push_back(OA);
2864 return dyn_cast<JobAction>(CurAction);
2865 }
2866 } else if (OA->hasHostDependence()) {
2867 CurAction = OA->getHostDependence();
2868 if (CanBeCollapsed &&
2869 !CurAction->isCollapsingWithNextDependentActionLegal())
2870 return nullptr;
2871 SavedOffloadAction.push_back(OA);
2872 return dyn_cast<JobAction>(CurAction);
2873 }
2874 return nullptr;
2875 }
2876
2877 return dyn_cast<JobAction>(CurAction);
2878 }
2879
2880 /// Return true if an assemble action can be collapsed.
2881 bool canCollapseAssembleAction() const {
2882 return TC.useIntegratedAs() && !SaveTemps &&
2883 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2884 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2885 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2886 }
2887
2888 /// Return true if a preprocessor action can be collapsed.
2889 bool canCollapsePreprocessorAction() const {
2890 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2891 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2892 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2893 }
2894
2895 /// Struct that relates an action with the offload actions that would be
2896 /// collapsed with it.
2897 struct JobActionInfo final {
2898 /// The action this info refers to.
2899 const JobAction *JA = nullptr;
2900 /// The offload actions we need to take care off if this action is
2901 /// collapsed.
2902 ActionList SavedOffloadAction;
2903 };
2904
2905 /// Append collapsed offload actions from the give nnumber of elements in the
2906 /// action info array.
2907 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2908 ArrayRef<JobActionInfo> &ActionInfo,
2909 unsigned ElementNum) {
2910 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2910, __PRETTY_FUNCTION__))
;
2911 for (unsigned I = 0; I < ElementNum; ++I)
2912 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2913 ActionInfo[I].SavedOffloadAction.end());
2914 }
2915
2916 /// Functions that attempt to perform the combining. They detect if that is
2917 /// legal, and if so they update the inputs \a Inputs and the offload action
2918 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2919 /// the combined action is returned. If the combining is not legal or if the
2920 /// tool does not exist, null is returned.
2921 /// Currently three kinds of collapsing are supported:
2922 /// - Assemble + Backend + Compile;
2923 /// - Assemble + Backend ;
2924 /// - Backend + Compile.
2925 const Tool *
2926 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2927 const ActionList *&Inputs,
2928 ActionList &CollapsedOffloadAction) {
2929 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2930 return nullptr;
2931 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2932 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2933 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2934 if (!AJ || !BJ || !CJ)
2935 return nullptr;
2936
2937 // Get compiler tool.
2938 const Tool *T = TC.SelectTool(*CJ);
2939 if (!T)
2940 return nullptr;
2941
2942 // When using -fembed-bitcode, it is required to have the same tool (clang)
2943 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2944 if (EmbedBitcode) {
2945 const Tool *BT = TC.SelectTool(*BJ);
2946 if (BT == T)
2947 return nullptr;
2948 }
2949
2950 if (!T->hasIntegratedAssembler())
2951 return nullptr;
2952
2953 Inputs = &CJ->getInputs();
2954 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2955 /*NumElements=*/3);
2956 return T;
2957 }
2958 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2959 const ActionList *&Inputs,
2960 ActionList &CollapsedOffloadAction) {
2961 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2962 return nullptr;
2963 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2964 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2965 if (!AJ || !BJ)
2966 return nullptr;
2967
2968 // Retrieve the compile job, backend action must always be preceded by one.
2969 ActionList CompileJobOffloadActions;
2970 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2971 /*CanBeCollapsed=*/false);
2972 if (!AJ || !BJ || !CJ)
2973 return nullptr;
2974
2975 assert(isa<CompileJobAction>(CJ) &&((isa<CompileJobAction>(CJ) && "Expecting compile job preceding backend job."
) ? static_cast<void> (0) : __assert_fail ("isa<CompileJobAction>(CJ) && \"Expecting compile job preceding backend job.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2976, __PRETTY_FUNCTION__))
2976 "Expecting compile job preceding backend job.")((isa<CompileJobAction>(CJ) && "Expecting compile job preceding backend job."
) ? static_cast<void> (0) : __assert_fail ("isa<CompileJobAction>(CJ) && \"Expecting compile job preceding backend job.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 2976, __PRETTY_FUNCTION__))
;
2977
2978 // Get compiler tool.
2979 const Tool *T = TC.SelectTool(*CJ);
2980 if (!T)
2981 return nullptr;
2982
2983 if (!T->hasIntegratedAssembler())
2984 return nullptr;
2985
2986 Inputs = &BJ->getInputs();
2987 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2988 /*NumElements=*/2);
2989 return T;
2990 }
2991 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2992 const ActionList *&Inputs,
2993 ActionList &CollapsedOffloadAction) {
2994 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
2995 return nullptr;
2996 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
2997 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
2998 if (!BJ || !CJ)
2999 return nullptr;
3000
3001 // Get compiler tool.
3002 const Tool *T = TC.SelectTool(*CJ);
3003 if (!T)
3004 return nullptr;
3005
3006 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3007 return nullptr;
3008
3009 Inputs = &CJ->getInputs();
3010 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3011 /*NumElements=*/2);
3012 return T;
3013 }
3014
3015 /// Updates the inputs if the obtained tool supports combining with
3016 /// preprocessor action, and the current input is indeed a preprocessor
3017 /// action. If combining results in the collapse of offloading actions, those
3018 /// are appended to \a CollapsedOffloadAction.
3019 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3020 ActionList &CollapsedOffloadAction) {
3021 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3022 return;
3023
3024 // Attempt to get a preprocessor action dependence.
3025 ActionList PreprocessJobOffloadActions;
3026 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3027 if (!PJ || !isa<PreprocessJobAction>(PJ))
3028 return;
3029
3030 // This is legal to combine. Append any offload action we found and set the
3031 // current inputs to preprocessor inputs.
3032 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3033 PreprocessJobOffloadActions.end());
3034 Inputs = &PJ->getInputs();
3035 }
3036
3037public:
3038 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3039 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3040 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3041 EmbedBitcode(EmbedBitcode) {
3042 assert(BaseAction && "Invalid base action.")((BaseAction && "Invalid base action.") ? static_cast
<void> (0) : __assert_fail ("BaseAction && \"Invalid base action.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3042, __PRETTY_FUNCTION__))
;
3043 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3044 }
3045
3046 /// Check if a chain of actions can be combined and return the tool that can
3047 /// handle the combination of actions. The pointer to the current inputs \a
3048 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3049 /// connected to collapsed actions are updated accordingly. The latter enables
3050 /// the caller of the selector to process them afterwards instead of just
3051 /// dropping them. If no suitable tool is found, null will be returned.
3052 const Tool *getTool(const ActionList *&Inputs,
3053 ActionList &CollapsedOffloadAction) {
3054 //
3055 // Get the largest chain of actions that we could combine.
3056 //
3057
3058 SmallVector<JobActionInfo, 5> ActionChain(1);
3059 ActionChain.back().JA = BaseAction;
3060 while (ActionChain.back().JA) {
3061 const Action *CurAction = ActionChain.back().JA;
3062
3063 // Grow the chain by one element.
3064 ActionChain.resize(ActionChain.size() + 1);
3065 JobActionInfo &AI = ActionChain.back();
3066
3067 // Attempt to fill it with the
3068 AI.JA =
3069 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3070 }
3071
3072 // Pop the last action info as it could not be filled.
3073 ActionChain.pop_back();
3074
3075 //
3076 // Attempt to combine actions. If all combining attempts failed, just return
3077 // the tool of the provided action. At the end we attempt to combine the
3078 // action with any preprocessor action it may depend on.
3079 //
3080
3081 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3082 CollapsedOffloadAction);
3083 if (!T)
3084 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3085 if (!T)
3086 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3087 if (!T) {
3088 Inputs = &BaseAction->getInputs();
3089 T = TC.SelectTool(*BaseAction);
3090 }
3091
3092 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3093 return T;
3094 }
3095};
3096}
3097
3098/// Return a string that uniquely identifies the result of a job. The bound arch
3099/// is not necessarily represented in the toolchain's triple -- for example,
3100/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3101/// Also, we need to add the offloading device kind, as the same tool chain can
3102/// be used for host and device for some programming models, e.g. OpenMP.
3103static std::string GetTriplePlusArchString(const ToolChain *TC,
3104 StringRef BoundArch,
3105 Action::OffloadKind OffloadKind) {
3106 std::string TriplePlusArch = TC->getTriple().normalize();
3107 if (!BoundArch.empty()) {
3108 TriplePlusArch += "-";
3109 TriplePlusArch += BoundArch;
3110 }
3111 TriplePlusArch += "-";
3112 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3113 return TriplePlusArch;
3114}
3115
3116InputInfo Driver::BuildJobsForAction(
3117 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3118 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3119 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3120 Action::OffloadKind TargetDeviceOffloadKind) const {
3121 std::pair<const Action *, std::string> ActionTC = {
3122 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3123 auto CachedResult = CachedResults.find(ActionTC);
3124 if (CachedResult != CachedResults.end()) {
3125 return CachedResult->second;
3126 }
3127 InputInfo Result = BuildJobsForActionNoCache(
3128 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3129 CachedResults, TargetDeviceOffloadKind);
3130 CachedResults[ActionTC] = Result;
3131 return Result;
3132}
3133
3134InputInfo Driver::BuildJobsForActionNoCache(
3135 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3136 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3137 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3138 Action::OffloadKind TargetDeviceOffloadKind) const {
3139 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3140
3141 InputInfoList OffloadDependencesInputInfo;
3142 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3143 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3144 // The offload action is expected to be used in four different situations.
3145 //
3146 // a) Set a toolchain/architecture/kind for a host action:
3147 // Host Action 1 -> OffloadAction -> Host Action 2
3148 //
3149 // b) Set a toolchain/architecture/kind for a device action;
3150 // Device Action 1 -> OffloadAction -> Device Action 2
3151 //
3152 // c) Specify a device dependence to a host action;
3153 // Device Action 1 _
3154 // \
3155 // Host Action 1 ---> OffloadAction -> Host Action 2
3156 //
3157 // d) Specify a host dependence to a device action.
3158 // Host Action 1 _
3159 // \
3160 // Device Action 1 ---> OffloadAction -> Device Action 2
3161 //
3162 // For a) and b), we just return the job generated for the dependence. For
3163 // c) and d) we override the current action with the host/device dependence
3164 // if the current toolchain is host/device and set the offload dependences
3165 // info with the jobs obtained from the device/host dependence(s).
3166
3167 // If there is a single device option, just generate the job for it.
3168 if (OA->hasSingleDeviceDependence()) {
3169 InputInfo DevA;
3170 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3171 const char *DepBoundArch) {
3172 DevA =
3173 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3174 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3175 CachedResults, DepA->getOffloadingDeviceKind());
3176 });
3177 return DevA;
3178 }
3179
3180 // If 'Action 2' is host, we generate jobs for the device dependences and
3181 // override the current action with the host dependence. Otherwise, we
3182 // generate the host dependences and override the action with the device
3183 // dependence. The dependences can't therefore be a top-level action.
3184 OA->doOnEachDependence(
3185 /*IsHostDependence=*/BuildingForOffloadDevice,
3186 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3187 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3188 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3189 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3190 DepA->getOffloadingDeviceKind()));
3191 });
3192
3193 A = BuildingForOffloadDevice
3194 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3195 : OA->getHostDependence();
3196 }
3197
3198 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3199 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3200 // just using Args was better?
3201 const Arg &Input = IA->getInputArg();
3202 Input.claim();
3203 if (Input.getOption().matches(options::OPT_INPUT)) {
3204 const char *Name = Input.getValue();
3205 return InputInfo(A, Name, /* BaseInput = */ Name);
3206 }
3207 return InputInfo(A, &Input, /* BaseInput = */ "");
3208 }
3209
3210 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3211 const ToolChain *TC;
3212 StringRef ArchName = BAA->getArchName();
3213
3214 if (!ArchName.empty())
3215 TC = &getToolChain(C.getArgs(),
3216 computeTargetTriple(*this, DefaultTargetTriple,
3217 C.getArgs(), ArchName));
3218 else
3219 TC = &C.getDefaultToolChain();
3220
3221 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3222 MultipleArchs, LinkingOutput, CachedResults,
3223 TargetDeviceOffloadKind);
3224 }
3225
3226
3227 const ActionList *Inputs = &A->getInputs();
3228
3229 const JobAction *JA = cast<JobAction>(A);
3230 ActionList CollapsedOffloadActions;
3231
3232 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3233 embedBitcodeInObject() && !isUsingLTO());
3234 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3235
3236 if (!T)
3237 return InputInfo();
3238
3239 // If we've collapsed action list that contained OffloadAction we
3240 // need to build jobs for host/device-side inputs it may have held.
3241 for (const auto *OA : CollapsedOffloadActions)
3242 cast<OffloadAction>(OA)->doOnEachDependence(
3243 /*IsHostDependence=*/BuildingForOffloadDevice,
3244 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3245 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3246 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3247 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3248 DepA->getOffloadingDeviceKind()));
3249 });
3250
3251 // Only use pipes when there is exactly one input.
3252 InputInfoList InputInfos;
3253 for (const Action *Input : *Inputs) {
3254 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3255 // shouldn't get temporary output names.
3256 // FIXME: Clean this up.
3257 bool SubJobAtTopLevel =
3258 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3259 InputInfos.push_back(BuildJobsForAction(
3260 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3261 CachedResults, A->getOffloadingDeviceKind()));
3262 }
3263
3264 // Always use the first input as the base input.
3265 const char *BaseInput = InputInfos[0].getBaseInput();
3266
3267 // ... except dsymutil actions, which use their actual input as the base
3268 // input.
3269 if (JA->getType() == types::TY_dSYM)
3270 BaseInput = InputInfos[0].getFilename();
3271
3272 // Append outputs of offload device jobs to the input list
3273 if (!OffloadDependencesInputInfo.empty())
3274 InputInfos.append(OffloadDependencesInputInfo.begin(),
3275 OffloadDependencesInputInfo.end());
3276
3277 // Set the effective triple of the toolchain for the duration of this job.
3278 llvm::Triple EffectiveTriple;
3279 const ToolChain &ToolTC = T->getToolChain();
3280 const ArgList &Args =
3281 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3282 if (InputInfos.size() != 1) {
3283 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3284 } else {
3285 // Pass along the input type if it can be unambiguously determined.
3286 EffectiveTriple = llvm::Triple(
3287 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3288 }
3289 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3290
3291 // Determine the place to write output to, if any.
3292 InputInfo Result;
3293 InputInfoList UnbundlingResults;
3294 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3295 // If we have an unbundling job, we need to create results for all the
3296 // outputs. We also update the results cache so that other actions using
3297 // this unbundling action can get the right results.
3298 for (auto &UI : UA->getDependentActionsInfo()) {
3299 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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3300, __PRETTY_FUNCTION__))
3300 "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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3300, __PRETTY_FUNCTION__))
;
3301
3302 // Unbundling actions are never at the top level. When we generate the
3303 // offloading prefix, we also do that for the host file because the
3304 // unbundling action does not change the type of the output which can
3305 // cause a overwrite.
3306 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3307 UI.DependentOffloadKind,
3308 UI.DependentToolChain->getTriple().normalize(),
3309 /*CreatePrefixForHost=*/true);
3310 auto CurI = InputInfo(
3311 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3312 /*AtTopLevel=*/false, MultipleArchs,
3313 OffloadingPrefix),
3314 BaseInput);
3315 // Save the unbundling result.
3316 UnbundlingResults.push_back(CurI);
3317
3318 // Get the unique string identifier for this dependence and cache the
3319 // result.
3320 CachedResults[{A, GetTriplePlusArchString(
3321 UI.DependentToolChain, UI.DependentBoundArch,
3322 UI.DependentOffloadKind)}] = CurI;
3323 }
3324
3325 // Now that we have all the results generated, select the one that should be
3326 // returned for the current depending action.
3327 std::pair<const Action *, std::string> ActionTC = {
3328 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3329 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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3330, __PRETTY_FUNCTION__))
3330 "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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3330, __PRETTY_FUNCTION__))
;
3331 Result = CachedResults[ActionTC];
3332 } else if (JA->getType() == types::TY_Nothing)
3333 Result = InputInfo(A, BaseInput);
3334 else {
3335 // We only have to generate a prefix for the host if this is not a top-level
3336 // action.
3337 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3338 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3339 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3340 !AtTopLevel);
3341 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3342 AtTopLevel, MultipleArchs,
3343 OffloadingPrefix),
3344 BaseInput);
3345 }
3346
3347 if (CCCPrintBindings && !CCGenDiagnostics) {
3348 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3349 << " - \"" << T->getName() << "\", inputs: [";
3350 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3351 llvm::errs() << InputInfos[i].getAsString();
3352 if (i + 1 != e)
3353 llvm::errs() << ", ";
3354 }
3355 if (UnbundlingResults.empty())
3356 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3357 else {
3358 llvm::errs() << "], outputs: [";
3359 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3360 llvm::errs() << UnbundlingResults[i].getAsString();
3361 if (i + 1 != e)
3362 llvm::errs() << ", ";
3363 }
3364 llvm::errs() << "] \n";
3365 }
3366 } else {
3367 if (UnbundlingResults.empty())
3368 T->ConstructJob(
3369 C, *JA, Result, InputInfos,
3370 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3371 LinkingOutput);
3372 else
3373 T->ConstructJobMultipleOutputs(
3374 C, *JA, UnbundlingResults, InputInfos,
3375 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3376 LinkingOutput);
3377 }
3378 return Result;
3379}
3380
3381const char *Driver::getDefaultImageName() const {
3382 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3383 return Target.isOSWindows() ? "a.exe" : "a.out";
3384}
3385
3386/// \brief Create output filename based on ArgValue, which could either be a
3387/// full filename, filename without extension, or a directory. If ArgValue
3388/// does not provide a filename, then use BaseName, and use the extension
3389/// suitable for FileType.
3390static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3391 StringRef BaseName,
3392 types::ID FileType) {
3393 SmallString<128> Filename = ArgValue;
3394
3395 if (ArgValue.empty()) {
3396 // If the argument is empty, output to BaseName in the current dir.
3397 Filename = BaseName;
3398 } else if (llvm::sys::path::is_separator(Filename.back())) {
3399 // If the argument is a directory, output to BaseName in that dir.
3400 llvm::sys::path::append(Filename, BaseName);
3401 }
3402
3403 if (!llvm::sys::path::has_extension(ArgValue)) {
3404 // If the argument didn't provide an extension, then set it.
3405 const char *Extension = types::getTypeTempSuffix(FileType, true);
3406
3407 if (FileType == types::TY_Image &&
3408 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3409 // The output file is a dll.
3410 Extension = "dll";
3411 }
3412
3413 llvm::sys::path::replace_extension(Filename, Extension);
3414 }
3415
3416 return Args.MakeArgString(Filename.c_str());
3417}
3418
3419const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3420 const char *BaseInput,
3421 StringRef BoundArch, bool AtTopLevel,
3422 bool MultipleArchs,
3423 StringRef OffloadingPrefix) const {
3424 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3425 // Output to a user requested destination?
3426 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3427 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3428 return C.addResultFile(FinalOutput->getValue(), &JA);
3429 }
3430
3431 // For /P, preprocess to file named after BaseInput.
3432 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3433 assert(AtTopLevel && isa<PreprocessJobAction>(JA))((AtTopLevel && isa<PreprocessJobAction>(JA)) ?
static_cast<void> (0) : __assert_fail ("AtTopLevel && isa<PreprocessJobAction>(JA)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3433, __PRETTY_FUNCTION__))
;
3434 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3435 StringRef NameArg;
3436 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3437 NameArg = A->getValue();
3438 return C.addResultFile(
3439 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3440 &JA);
3441 }
3442
3443 // Default to writing to stdout?
3444 if (AtTopLevel && !CCGenDiagnostics &&
3445 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3446 return "-";
3447
3448 // Is this the assembly listing for /FA?
3449 if (JA.getType() == types::TY_PP_Asm &&
3450 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3451 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3452 // Use /Fa and the input filename to determine the asm file name.
3453 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3454 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3455 return C.addResultFile(
3456 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3457 &JA);
3458 }
3459
3460 // Output to a temporary file?
3461 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3462 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3463 CCGenDiagnostics) {
3464 StringRef Name = llvm::sys::path::filename(BaseInput);
3465 std::pair<StringRef, StringRef> Split = Name.split('.');
3466 std::string TmpName = GetTemporaryPath(
3467 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3468 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3469 }
3470
3471 SmallString<128> BasePath(BaseInput);
3472 StringRef BaseName;
3473
3474 // Dsymutil actions should use the full path.
3475 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3476 BaseName = BasePath;
3477 else
3478 BaseName = llvm::sys::path::filename(BasePath);
3479
3480 // Determine what the derived output name should be.
3481 const char *NamedOutput;
3482
3483 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3484 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3485 // The /Fo or /o flag decides the object filename.
3486 StringRef Val =
3487 C.getArgs()
3488 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3489 ->getValue();
3490 NamedOutput =
3491 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3492 } else if (JA.getType() == types::TY_Image &&
3493 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3494 options::OPT__SLASH_o)) {
3495 // The /Fe or /o flag names the linked file.
3496 StringRef Val =
3497 C.getArgs()
3498 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3499 ->getValue();
3500 NamedOutput =
3501 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3502 } else if (JA.getType() == types::TY_Image) {
3503 if (IsCLMode()) {
3504 // clang-cl uses BaseName for the executable name.
3505 NamedOutput =
3506 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3507 } else {
3508 SmallString<128> Output(getDefaultImageName());
3509 Output += OffloadingPrefix;
3510 if (MultipleArchs && !BoundArch.empty()) {
3511 Output += "-";
3512 Output.append(BoundArch);
3513 }
3514 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3515 }
3516 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3517 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3518 } else {
3519 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3520 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301756/tools/clang/lib/Driver/Driver.cpp"
, 3520, __PRETTY_FUNCTION__))
;
3521
3522 std::string::size_type End = std::string::npos;
3523 if (!types::appendSuffixForType(JA.getType()))
3524 End = BaseName.rfind('.');
3525 SmallString<128> Suffixed(BaseName.substr(0, End));
3526 Suffixed += OffloadingPrefix;
3527 if (MultipleArchs && !BoundArch.empty()) {
3528 Suffixed += "-";
3529 Suffixed.append(BoundArch);
3530 }
3531 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3532 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3533 // optimized bitcode output.
3534 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3535 JA.getType() == types::TY_LLVM_BC)
3536 Suffixed += ".tmp";
3537 Suffixed += '.';
3538 Suffixed += Suffix;
3539 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3540 }
3541
3542 // Prepend object file path if -save-temps=obj
3543 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3544 JA.getType() != types::TY_PCH) {
3545 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3546 SmallString<128> TempPath(FinalOutput->getValue());
3547 llvm::sys::path::remove_filename(TempPath);
3548 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3549 llvm::sys::path::append(TempPath, OutputFileName);
3550 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3551 }
3552
3553 // If we're saving temps and the temp file conflicts with the input file,
3554 // then avoid overwriting input file.
3555 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3556 bool SameFile = false;
3557 SmallString<256> Result;
3558 llvm::sys::fs::current_path(Result);
3559 llvm::sys::path::append(Result, BaseName);
3560 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3561 // Must share the same path to conflict.
3562 if (SameFile) {
3563 StringRef Name = llvm::sys::path::filename(BaseInput);
3564 std::pair<StringRef, StringRef> Split = Name.split('.');
3565 std::string TmpName = GetTemporaryPath(
3566 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3567 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3568 }
3569 }
3570
3571 // As an annoying special case, PCH generation doesn't strip the pathname.
3572 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3573 llvm::sys::path::remove_filename(BasePath);
3574 if (BasePath.empty())
3575 BasePath = NamedOutput;
3576 else
3577 llvm::sys::path::append(BasePath, NamedOutput);
3578 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3579 } else {
3580 return C.addResultFile(NamedOutput, &JA);
3581 }
3582}
3583
3584std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3585 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3586 // attempting to use this prefix when looking for file paths.
3587 for (const std::string &Dir : PrefixDirs) {
3588 if (Dir.empty())
3589 continue;
3590 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3591 llvm::sys::path::append(P, Name);
3592 if (llvm::sys::fs::exists(Twine(P)))
3593 return P.str();
3594 }
3595
3596 SmallString<128> P(ResourceDir);
3597 llvm::sys::path::append(P, Name);
3598 if (llvm::sys::fs::exists(Twine(P)))
3599 return P.str();
3600
3601 for (const std::string &Dir : TC.getFilePaths()) {
3602 if (Dir.empty())
3603 continue;
3604 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3605 llvm::sys::path::append(P, Name);
3606 if (llvm::sys::fs::exists(Twine(P)))
3607 return P.str();
3608 }
3609
3610 return Name;
3611}
3612
3613void Driver::generatePrefixedToolNames(
3614 StringRef Tool, const ToolChain &TC,
3615 SmallVectorImpl<std::string> &Names) const {
3616 // FIXME: Needs a better variable than DefaultTargetTriple
3617 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3618 Names.emplace_back(Tool);
3619
3620 // Allow the discovery of tools prefixed with LLVM's default target triple.
3621 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3622 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3623 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3624}
3625
3626static bool ScanDirForExecutable(SmallString<128> &Dir,
3627 ArrayRef<std::string> Names) {
3628 for (const auto &Name : Names) {
3629 llvm::sys::path::append(Dir, Name);
3630 if (llvm::sys::fs::can_execute(Twine(Dir)))
3631 return true;
3632 llvm::sys::path::remove_filename(Dir);
3633 }
3634 return false;
3635}
3636
3637std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3638 SmallVector<std::string, 2> TargetSpecificExecutables;
3639 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3640
3641 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3642 // attempting to use this prefix when looking for program paths.
3643 for (const auto &PrefixDir : PrefixDirs) {
3644 if (llvm::sys::fs::is_directory(PrefixDir)) {
3645 SmallString<128> P(PrefixDir);
3646 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3647 return P.str();
3648 } else {
3649 SmallString<128> P((PrefixDir + Name).str());
3650 if (llvm::sys::fs::can_execute(Twine(P)))
3651 return P.str();
3652 }
3653 }
3654
3655 const ToolChain::path_list &List = TC.getProgramPaths();
3656 for (const auto &Path : List) {
3657 SmallString<128> P(Path);
3658 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3659 return P.str();
3660 }
3661
3662 // If all else failed, search the path.
3663 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3664 if (llvm::ErrorOr<std::string> P =
3665 llvm::sys::findProgramByName(TargetSpecificExecutable))
3666 return *P;
3667
3668 return Name;
3669}
3670
3671std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3672 SmallString<128> Path;
3673 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3674 if (EC) {
3675 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3676 return "";
3677 }
3678
3679 return Path.str();
3680}
3681
3682std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3683 SmallString<128> Output;
3684 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3685 // FIXME: If anybody needs it, implement this obscure rule:
3686 // "If you specify a directory without a file name, the default file name
3687 // is VCx0.pch., where x is the major version of Visual C++ in use."
3688 Output = FpArg->getValue();
3689
3690 // "If you do not specify an extension as part of the path name, an
3691 // extension of .pch is assumed. "
3692 if (!llvm::sys::path::has_extension(Output))
3693 Output += ".pch";
3694 } else {
3695 Output = BaseName;
3696 llvm::sys::path::replace_extension(Output, ".pch");
3697 }
3698 return Output.str();
3699}
3700
3701const ToolChain &Driver::getToolChain(const ArgList &Args,
3702 const llvm::Triple &Target) const {
3703
3704 auto &TC = ToolChains[Target.str()];
3705 if (!TC) {
3706 switch (Target.getOS()) {
3707 case llvm::Triple::Haiku:
3708 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3709 break;
3710 case llvm::Triple::CloudABI:
3711 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3712 break;
3713 case llvm::Triple::Darwin:
3714 case llvm::Triple::MacOSX:
3715 case llvm::Triple::IOS:
3716 case llvm::Triple::TvOS:
3717 case llvm::Triple::WatchOS:
3718 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3719 break;
3720 case llvm::Triple::DragonFly:
3721 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3722 break;
3723 case llvm::Triple::OpenBSD:
3724 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3725 break;
3726 case llvm::Triple::Bitrig:
3727 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3728 break;
3729 case llvm::Triple::NetBSD:
3730 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3731 break;
3732 case llvm::Triple::FreeBSD:
3733 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3734 break;
3735 case llvm::Triple::Minix:
3736 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3737 break;
3738 case llvm::Triple::Linux:
3739 case llvm::Triple::ELFIAMCU:
3740 if (Target.getArch() == llvm::Triple::hexagon)
3741 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3742 Args);
3743 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3744 !Target.hasEnvironment())
3745 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3746 Args);
3747 else
3748 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3749 break;
3750 case llvm::Triple::NaCl:
3751 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3752 break;
3753 case llvm::Triple::Fuchsia:
3754 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3755 break;
3756 case llvm::Triple::Solaris:
3757 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3758 break;
3759 case llvm::Triple::AMDHSA:
3760 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3761 break;
3762 case llvm::Triple::Win32:
3763 switch (Target.getEnvironment()) {
3764 default:
3765 if (Target.isOSBinFormatELF())
3766 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3767 else if (Target.isOSBinFormatMachO())
3768 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3769 else
3770 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3771 break;
3772 case llvm::Triple::GNU:
3773 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3774 break;
3775 case llvm::Triple::Itanium:
3776 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3777 Args);
3778 break;
3779 case llvm::Triple::MSVC:
3780 case llvm::Triple::UnknownEnvironment:
3781 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3782 break;
3783 }
3784 break;
3785 case llvm::Triple::PS4:
3786 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3787 break;
3788 case llvm::Triple::Contiki:
3789 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3790 break;
3791 default:
3792 // Of these targets, Hexagon is the only one that might have
3793 // an OS of Linux, in which case it got handled above already.
3794 switch (Target.getArch()) {
3795 case llvm::Triple::tce:
3796 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3797 break;
3798 case llvm::Triple::tcele:
3799 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3800 break;
3801 case llvm::Triple::hexagon:
3802 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3803 Args);
3804 break;
3805 case llvm::Triple::lanai:
3806 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3807 break;
3808 case llvm::Triple::xcore:
3809 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3810 break;
3811 case llvm::Triple::wasm32:
3812 case llvm::Triple::wasm64:
3813 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3814 break;
3815 case llvm::Triple::avr:
3816 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3817 break;
3818 default:
3819 if (Target.getVendor() == llvm::Triple::Myriad)
3820 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3821 Args);
3822 else if (Target.isOSBinFormatELF())
3823 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3824 else if (Target.isOSBinFormatMachO())
3825 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3826 else
3827 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3828 }
3829 }
3830 }
3831
3832 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3833 // compiles always need two toolchains, the CUDA toolchain and the host
3834 // toolchain. So the only valid way to create a CUDA toolchain is via
3835 // CreateOffloadingDeviceToolChains.
3836
3837 return *TC;
3838}
3839
3840bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3841 // Say "no" if there is not exactly one input of a type clang understands.
3842 if (JA.size() != 1 ||
3843 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3844 return false;
3845
3846 // And say "no" if this is not a kind of action clang understands.
3847 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3848 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3849 return false;
3850
3851 return true;
3852}
3853
3854/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3855/// grouped values as integers. Numbers which are not provided are set to 0.
3856///
3857/// \return True if the entire string was parsed (9.2), or all groups were
3858/// parsed (10.3.5extrastuff).
3859bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3860 unsigned &Micro, bool &HadExtra) {
3861 HadExtra = false;
3862
3863 Major = Minor = Micro = 0;
3864 if (Str.empty())
3865 return false;
3866
3867 if (Str.consumeInteger(10, Major))
3868 return false;
3869 if (Str.empty())
3870 return true;
3871 if (Str[0] != '.')
3872 return false;
3873
3874 Str = Str.drop_front(1);
3875
3876 if (Str.consumeInteger(10, Minor))
3877 return false;
3878 if (Str.empty())
3879 return true;
3880 if (Str[0] != '.')
3881 return false;
3882 Str = Str.drop_front(1);
3883
3884 if (Str.consumeInteger(10, Micro))
3885 return false;
3886 if (!Str.empty())
3887 HadExtra = true;
3888 return true;
3889}
3890
3891/// Parse digits from a string \p Str and fulfill \p Digits with
3892/// the parsed numbers. This method assumes that the max number of
3893/// digits to look for is equal to Digits.size().
3894///
3895/// \return True if the entire string was parsed and there are
3896/// no extra characters remaining at the end.
3897bool Driver::GetReleaseVersion(StringRef Str,
3898 MutableArrayRef<unsigned> Digits) {
3899 if (Str.empty())
3900 return false;
3901
3902 unsigned CurDigit = 0;
3903 while (CurDigit < Digits.size()) {
3904 unsigned Digit;
3905 if (Str.consumeInteger(10, Digit))
3906 return false;
3907 Digits[CurDigit] = Digit;
3908 if (Str.empty())
3909 return true;
3910 if (Str[0] != '.')
3911 return false;
3912 Str = Str.drop_front(1);
3913 CurDigit++;
3914 }
3915
3916 // More digits than requested, bail out...
3917 return false;
3918}
3919
3920std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3921 unsigned IncludedFlagsBitmask = 0;
3922 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
3923
3924 if (Mode == CLMode) {
3925 // Include CL and Core options.
3926 IncludedFlagsBitmask |= options::CLOption;
3927 IncludedFlagsBitmask |= options::CoreOption;
3928 } else {
3929 ExcludedFlagsBitmask |= options::CLOption;
3930 }
3931
3932 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3933}
3934
3935bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
3936 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3937}