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