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