Coverage Report

Created: 2019-07-24 05:18

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