Coverage Report

Created: 2018-07-19 20:53

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/tools/driver/driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This is the entry point to the clang driver; it is a thin wrapper
11
// for functionality in the Driver clang library.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "clang/Driver/Driver.h"
16
#include "clang/Basic/DiagnosticOptions.h"
17
#include "clang/Driver/Compilation.h"
18
#include "clang/Driver/DriverDiagnostic.h"
19
#include "clang/Driver/Options.h"
20
#include "clang/Driver/ToolChain.h"
21
#include "clang/Frontend/ChainedDiagnosticConsumer.h"
22
#include "clang/Frontend/CompilerInvocation.h"
23
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
24
#include "clang/Frontend/TextDiagnosticPrinter.h"
25
#include "clang/Frontend/Utils.h"
26
#include "llvm/ADT/ArrayRef.h"
27
#include "llvm/ADT/SmallString.h"
28
#include "llvm/ADT/SmallVector.h"
29
#include "llvm/Option/ArgList.h"
30
#include "llvm/Option/OptTable.h"
31
#include "llvm/Option/Option.h"
32
#include "llvm/Support/CommandLine.h"
33
#include "llvm/Support/ErrorHandling.h"
34
#include "llvm/Support/FileSystem.h"
35
#include "llvm/Support/Host.h"
36
#include "llvm/Support/InitLLVM.h"
37
#include "llvm/Support/Path.h"
38
#include "llvm/Support/Process.h"
39
#include "llvm/Support/Program.h"
40
#include "llvm/Support/Regex.h"
41
#include "llvm/Support/Signals.h"
42
#include "llvm/Support/StringSaver.h"
43
#include "llvm/Support/TargetSelect.h"
44
#include "llvm/Support/Timer.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <memory>
47
#include <set>
48
#include <system_error>
49
using namespace clang;
50
using namespace clang::driver;
51
using namespace llvm::opt;
52
53
20.8k
std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
54
20.8k
  if (!CanonicalPrefixes) {
55
783
    SmallString<128> ExecutablePath(Argv0);
56
783
    // Do a PATH lookup if Argv0 isn't a valid path.
57
783
    if (!llvm::sys::fs::exists(ExecutablePath))
58
0
      if (llvm::ErrorOr<std::string> P =
59
0
              llvm::sys::findProgramByName(ExecutablePath))
60
0
        ExecutablePath = *P;
61
783
    return ExecutablePath.str();
62
783
  }
63
20.0k
64
20.0k
  // This just needs to be some symbol in the binary; C++ doesn't
65
20.0k
  // allow taking the address of ::main however.
66
20.0k
  void *P = (void*) (intptr_t) GetExecutablePath;
67
20.0k
  return llvm::sys::fs::getMainExecutable(Argv0, P);
