tan  0.0.1
clang_driver.cpp
1 /**
2  * \file Based on https://github.com/llvm/llvm-project/blob/release/16.x/clang/tools/driver/driver.cpp
3  * Important changes are marked with "TAN_NOTE:"
4  */
5 
6 //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
7 //
8 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
9 // See https://llvm.org/LICENSE.txt for license information.
10 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
11 //
12 //===----------------------------------------------------------------------===//
13 //
14 // This is the entry point to the clang driver; it is a thin wrapper
15 // for functionality in the Driver clang library.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "clang/Driver/Driver.h"
20 #include "clang/Basic/DiagnosticOptions.h"
21 #include "clang/Basic/HeaderInclude.h"
22 #include "clang/Basic/Stack.h"
23 #include "clang/Config/config.h"
24 #include "clang/Driver/Compilation.h"
25 #include "clang/Driver/DriverDiagnostic.h"
26 #include "clang/Driver/Options.h"
27 #include "clang/Driver/ToolChain.h"
28 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
29 #include "clang/Frontend/CompilerInvocation.h"
30 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
31 #include "clang/Frontend/TextDiagnosticPrinter.h"
32 #include "clang/Frontend/Utils.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/OptTable.h"
38 #include "llvm/Option/Option.h"
39 #include "llvm/Support/BuryPointer.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/CrashRecoveryContext.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/Regex.h"
51 #include "llvm/Support/Signals.h"
52 #include "llvm/Support/StringSaver.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/Timer.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <memory>
57 #include <optional>
58 #include <set>
59 #include <system_error>
60 using namespace clang;
61 using namespace clang::driver;
62 using namespace llvm::opt;
63 
64 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
65  if (!CanonicalPrefixes) {
66  SmallString<128> ExecutablePath(Argv0);
67  // Do a PATH lookup if Argv0 isn't a valid path.
68  if (!llvm::sys::fs::exists(ExecutablePath))
69  if (llvm::ErrorOr<std::string> P = llvm::sys::findProgramByName(ExecutablePath))
70  ExecutablePath = *P;
71  return std::string(ExecutablePath.str());
72  }
73 
74  // This just needs to be some symbol in the binary; C++ doesn't
75  // allow taking the address of ::main however.
76  void *P = (void *)(intptr_t)GetExecutablePath;
77  return llvm::sys::fs::getMainExecutable(Argv0, P);
78 }
79 
80 static const char *GetStableCStr(std::set<std::string> &SavedStrings, StringRef S) {
81  return SavedStrings.insert(std::string(S)).first->c_str();
82 }
83 
84 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
85 ///
86 /// The input string is a space separate list of edits to perform,
87 /// they are applied in order to the input argument lists. Edits
88 /// should be one of the following forms:
89 ///
90 /// '#': Silence information about the changes to the command line arguments.
91 ///
92 /// '^': Add FOO as a new argument at the beginning of the command line.
93 ///
94 /// '+': Add FOO as a new argument at the end of the command line.
95 ///
96 /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
97 /// line.
98 ///
99 /// 'xOPTION': Removes all instances of the literal argument OPTION.
100 ///
101 /// 'XOPTION': Removes all instances of the literal argument OPTION,
102 /// and the following argument.
103 ///
104 /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
105 /// at the end of the command line.
106 ///
107 /// \param OS - The stream to write edit information to.
108 /// \param Args - The vector of command line arguments.
109 /// \param Edit - The override command to perform.
110 /// \param SavedStrings - Set to use for storing string representations.
111 static void ApplyOneQAOverride(raw_ostream &OS,
112  SmallVectorImpl<const char *> &Args,
113  StringRef Edit,
114  std::set<std::string> &SavedStrings) {
115  // This does not need to be efficient.
116 
117  if (Edit[0] == '^') {
118  const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
119  OS << "### Adding argument " << Str << " at beginning\n";
120  Args.insert(Args.begin() + 1, Str);
121  } else if (Edit[0] == '+') {
122  const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
123  OS << "### Adding argument " << Str << " at end\n";
124  Args.push_back(Str);
125  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") && Edit.slice(2, Edit.size() - 1).contains('/')) {
126  StringRef MatchPattern = Edit.substr(2).split('/').first;
127  StringRef ReplPattern = Edit.substr(2).split('/').second;
128  ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
129 
130  for (unsigned i = 1, e = Args.size(); i != e; ++i) {
131  // Ignore end-of-line response file markers
132  if (Args[i] == nullptr)
133  continue;
134  std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
135 
136  if (Repl != Args[i]) {
137  OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
138  Args[i] = GetStableCStr(SavedStrings, Repl);
139  }
140  }
141  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
142  auto Option = Edit.substr(1);
143  for (unsigned i = 1; i < Args.size();) {
144  if (Option == Args[i]) {
145  OS << "### Deleting argument " << Args[i] << '\n';
146  Args.erase(Args.begin() + i);
147  if (Edit[0] == 'X') {
148  if (i < Args.size()) {
149  OS << "### Deleting argument " << Args[i] << '\n';
150  Args.erase(Args.begin() + i);
151  } else
152  OS << "### Invalid X edit, end of command line!\n";
153  }
154  } else
155  ++i;
156  }
157  } else if (Edit[0] == 'O') {
158  for (unsigned i = 1; i < Args.size();) {
159  const char *A = Args[i];
160  // Ignore end-of-line response file markers
161  if (A == nullptr)
162  continue;
163  if (A[0] == '-' && A[1] == 'O' &&
164  (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' || ('0' <= A[2] && A[2] <= '9'))))) {
165  OS << "### Deleting argument " << Args[i] << '\n';
166  Args.erase(Args.begin() + i);
167  } else
168  ++i;
169  }
170  OS << "### Adding argument " << Edit << " at end\n";
171  Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
172  } else {
173  OS << "### Unrecognized edit: " << Edit << "\n";
174  }
175 }
176 
177 /// ApplyQAOverride - Apply a comma separate list of edits to the
178 /// input argument lists. See ApplyOneQAOverride.
179 static void
180 ApplyQAOverride(SmallVectorImpl<const char *> &Args, const char *OverrideStr, std::set<std::string> &SavedStrings) {
181  raw_ostream *OS = &llvm::errs();
182 
183  if (OverrideStr[0] == '#') {
184  ++OverrideStr;
185  OS = &llvm::nulls();
186  }
187 
188  *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
189 
190  // This does not need to be efficient.
191 
192  const char *S = OverrideStr;
193  while (*S) {
194  const char *End = ::strchr(S, ' ');
195  if (!End)
196  End = S + strlen(S);
197  if (End != S)
198  ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
199  S = End;
200  if (*S != '\0')
201  ++S;
202  }
203 }
204 
205 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr);
206 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr);
207 extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr);
208 
209 static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
210  SmallVectorImpl<const char *> &ArgVector,
211  std::set<std::string> &SavedStrings) {
212  // Put target and mode arguments at the start of argument list so that
213  // arguments specified in command line could override them. Avoid putting
214  // them at index 0, as an option like '-cc1' must remain the first.
215  int InsertionPoint = 0;
216  if (ArgVector.size() > 0)
217  ++InsertionPoint;
218 
219  if (NameParts.DriverMode) {
220  // Add the mode flag to the arguments.
221  ArgVector.insert(ArgVector.begin() + InsertionPoint, GetStableCStr(SavedStrings, NameParts.DriverMode));
222  }
223 
224  if (NameParts.TargetIsValid) {
225  const char *arr[] = {"-target", GetStableCStr(SavedStrings, NameParts.TargetPrefix)};
226  ArgVector.insert(ArgVector.begin() + InsertionPoint, std::begin(arr), std::end(arr));
227  }
228 }
229 
230 static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver, SmallVectorImpl<const char *> &Opts) {
231  llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
232  // The first instance of '#' should be replaced with '=' in each option.
233  for (const char *Opt : Opts)
234  if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
235  *NumberSignPtr = '=';
236 }
237 
238 template <class T> static T checkEnvVar(const char *EnvOptSet, const char *EnvOptFile, std::string &OptFile) {
239  const char *Str = ::getenv(EnvOptSet);
240  if (!Str)
241  return T{};
242 
243  T OptVal = Str;
244  if (const char *Var = ::getenv(EnvOptFile))
245  OptFile = Var;
246  return OptVal;
247 }
248 
249 static bool SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
250  TheDriver.CCPrintOptions =
251  checkEnvVar<bool>("CC_PRINT_OPTIONS", "CC_PRINT_OPTIONS_FILE", TheDriver.CCPrintOptionsFilename);
252  if (checkEnvVar<bool>("CC_PRINT_HEADERS", "CC_PRINT_HEADERS_FILE", TheDriver.CCPrintHeadersFilename)) {
253  TheDriver.CCPrintHeadersFormat = HIFMT_Textual;
254  TheDriver.CCPrintHeadersFiltering = HIFIL_None;
255  } else {
256  std::string EnvVar =
257  checkEnvVar<std::string>("CC_PRINT_HEADERS_FORMAT", "CC_PRINT_HEADERS_FILE", TheDriver.CCPrintHeadersFilename);
258  if (!EnvVar.empty()) {
259  TheDriver.CCPrintHeadersFormat = stringToHeaderIncludeFormatKind(EnvVar.c_str());
260  if (!TheDriver.CCPrintHeadersFormat) {
261  TheDriver.Diag(clang::diag::err_drv_print_header_env_var) << 0 << EnvVar;
262  return false;
263  }
264 
265  const char *FilteringStr = ::getenv("CC_PRINT_HEADERS_FILTERING");
266  HeaderIncludeFilteringKind Filtering;
267  if (!stringToHeaderIncludeFiltering(FilteringStr, Filtering)) {
268  TheDriver.Diag(clang::diag::err_drv_print_header_env_var) << 1 << FilteringStr;
269  return false;
270  }
271 
272  if ((TheDriver.CCPrintHeadersFormat == HIFMT_Textual && Filtering != HIFIL_None) ||
273  (TheDriver.CCPrintHeadersFormat == HIFMT_JSON && Filtering != HIFIL_Only_Direct_System)) {
274  TheDriver.Diag(clang::diag::err_drv_print_header_env_var_combination) << EnvVar << FilteringStr;
275  return false;
276  }
277  TheDriver.CCPrintHeadersFiltering = Filtering;
278  }
279  }
280 
281  TheDriver.CCLogDiagnostics =
282  checkEnvVar<bool>("CC_LOG_DIAGNOSTICS", "CC_LOG_DIAGNOSTICS_FILE", TheDriver.CCLogDiagnosticsFilename);
283  TheDriver.CCPrintProcessStats =
284  checkEnvVar<bool>("CC_PRINT_PROC_STAT", "CC_PRINT_PROC_STAT_FILE", TheDriver.CCPrintStatReportFilename);
285 
286  return true;
287 }
288 
289 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient, const std::string &Path) {
290  // If the clang binary happens to be named cl.exe for compatibility reasons,
291  // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
292  StringRef ExeBasename(llvm::sys::path::stem(Path));
293  if (ExeBasename.equals_insensitive("cl"))
294  ExeBasename = "clang-cl";
295  DiagClient->setPrefix(std::string(ExeBasename));
296 }
297 
298 static void SetInstallDir(SmallVectorImpl<const char *> &argv, Driver &TheDriver, bool CanonicalPrefixes) {
299  // Attempt to find the original path used to invoke the driver, to determine
300  // the installed path. We do this manually, because we want to support that
301  // path being a symlink.
302  SmallString<128> InstalledPath(argv[0]);
303 
304  // Do a PATH lookup, if there are no directory components.
305  if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
306  if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(llvm::sys::path::filename(InstalledPath.str())))
307  InstalledPath = *Tmp;
308 
309  // FIXME: We don't actually canonicalize this, we just make it absolute.
310  if (CanonicalPrefixes)
311  llvm::sys::fs::make_absolute(InstalledPath);
312 
313  StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
314  if (llvm::sys::fs::exists(InstalledPathParent))
315  TheDriver.setInstalledDir(InstalledPathParent);
316 }
317 
318 static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV) {
319  // If we call the cc1 tool from the clangDriver library (through
320  // Driver::CC1Main), we need to clean up the options usage count. The options
321  // are currently global, and they might have been used previously by the
322  // driver.
323  llvm::cl::ResetAllOptionOccurrences();
324 
325  llvm::BumpPtrAllocator A;
326  llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine);
327  if (llvm::Error Err = ECtx.expandResponseFiles(ArgV)) {
328  llvm::errs() << toString(std::move(Err)) << '\n';
329  return 1;
330  }
331  StringRef Tool = ArgV[1];
332  void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath;
333  if (Tool == "-cc1")
334  return cc1_main(ArrayRef(ArgV).slice(1), ArgV[0], GetExecutablePathVP);
335  if (Tool == "-cc1as")
336  return cc1as_main(ArrayRef(ArgV).slice(2), ArgV[0], GetExecutablePathVP);
337  if (Tool == "-cc1gen-reproducer")
338  return cc1gen_reproducer_main(ArrayRef(ArgV).slice(2), ArgV[0], GetExecutablePathVP);
339  // Reject unknown tools.
340  llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
341  << "Valid tools include '-cc1' and '-cc1as'.\n";
342  return 1;
343 }
344 
345 int clang_main(int Argc, char **Argv) {
346  noteBottomOfStack();
347  llvm::InitLLVM X(Argc, Argv);
348  llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
349  " and include the crash backtrace, preprocessed "
350  "source, and associated run script.\n");
351  SmallVector<const char *, 256> Args(Argv, Argv + Argc);
352 
353  if (llvm::sys::Process::FixupStandardFileDescriptors())
354  return 1;
355 
356  llvm::InitializeAllTargets();
357 
358  llvm::BumpPtrAllocator A;
359  llvm::StringSaver Saver(A);
360 
361  // Parse response files using the GNU syntax, unless we're in CL mode. There
362  // are two ways to put clang in CL compatibility mode: Args[0] is either
363  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
364  // command line parsing can't happen until after response file parsing, so we
365  // have to manually search for a --driver-mode=cl argument the hard way.
366  // Finally, our -cc1 tools don't care which tokenization mode we use because
367  // response files written by clang will tokenize the same way in either mode.
368  bool ClangCLMode = IsClangCL(getDriverMode(Args[0], llvm::ArrayRef(Args).slice(1)));
369  enum { Default, POSIX, Windows } RSPQuoting = Default;
370  for (const char *F : Args) {
371  if (strcmp(F, "--rsp-quoting=posix") == 0)
372  RSPQuoting = POSIX;
373  else if (strcmp(F, "--rsp-quoting=windows") == 0)
374  RSPQuoting = Windows;
375  }
376 
377  // Determines whether we want nullptr markers in Args to indicate response
378  // files end-of-lines. We only use this for the /LINK driver argument with
379  // clang-cl.exe on Windows.
380  bool MarkEOLs = ClangCLMode;
381 
382  llvm::cl::TokenizerCallback Tokenizer;
383  if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
384  Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
385  else
386  Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
387 
388  if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).startswith("-cc1"))
389  MarkEOLs = false;
390  llvm::cl::ExpansionContext ECtx(A, Tokenizer);
391  ECtx.setMarkEOLs(MarkEOLs);
392  if (llvm::Error Err = ECtx.expandResponseFiles(Args)) {
393  llvm::errs() << toString(std::move(Err)) << '\n';
394  return 1;
395  }
396 
397  // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
398  // file.
399  auto FirstArg = llvm::find_if(llvm::drop_begin(Args), [](const char *A) { return A != nullptr; });
400  if (FirstArg != Args.end() && StringRef(*FirstArg).startswith("-cc1")) {
401  // If -cc1 came from a response file, remove the EOL sentinels.
402  if (MarkEOLs) {
403  auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
404  Args.resize(newEnd - Args.begin());
405  }
406  return ExecuteCC1Tool(Args);
407  }
408 
409  // Handle options that need handling before the real command line parsing in
410  // Driver::BuildCompilation()
411  bool CanonicalPrefixes = true;
412  for (int i = 1, size = Args.size(); i < size; ++i) {
413  // Skip end-of-line response file markers
414  if (Args[i] == nullptr)
415  continue;
416  if (StringRef(Args[i]) == "-canonical-prefixes")
417  CanonicalPrefixes = true;
418  else if (StringRef(Args[i]) == "-no-canonical-prefixes")
419  CanonicalPrefixes = false;
420  }
421 
422  // Handle CL and _CL_ which permits additional command line options to be
423  // prepended or appended.
424  if (ClangCLMode) {
425  // Arguments in "CL" are prepended.
426  std::optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
427  if (OptCL) {
428  SmallVector<const char *, 8> PrependedOpts;
429  getCLEnvVarOptions(*OptCL, Saver, PrependedOpts);
430 
431  // Insert right after the program name to prepend to the argument list.
432  Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
433  }
434  // Arguments in "_CL_" are appended.
435  std::optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
436  if (Opt_CL_) {
437  SmallVector<const char *, 8> AppendedOpts;
438  getCLEnvVarOptions(*Opt_CL_, Saver, AppendedOpts);
439 
440  // Insert at the end of the argument list to append.
441  Args.append(AppendedOpts.begin(), AppendedOpts.end());
442  }
443  }
444 
445  std::set<std::string> SavedStrings;
446  // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
447  // scenes.
448  if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
449  // FIXME: Driver shouldn't take extra initial argument.
450  ApplyQAOverride(Args, OverrideStr, SavedStrings);
451  }
452 
453  /**
454  * TAN_NOTE: CanonicalPrefixes must be set to false
455  * Otherwise GetExecutablePath will use a function pointer to get the actual executable path of the current process,
456  * which is pointing to `tanc`. Then the driver will run the executable, which is not we want. We want the drvier to
457  * call clang installed on our system.
458  */
459  std::string Path = GetExecutablePath(Args[0], false);
460 
461  // Whether the cc1 tool should be called inside the current process, or if we
462  // should spawn a new clang subprocess (old behavior).
463  // Not having an additional process saves some execution time of Windows,
464  // and makes debugging and profiling easier.
465  bool UseNewCC1Process = CLANG_SPAWN_CC1;
466  for (const char *Arg : Args)
467  UseNewCC1Process = llvm::StringSwitch<bool>(Arg)
468  .Case("-fno-integrated-cc1", true)
469  .Case("-fintegrated-cc1", false)
470  .Default(UseNewCC1Process);
471 
472  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(Args);
473 
474  TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
475  FixupDiagPrefixExeName(DiagClient, Path);
476 
477  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
478 
479  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
480 
481  if (!DiagOpts->DiagnosticSerializationFile.empty()) {
482  auto SerializedConsumer =
483  clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile, &*DiagOpts, /*MergeChildRecords=*/true);
484  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(SerializedConsumer)));
485  }
486 
487  ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
488 
489  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
490  SetInstallDir(Args, TheDriver, CanonicalPrefixes);
491  auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(Args[0]);
492  TheDriver.setTargetAndMode(TargetAndMode);
493 
494  insertTargetAndModeArgs(TargetAndMode, Args, SavedStrings);
495 
496  if (!SetBackdoorDriverOutputsFromEnvVars(TheDriver))
497  return 1;
498 
499  if (!UseNewCC1Process) {
500  TheDriver.CC1Main = &ExecuteCC1Tool;
501  // Ensure the CC1Command actually catches cc1 crashes
502  llvm::CrashRecoveryContext::Enable();
503  }
504 
505  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
506 
507  Driver::ReproLevel ReproLevel = Driver::ReproLevel::OnCrash;
508  if (Arg *A = C->getArgs().getLastArg(options::OPT_gen_reproducer_eq)) {
509  auto Level = llvm::StringSwitch<std::optional<Driver::ReproLevel>>(A->getValue())
510  .Case("off", Driver::ReproLevel::Off)
511  .Case("crash", Driver::ReproLevel::OnCrash)
512  .Case("error", Driver::ReproLevel::OnError)
513  .Case("always", Driver::ReproLevel::Always)
514  .Default(std::nullopt);
515  if (!Level) {
516  llvm::errs() << "Unknown value for " << A->getSpelling() << ": '" << A->getValue() << "'\n";
517  return 1;
518  }
519  ReproLevel = *Level;
520  }
521  if (!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
522  ReproLevel = Driver::ReproLevel::Always;
523 
524  int Res = 1;
525  bool IsCrash = false;
526  Driver::CommandStatus CommandStatus = Driver::CommandStatus::Ok;
527  // Pretend the first command failed if ReproStatus is Always.
528  const Command *FailingCommand = nullptr;
529  if (!C->getJobs().empty())
530  FailingCommand = &*C->getJobs().begin();
531  if (C && !C->containsError()) {
532  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
533  Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
534 
535  for (const auto &P : FailingCommands) {
536  int CommandRes = P.first;
537  FailingCommand = P.second;
538  if (!Res)
539  Res = CommandRes;
540 
541  // If result status is < 0, then the driver command signalled an error.
542  // If result status is 70, then the driver command reported a fatal error.
543  // On Windows, abort will return an exit code of 3. In these cases,
544  // generate additional diagnostic information if possible.
545  IsCrash = CommandRes < 0 || CommandRes == 70;
546 #ifdef _WIN32
547  IsCrash |= CommandRes == 3;
548 #endif
549 #if LLVM_ON_UNIX
550  // When running in integrated-cc1 mode, the CrashRecoveryContext returns
551  // the same codes as if the program crashed. See section "Exit Status for
552  // Commands":
553  // https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html
554  IsCrash |= CommandRes > 128;
555 #endif
556  CommandStatus = IsCrash ? Driver::CommandStatus::Crash : Driver::CommandStatus::Error;
557  if (IsCrash)
558  break;
559  }
560  }
561 
562  // Print the bug report message that would be printed if we did actually
563  // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
564  if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
565  llvm::dbgs() << llvm::getBugReportMsg();
566  if (FailingCommand != nullptr &&
567  TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel, *C, *FailingCommand))
568  Res = 1;
569 
570  Diags.getClient()->finish();
571 
572  if (!UseNewCC1Process && IsCrash) {
573  // When crashing in -fintegrated-cc1 mode, bury the timer pointers, because
574  // the internal linked list might point to already released stack frames.
575  llvm::BuryPointer(llvm::TimerGroup::aquireDefaultGroup());
576  } else {
577  // If any timers were active but haven't been destroyed yet, print their
578  // results now. This happens in -disable-free mode.
579  llvm::TimerGroup::printAll(llvm::errs());
580  llvm::TimerGroup::clearAll();
581  }
582 
583 #ifdef _WIN32
584  // Exit status should not be negative on Win32, unless abnormal termination.
585  // Once abnormal termination was caught, negative status should not be
586  // propagated.
587  if (Res < 0)
588  Res = 1;
589 #endif
590 
591  // If we have multiple failing commands, we return the result of the first
592  // failing command.
593  return Res;
594 }