68
20.0k
}
69
70
static const char *GetStableCStr(std::set<std::string> &SavedStrings,
71
7.43k
                                 StringRef S) {
72
7.43k
  return SavedStrings.insert(S).first->c_str();
73
7.43k
}
74
75
/// ApplyQAOverride - Apply a list of edits to the input argument lists.
76
///
77
/// The input string is a space separate list of edits to perform,
78
/// they are applied in order to the input argument lists. Edits
79
/// should be one of the following forms:
80
///
81
///  '#': Silence information about the changes to the command line arguments.
82
///
83
///  '^': Add FOO as a new argument at the beginning of the command line.
84
///
85
///  '+': Add FOO as a new argument at the end of the command line.
86
///
87
///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
88
///  line.
89
///
90
///  'xOPTION': Removes all instances of the literal argument OPTION.
91
///
92
///  'XOPTION': Removes all instances of the literal argument OPTION,
93
///  and the following argument.
94
///
95
///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
96
///  at the end of the command line.
97
///
98
/// \param OS - The stream to write edit information to.
99
/// \param Args - The vector of command line arguments.
100
/// \param Edit - The override command to perform.
101
/// \param SavedStrings - Set to use for storing string representations.
102
static void ApplyOneQAOverride(raw_ostream &OS,
103
                               SmallVectorImpl<const char*> &Args,
104
                               StringRef Edit,
105
14
                               std::set<std::string> &SavedStrings) {
106
14
  // This does not need to be efficient.
107
14
108
14
  if (Edit[0] == '^') {
109
1
    const char *Str =
110
1
      GetStableCStr(SavedStrings, Edit.substr(1));
111
1
    OS << "### Adding argument " << Str << " at beginning\n";
112
1
    Args.insert(Args.begin() + 1, Str);
113
13
  } else if (Edit[0] == '+') {
114
9
    const char *Str =
115
9
      GetStableCStr(SavedStrings, Edit.substr(1));
116
9
    OS << "### Adding argument " << Str << " at end\n";
117
9
    Args.push_back(Str);
118
9
  } else 
if (4
Edit[0] == 's'4
&&
Edit[1] == '/'0
&&
Edit.endswith("/")0
&&
119
4
             
Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos0
) {
120
0
    StringRef MatchPattern = Edit.substr(2).split('/').first;
121
0
    StringRef ReplPattern = Edit.substr(2).split('/').second;
122
0
    ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
123
0
124
0
    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
125
0
      // Ignore end-of-line response file markers
126
0
      if (Args[i] == nullptr)
127
0
        continue;
128
0
      std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
129
0
130
0
      if (Repl != Args[i]) {
131
0
        OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
132
0
        Args[i] = GetStableCStr(SavedStrings, Repl);
133
0
      }
134
0
    }
135
4
  } else if (Edit[0] == 'x' || 
Edit[0] == 'X'2
) {
136
3
    auto Option = Edit.substr(1);
137
34
    for (unsigned i = 1; i < Args.size();) {
138
31
      if (Option == Args[i]) {
139
4
        OS << "### Deleting argument " << Args[i] << '\n';
140
4
        Args.erase(Args.begin() + i);
141
4
        if (Edit[0] == 'X') {
142
1
          if (i < Args.size()) {
143
1
            OS << "### Deleting argument " << Args[i] << '\n';
144
1
            Args.erase(Args.begin() + i);
145
1
          } else
146
0
            OS << "### Invalid X edit, end of command line!\n";
147
1
        }
148
4
      } else
149
27
        ++i;
150
31
    }
151
3
  } else 
if (1
Edit[0] == 'O'1
) {
152
11
    for (unsigned i = 1; i < Args.size();) {
153
10
      const char *A = Args[i];
154
10
      // Ignore end-of-line response file markers
155
10
      if (A == nullptr)
156
0
        continue;
157
10
      if (A[0] == '-' && 
A[1] == 'O'8
&&
158
10
          
(7
A[2] == '\0'7
||
159
7
           
(6
A[3] == '\0'6
&&
(5
A[2] == 's'5
||
A[2] == 'z'4
||
160
6
                             
(3
'0' <= A[2]3
&&
A[2] <= '9'3
))))) {
161
6
        OS << "### Deleting argument " << Args[i] << '\n';
162
6
        Args.erase(Args.begin() + i);
163
6
      } else
164
4
        ++i;
165
10
    }
166
1
    OS << "### Adding argument " << Edit << " at end\n";
167
1
    Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
168
1
  } else {
169
0
    OS << "### Unrecognized edit: " << Edit << "\n";
170
0
  }
171
14
}
172
173
/// ApplyQAOverride - Apply a comma separate list of edits to the
174
/// input argument lists. See ApplyOneQAOverride.
175
static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
176
                            const char *OverrideStr,
177
2
                            std::set<std::string> &SavedStrings) {
178
2
  raw_ostream *OS = &llvm::errs();
179
2
180
2
  if (OverrideStr[0] == '#') {
181
1
    ++OverrideStr;
182
1
    OS = &llvm::nulls();
183
1
  }
184
2
185
2
  *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
186
2
187
2
  // This does not need to be efficient.
188
2
189
2
  const char *S = OverrideStr;
190
17
  while (*S) {
191
15
    const char *End = ::strchr(S, ' ');
192
15
    if (!End)
193
1
      End = S + strlen(S);
194
15
    if (End != S)
195
14
      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
196
15
    S = End;
197
15
    if (*S != '\0')
198
14
      ++S;
199
15
  }
200
2
}
201
202
extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
203
                    void *MainAddr);
204
extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
205
                      void *MainAddr);
206
extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv,
207
                                  const char *Argv0, void *MainAddr);
208
209
static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
210
                                    SmallVectorImpl<const char *> &ArgVector,
211
20.8k
                                    std::set<std::string> &SavedStrings) {
212
20.8k
  // Put target and mode arguments at the start of argument list so that
213
20.8k
  // arguments specified in command line could override them. Avoid putting
214
20.8k
  // them at index 0, as an option like '-cc1' must remain the first.
215
20.8k
  int InsertionPoint = 0;
216
20.8k
  if (ArgVector.size() > 0)
217
20.8k
    ++InsertionPoint;
218
20.8k
219
20.8k
  if (NameParts.DriverMode) {
220
7.41k
    // Add the mode flag to the arguments.
221
7.41k
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
222
7.41k
                     GetStableCStr(SavedStrings, NameParts.DriverMode));
223
7.41k
  }
224
20.8k
225
20.8k
  if (NameParts.TargetIsValid) {
226
10
    const char *arr[] = {"-target", GetStableCStr(SavedStrings,
227
10
                                                  NameParts.TargetPrefix)};
228
10
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
229
10
                     std::begin(arr), std::end(arr));
230
10
  }
231
20.8k
}
232
233
static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
234
3
                               SmallVectorImpl<const char *> &Opts) {
235
3
  llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
236
3
  // The first instance of '#' should be replaced with '=' in each option.
237
3
  for (const char *Opt : Opts)
238
5
    if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
239
0
      *NumberSignPtr = '=';
240
3
}
241
242
20.8k
static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
243
20.8k
  // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
244
20.8k
  TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
245
20.8k
  if (TheDriver.CCPrintOptions)
246
1
    TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
247
20.8k
248
20.8k
  // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
249
20.8k
  TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
250
20.8k
  if (TheDriver.CCPrintHeaders)
251
1
    TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
252
20.8k
253
20.8k
  // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
254
20.8k
  TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
255
20.8k
  if (TheDriver.CCLogDiagnostics)
256
3
    TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
257
20.8k
}
258
259
static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
260
20.8k
                                   const std::string &Path) {
261
20.8k
  // If the clang binary happens to be named cl.exe for compatibility reasons,
262
20.8k
  // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
263
20.8k
  StringRef ExeBasename(llvm::sys::path::filename(Path));
264
20.8k
  if (ExeBasename.equals_lower("cl.exe"))
265
0
    ExeBasename = "clang-cl.exe";
266
20.8k
  DiagClient->setPrefix(ExeBasename);
267
20.8k
}
268
269
// This lets us create the DiagnosticsEngine with a properly-filled-out
270
// DiagnosticOptions instance.
271
static DiagnosticOptions *
272
20.8k
CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
273
20.8k
  auto *DiagOpts = new DiagnosticOptions;
274
20.8k
  std::unique_ptr<OptTable> Opts(createDriverOptTable());
275
20.8k
  unsigned MissingArgIndex, MissingArgCount;
276
20.8k
  InputArgList Args =
277
20.8k
      Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
278
20.8k
  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
279
20.8k
  // Any errors that would be diagnosed here will also be diagnosed later,
280
20.8k
  // when the DiagnosticsEngine actually exists.
281
20.8k
  (void)ParseDiagnosticArgs(*DiagOpts, Args);
282
20.8k
  return DiagOpts;
283
20.8k
}
284
285
static void SetInstallDir(SmallVectorImpl<const char *> &argv,
286
20.8k
                          Driver &TheDriver, bool CanonicalPrefixes) {
287
20.8k
  // Attempt to find the original path used to invoke the driver, to determine
288
20.8k
  // the installed path. We do this manually, because we want to support that
289
20.8k
  // path being a symlink.
290
20.8k
  SmallString<128> InstalledPath(argv[0]);
291
20.8k
292
20.8k
  // Do a PATH lookup, if there are no directory components.
293
20.8k
  if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
294
0
    if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
295
0
            llvm::sys::path::filename(InstalledPath.str())))
296
0
      InstalledPath = *Tmp;
297
20.8k
298
20.8k
  // FIXME: We don't actually canonicalize this, we just make it absolute.
299
20.8k
  if (CanonicalPrefixes)
300
20.0k
    llvm::sys::fs::make_absolute(InstalledPath);
301
20.8k
302
20.8k
  StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
303
20.8k
  if (llvm::sys::fs::exists(InstalledPathParent))
304
20.8k
    TheDriver.setInstalledDir(InstalledPathParent);
305
20.8k
}
306
307
35.7k
static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
308
35.7k
  void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
309
35.7k
  if (Tool == "")
310
34.9k
    return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
311
776
  if (Tool == "as")
312
772
    return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
313
4
  if (Tool == "gen-reproducer")
314
3
    return cc1gen_reproducer_main(argv.slice(2), argv[0], GetExecutablePathVP);
315
1
316
1
  // Reject unknown tools.
317
1
  llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
318
1
               << "Valid tools include '-cc1' and '-cc1as'.\n";
319
1
  return 1;
320
1
}
321
322
56.5k
int main(int argc_, const char **argv_) {
323
56.5k
  llvm::InitLLVM X(argc_, argv_);
324
56.5k
  SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
325
56.5k
326
56.5k
  if (llvm::sys::Process::FixupStandardFileDescriptors())
327
0
    return 1;
328
56.5k
329
56.5k
  llvm::InitializeAllTargets();
330
56.5k
  auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
331
56.5k
332
56.5k
  llvm::BumpPtrAllocator A;
333
56.5k
  llvm::StringSaver Saver(A);
334
56.5k
335
56.5k
  // Parse response files using the GNU syntax, unless we're in CL mode. There
336
56.5k
  // are two ways to put clang in CL compatibility mode: argv[0] is either
337
56.5k
  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
338
56.5k
  // command line parsing can't happen until after response file parsing, so we
339
56.5k
  // have to manually search for a --driver-mode=cl argument the hard way.
340
56.5k
  // Finally, our -cc1 tools don't care which tokenization mode we use because
341
56.5k
  // response files written by clang will tokenize the same way in either mode.
342
56.5k
  bool ClangCLMode = false;
343
56.5k
  if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
344
1.85M
      
std::find_if(argv.begin(), argv.end(), [](const char *F) 56.5k
{
345
1.85M
        return F && strcmp(F, "--driver-mode=cl") == 0;
346
1.85M
      }) != argv.end()) {
347
447
    ClangCLMode = true;
348
447
  }
349
56.5k
  enum { Default, POSIX, Windows } RSPQuoting = Default;
350
1.85M
  for (const char *F : argv) {
351
1.85M
    if (strcmp(F, "--rsp-quoting=posix") == 0)
352
0
      RSPQuoting = POSIX;
353
1.85M
    else if (strcmp(F, "--rsp-quoting=windows") == 0)
354
2
      RSPQuoting = Windows;
355
1.85M
  }
356
56.5k
357
56.5k
  // Determines whether we want nullptr markers in argv to indicate response
358
56.5k
  // files end-of-lines. We only use this for the /LINK driver argument with
359
56.5k
  // clang-cl.exe on Windows.
360
56.5k
  bool MarkEOLs = ClangCLMode;
361
56.5k
362
56.5k
  llvm::cl::TokenizerCallback Tokenizer;
363
56.5k
  if (RSPQuoting == Windows || 
(56.5k
RSPQuoting == Default56.5k
&&
ClangCLMode56.5k
))
364
449
    Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
365
56.1k
  else
366
56.1k
    Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
367
56.5k
368
56.5k
  if (MarkEOLs && 
argv.size() > 1447
&&
StringRef(argv[1]).startswith("-cc1")447
)
369
0
    MarkEOLs = false;
370
56.5k
  llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
371
56.5k
372
56.5k
  // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
373
56.5k
  // file.
374
56.5k
  auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
375
56.5k
                               [](const char *A) { return A != nullptr; });
376
56.5k
  if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
377
35.7k
    // If -cc1 came from a response file, remove the EOL sentinels.
378
35.7k
    if (MarkEOLs) {
379
0
      auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
380
0
      argv.resize(newEnd - argv.begin());
381
0
    }
382
35.7k
    return ExecuteCC1Tool(argv, argv[1] + 4);
383
35.7k
  }
384
20.8k
385
20.8k
  bool CanonicalPrefixes = true;
386
735k
  for (int i = 1, size = argv.size(); i < size; 
++i714k
) {
387
715k
    // Skip end-of-line response file markers
388
715k
    if (argv[i] == nullptr)
389
4
      continue;
390
715k
    if (StringRef(argv[i]) == "-no-canonical-prefixes") {
391
783
      CanonicalPrefixes = false;
392
783
      break;
393
783
    }
394
715k
  }
395
20.8k
396
20.8k
  // Handle CL and _CL_ which permits additional command line options to be
397
20.8k
  // prepended or appended.
398
20.8k
  if (ClangCLMode) {
399
447
    // Arguments in "CL" are prepended.
400
447
    llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
401
447
    if (OptCL.hasValue()) {
402
2
      SmallVector<const char *, 8> PrependedOpts;
403
2
      getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
404
2
405
2
      // Insert right after the program name to prepend to the argument list.
406
2
      argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
407
2
    }
408
447
    // Arguments in "_CL_" are appended.
409
447
    llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
410
447
    if (Opt_CL_.hasValue()) {
411
1
      SmallVector<const char *, 8> AppendedOpts;
412
1
      getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
413
1
414
1
      // Insert at the end of the argument list to append.
415
1
      argv.append(AppendedOpts.begin(), AppendedOpts.end());
416
1
    }
417
447
  }
418
20.8k
419
20.8k
  std::set<std::string> SavedStrings;
420
20.8k
  // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
421
20.8k
  // scenes.
422
20.8k
  if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
423
2
    // FIXME: Driver shouldn't take extra initial argument.
424
2
    ApplyQAOverride(argv, OverrideStr, SavedStrings);
425
2
  }
426
20.8k
427
20.8k
  std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
428
20.8k
429
20.8k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
430
20.8k
      CreateAndPopulateDiagOpts(argv);
431
20.8k
432
20.8k
  TextDiagnosticPrinter *DiagClient
433
20.8k
    = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
434
20.8k
  FixupDiagPrefixExeName(DiagClient, Path);
435
20.8k
436
20.8k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
437
20.8k
438
20.8k
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
439
20.8k
440
20.8k
  if (!DiagOpts->DiagnosticSerializationFile.empty()) {
441
11
    auto SerializedConsumer =
442
11
        clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
443
11
                                        &*DiagOpts, /*MergeChildRecords=*/true);
444
11
    Diags.setClient(new ChainedDiagnosticConsumer(
445
11
        Diags.takeClient(), std::move(SerializedConsumer)));
446
11
  }
447
20.8k
448
20.8k
  ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
449
20.8k
450
20.8k
  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
451
20.8k
  SetInstallDir(argv, TheDriver, CanonicalPrefixes);
452
20.8k
  TheDriver.setTargetAndMode(TargetAndMode);
453
20.8k
454
20.8k
  insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
455
20.8k
456
20.8k
  SetBackdoorDriverOutputsFromEnvVars(TheDriver);
457
20.8k
458
20.8k
  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
459
20.8k
  int Res = 1;
460
20.8k
  if (C && !C->containsError()) {
461
20.7k
    SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
462
20.7k
    Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
463
20.7k
464
20.7k
    // Force a crash to test the diagnostics.
465
20.7k
    if (TheDriver.GenReproducer) {
466
14
      Diags.Report(diag::err_drv_force_crash)
467
14
        << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
468
14
469
14
      // Pretend that every command failed.
470
14
      FailingCommands.clear();
471
14
      for (const auto &J : C->getJobs())
472
14
        if (const Command *C = dyn_cast<Command>(&J))
473
14
          FailingCommands.push_back(std::make_pair(-1, C));
474
14
    }
475
20.7k
476
20.7k
    for (const auto &P : FailingCommands) {
477
206
      int CommandRes = P.first;
478
206
      const Command *FailingCommand = P.second;
479
206
      if (!Res)
480
205
        Res = CommandRes;
481
206
482
206
      // If result status is < 0, then the driver command signalled an error.
483
206
      // If result status is 70, then the driver command reported a fatal error.
484
206
      // On Windows, abort will return an exit code of 3.  In these cases,
485
206
      // generate additional diagnostic information if possible.
486
206
      bool DiagnoseCrash = CommandRes < 0 || 
CommandRes == 70175
;
487
#ifdef _WIN32
488
      DiagnoseCrash |= CommandRes == 3;
489
#endif
490
206
      if (DiagnoseCrash) {
491
31
        TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
492
31
        break;
493
31
      }
494
206
    }
495
20.7k
  }
496
20.8k
497
20.8k
  Diags.getClient()->finish();
498
20.8k
499
20.8k
  // If any timers were active but haven't been destroyed yet, print their
500
20.8k
  // results now.  This happens in -disable-free mode.
501
20.8k
  llvm::TimerGroup::printAll(llvm::errs());
502
20.8k
503
#ifdef _WIN32
504
  // Exit status should not be negative on Win32, unless abnormal termination.
505
  // Once abnormal termiation was caught, negative status should not be
506
  // propagated.
507
  if (Res < 0)
508
    Res = 1;
509
#endif
510
511
20.8k
  // If we have multiple failing commands, we return the result of the first
512
20.8k
  // failing command.
513
20.8k
  return Res;
514
20.8k
}