blob: dfc96d308ab5042c1f6bb356748c03280e7e3fac [file] [log] [blame]
Daniel Dunbar544ecd12009-03-02 19:59:07 +00001//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Dunbar544ecd12009-03-02 19:59:07 +00006//
7//===----------------------------------------------------------------------===//
8//
Daniel Dunbarb2da9332009-03-03 05:55:11 +00009// This is the entry point to the clang driver; it is a thin wrapper
10// for functionality in the Driver clang library.
Daniel Dunbar544ecd12009-03-02 19:59:07 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyamae4b59a92018-04-13 20:57:57 +000014#include "clang/Driver/Driver.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000015#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbar544ecd12009-03-02 19:59:07 +000016#include "clang/Driver/Compilation.h"
Richard Smith940a6d72012-12-25 21:56:27 +000017#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000018#include "clang/Driver/Options.h"
Eric Christopher74a7c5d2015-09-25 17:44:31 +000019#include "clang/Driver/ToolChain.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000020#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000021#include "clang/Frontend/CompilerInvocation.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000022#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar12ee3802010-02-25 03:23:43 +000023#include "clang/Frontend/TextDiagnosticPrinter.h"
Chad Rosierd6f716a2012-03-13 20:09:56 +000024#include "clang/Frontend/Utils.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000025#include "llvm/ADT/ArrayRef.h"
Daniel Dunbard9b80c22009-03-18 02:11:26 +000026#include "llvm/ADT/SmallString.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000027#include "llvm/ADT/SmallVector.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000028#include "llvm/Option/ArgList.h"
29#include "llvm/Option/OptTable.h"
30#include "llvm/Option/Option.h"
Reid Kleckner61b23b72013-07-18 20:00:53 +000031#include "llvm/Support/CommandLine.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000032#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000033#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000034#include "llvm/Support/Host.h"
Rui Ueyamae4b59a92018-04-13 20:57:57 +000035#include "llvm/Support/InitLLVM.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000036#include "llvm/Support/Path.h"
David Majnemer3f8f8c92013-10-07 07:33:27 +000037#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000038#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000039#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Signals.h"
Rafael Espindola2b098e42015-06-13 12:50:07 +000041#include "llvm/Support/StringSaver.h"
Evan Cheng494eb062011-08-24 18:09:14 +000042#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000043#include "llvm/Support/Timer.h"
44#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000045#include <memory>
Mehdi Amini9670f842016-07-18 19:02:11 +000046#include <set>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000047#include <system_error>
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000048using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000049using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000050using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000051
Rafael Espindola9678d272013-06-26 05:03:40 +000052std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Petr Hosek8f90efe2017-06-16 22:40:18 +000053 if (!CanonicalPrefixes) {
54 SmallString<128> ExecutablePath(Argv0);
55 // Do a PATH lookup if Argv0 isn't a valid path.
56 if (!llvm::sys::fs::exists(ExecutablePath))
57 if (llvm::ErrorOr<std::string> P =
58 llvm::sys::findProgramByName(ExecutablePath))
59 ExecutablePath = *P;
60 return ExecutablePath.str();
61 }
Rafael Espindola73d46372009-12-04 19:31:58 +000062
Daniel Dunbarda382a82009-03-18 20:25:53 +000063 // This just needs to be some symbol in the binary; C++ doesn't
64 // allow taking the address of ::main however.
65 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000066 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000067}
68
Sean Silva6a9b0f92014-08-15 19:23:53 +000069static const char *GetStableCStr(std::set<std::string> &SavedStrings,
70 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000071 return SavedStrings.insert(S).first->c_str();
72}
73
74/// ApplyQAOverride - Apply a list of edits to the input argument lists.
75///
76/// The input string is a space separate list of edits to perform,
77/// they are applied in order to the input argument lists. Edits
78/// should be one of the following forms:
79///
Daniel Dunbar54091b82009-07-16 21:32:51 +000080/// '#': Silence information about the changes to the command line arguments.
81///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000082/// '^': Add FOO as a new argument at the beginning of the command line.
83///
84/// '+': Add FOO as a new argument at the end of the command line.
85///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000086/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
87/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000088///
89/// 'xOPTION': Removes all instances of the literal argument OPTION.
90///
91/// 'XOPTION': Removes all instances of the literal argument OPTION,
92/// and the following argument.
93///
94/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
95/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000096///
97/// \param OS - The stream to write edit information to.
98/// \param Args - The vector of command line arguments.
99/// \param Edit - The override command to perform.
100/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000101static void ApplyOneQAOverride(raw_ostream &OS,
102 SmallVectorImpl<const char*> &Args,
103 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000104 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000105 // This does not need to be efficient.
106
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000107 if (Edit[0] == '^') {
108 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000109 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000110 OS << "### Adding argument " << Str << " at beginning\n";
111 Args.insert(Args.begin() + 1, Str);
112 } else if (Edit[0] == '+') {
113 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000114 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000115 OS << "### Adding argument " << Str << " at end\n";
116 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000117 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000118 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
119 StringRef MatchPattern = Edit.substr(2).split('/').first;
120 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000121 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
122
123 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000124 // Ignore end-of-line response file markers
125 if (Args[i] == nullptr)
126 continue;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000127 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
128
129 if (Repl != Args[i]) {
130 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000131 Args[i] = GetStableCStr(SavedStrings, Repl);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000132 }
133 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000134 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
Benjamin Kramer0772c422016-02-13 13:42:54 +0000135 auto Option = Edit.substr(1);
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000136 for (unsigned i = 1; i < Args.size();) {
137 if (Option == Args[i]) {
138 OS << "### Deleting argument " << Args[i] << '\n';
139 Args.erase(Args.begin() + i);
140 if (Edit[0] == 'X') {
141 if (i < Args.size()) {
142 OS << "### Deleting argument " << Args[i] << '\n';
143 Args.erase(Args.begin() + i);
144 } else
145 OS << "### Invalid X edit, end of command line!\n";
146 }
147 } else
148 ++i;
149 }
150 } else if (Edit[0] == 'O') {
151 for (unsigned i = 1; i < Args.size();) {
152 const char *A = Args[i];
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000153 // Ignore end-of-line response file markers
154 if (A == nullptr)
155 continue;
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000156 if (A[0] == '-' && A[1] == 'O' &&
157 (A[2] == '\0' ||
158 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
159 ('0' <= A[2] && A[2] <= '9'))))) {
160 OS << "### Deleting argument " << Args[i] << '\n';
161 Args.erase(Args.begin() + i);
162 } else
163 ++i;
164 }
165 OS << "### Adding argument " << Edit << " at end\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000166 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000167 } else {
168 OS << "### Unrecognized edit: " << Edit << "\n";
169 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000170}
171
172/// ApplyQAOverride - Apply a comma separate list of edits to the
173/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000174static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000175 const char *OverrideStr,
176 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000177 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000178
Daniel Dunbar54091b82009-07-16 21:32:51 +0000179 if (OverrideStr[0] == '#') {
180 ++OverrideStr;
181 OS = &llvm::nulls();
182 }
183
Bob Wilsona19fad72014-01-15 01:41:52 +0000184 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000185
186 // This does not need to be efficient.
187
188 const char *S = OverrideStr;
189 while (*S) {
190 const char *End = ::strchr(S, ' ');
191 if (!End)
192 End = S + strlen(S);
193 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000194 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000195 S = End;
196 if (*S != '\0')
197 ++S;
198 }
199}
200
Sean Silva070cd2d2014-08-15 21:38:36 +0000201extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
202 void *MainAddr);
203extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
204 void *MainAddr);
Alex Lorenz045c5142018-04-07 00:03:27 +0000205extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv,
206 const char *Argv0, void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000207
Serge Pavlov4e769842017-08-29 05:22:26 +0000208static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
Eric Christopher74a7c5d2015-09-25 17:44:31 +0000209 SmallVectorImpl<const char *> &ArgVector,
210 std::set<std::string> &SavedStrings) {
Serge Pavlov3b7d3812017-09-20 15:22:27 +0000211 // Put target and mode arguments at the start of argument list so that
212 // arguments specified in command line could override them. Avoid putting
213 // them at index 0, as an option like '-cc1' must remain the first.
Serge Pavlov826e83312018-03-19 16:13:43 +0000214 int InsertionPoint = 0;
215 if (ArgVector.size() > 0)
Serge Pavlov3b7d3812017-09-20 15:22:27 +0000216 ++InsertionPoint;
217
Serge Pavlov4e769842017-08-29 05:22:26 +0000218 if (NameParts.DriverMode) {
Eric Christopher74a7c5d2015-09-25 17:44:31 +0000219 // Add the mode flag to the arguments.
Serge Pavlov826e83312018-03-19 16:13:43 +0000220 ArgVector.insert(ArgVector.begin() + InsertionPoint,
Serge Pavlov4e769842017-08-29 05:22:26 +0000221 GetStableCStr(SavedStrings, NameParts.DriverMode));
Hans Wennborg1a27e042014-10-17 17:07:59 +0000222 }
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000223
Serge Pavlov4e769842017-08-29 05:22:26 +0000224 if (NameParts.TargetIsValid) {
225 const char *arr[] = {"-target", GetStableCStr(SavedStrings,
226 NameParts.TargetPrefix)};
Serge Pavlov826e83312018-03-19 16:13:43 +0000227 ArgVector.insert(ArgVector.begin() + InsertionPoint,
228 std::begin(arr), std::end(arr));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000229 }
230}
231
David Majnemer3a4f9582015-08-10 18:16:32 +0000232static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
233 SmallVectorImpl<const char *> &Opts) {
234 llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
235 // The first instance of '#' should be replaced with '=' in each option.
236 for (const char *Opt : Opts)
237 if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
238 *NumberSignPtr = '=';
239}
240
Sean Silva0ee846f2014-08-15 20:59:03 +0000241static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
Sean Silva2103c382014-08-15 18:50:00 +0000242 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
243 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
244 if (TheDriver.CCPrintOptions)
245 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
246
247 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
248 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
249 if (TheDriver.CCPrintHeaders)
250 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
251
252 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
253 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
254 if (TheDriver.CCLogDiagnostics)
255 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
256}
257
Sean Silva965bb992014-08-15 18:58:09 +0000258static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
259 const std::string &Path) {
260 // If the clang binary happens to be named cl.exe for compatibility reasons,
261 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
Nico Webera2761e42018-08-22 23:53:39 +0000262 StringRef ExeBasename(llvm::sys::path::stem(Path));
263 if (ExeBasename.equals_lower("cl"))
264 ExeBasename = "clang-cl";
Sean Silva965bb992014-08-15 18:58:09 +0000265 DiagClient->setPrefix(ExeBasename);
266}
267
Sean Silva22b4a342014-08-15 18:58:12 +0000268// This lets us create the DiagnosticsEngine with a properly-filled-out
269// DiagnosticOptions instance.
270static DiagnosticOptions *
David Blaikie6d492ad2015-06-21 06:32:36 +0000271CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
Sean Silva22b4a342014-08-15 18:58:12 +0000272 auto *DiagOpts = new DiagnosticOptions;
273 std::unique_ptr<OptTable> Opts(createDriverOptTable());
274 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000275 InputArgList Args =
276 Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
Sean Silva22b4a342014-08-15 18:58:12 +0000277 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
278 // Any errors that would be diagnosed here will also be diagnosed later,
279 // when the DiagnosticsEngine actually exists.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000280 (void)ParseDiagnosticArgs(*DiagOpts, Args);
Sean Silva22b4a342014-08-15 18:58:12 +0000281 return DiagOpts;
282}
283
Sean Silvab5060472014-08-15 18:58:15 +0000284static void SetInstallDir(SmallVectorImpl<const char *> &argv,
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000285 Driver &TheDriver, bool CanonicalPrefixes) {
Sean Silvab5060472014-08-15 18:58:15 +0000286 // Attempt to find the original path used to invoke the driver, to determine
287 // the installed path. We do this manually, because we want to support that
288 // path being a symlink.
289 SmallString<128> InstalledPath(argv[0]);
290
291 // Do a PATH lookup, if there are no directory components.
Michael J. Spencerb011d482014-11-07 21:30:32 +0000292 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
293 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
294 llvm::sys::path::filename(InstalledPath.str())))
Michael J. Spencer04162ea2014-11-04 01:30:55 +0000295 InstalledPath = *Tmp;
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000296
297 // FIXME: We don't actually canonicalize this, we just make it absolute.
298 if (CanonicalPrefixes)
299 llvm::sys::fs::make_absolute(InstalledPath);
300
Joerg Sonnenberger9db01aa2016-01-15 22:29:34 +0000301 StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
302 if (llvm::sys::fs::exists(InstalledPathParent))
303 TheDriver.setInstalledDir(InstalledPathParent);
Sean Silvab5060472014-08-15 18:58:15 +0000304}
305
Sean Silva5d62c262014-08-15 21:40:51 +0000306static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
Sean Silva070cd2d2014-08-15 21:38:36 +0000307 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000308 if (Tool == "")
Sean Silva070cd2d2014-08-15 21:38:36 +0000309 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000310 if (Tool == "as")
Sean Silva070cd2d2014-08-15 21:38:36 +0000311 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
Alex Lorenz045c5142018-04-07 00:03:27 +0000312 if (Tool == "gen-reproducer")
313 return cc1gen_reproducer_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000314
315 // Reject unknown tools.
Brian Gesiak28db3142018-01-15 21:05:40 +0000316 llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
317 << "Valid tools include '-cc1' and '-cc1as'.\n";
Sean Silva9a6bdf82014-08-15 19:23:47 +0000318 return 1;
319}
320
Rafael Espindola77a067a2010-07-19 15:20:12 +0000321int main(int argc_, const char **argv_) {
Rui Ueyamae4b59a92018-04-13 20:57:57 +0000322 llvm::InitLLVM X(argc_, argv_);
323 SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
Rafael Espindola77a067a2010-07-19 15:20:12 +0000324
David Majnemer33498722014-10-06 23:52:23 +0000325 if (llvm::sys::Process::FixupStandardFileDescriptors())
326 return 1;
327
Eric Christopher74a7c5d2015-09-25 17:44:31 +0000328 llvm::InitializeAllTargets();
Serge Pavlov4e769842017-08-29 05:22:26 +0000329 auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
Reid Klecknere2d03442015-07-15 22:42:37 +0000330
Rafael Espindola2b098e42015-06-13 12:50:07 +0000331 llvm::BumpPtrAllocator A;
Rafael Espindola817d9622015-08-13 01:07:06 +0000332 llvm::StringSaver Saver(A);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000333
Reid Klecknere2d03442015-07-15 22:42:37 +0000334 // Parse response files using the GNU syntax, unless we're in CL mode. There
335 // are two ways to put clang in CL compatibility mode: argv[0] is either
336 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
337 // command line parsing can't happen until after response file parsing, so we
338 // have to manually search for a --driver-mode=cl argument the hard way.
339 // Finally, our -cc1 tools don't care which tokenization mode we use because
340 // response files written by clang will tokenize the same way in either mode.
Stephen Hinesa978a072016-04-20 00:33:06 +0000341 bool ClangCLMode = false;
Serge Pavlov4e769842017-08-29 05:22:26 +0000342 if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
Fangrui Song75e74e02019-03-31 08:48:19 +0000343 llvm::find_if(argv, [](const char *F) {
Reid Klecknere2d03442015-07-15 22:42:37 +0000344 return F && strcmp(F, "--driver-mode=cl") == 0;
345 }) != argv.end()) {
Stephen Hinesa978a072016-04-20 00:33:06 +0000346 ClangCLMode = true;
Reid Klecknere2d03442015-07-15 22:42:37 +0000347 }
Nico Weber47bf5052016-04-25 21:15:49 +0000348 enum { Default, POSIX, Windows } RSPQuoting = Default;
349 for (const char *F : argv) {
350 if (strcmp(F, "--rsp-quoting=posix") == 0)
351 RSPQuoting = POSIX;
352 else if (strcmp(F, "--rsp-quoting=windows") == 0)
353 RSPQuoting = Windows;
354 }
Reid Klecknere2d03442015-07-15 22:42:37 +0000355
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000356 // Determines whether we want nullptr markers in argv to indicate response
Stephen Hinesa978a072016-04-20 00:33:06 +0000357 // files end-of-lines. We only use this for the /LINK driver argument with
358 // clang-cl.exe on Windows.
Nico Weber47bf5052016-04-25 21:15:49 +0000359 bool MarkEOLs = ClangCLMode;
Stephen Hinesa978a072016-04-20 00:33:06 +0000360
Nico Weber47bf5052016-04-25 21:15:49 +0000361 llvm::cl::TokenizerCallback Tokenizer;
362 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
Stephen Hinesa978a072016-04-20 00:33:06 +0000363 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
Nico Weber47bf5052016-04-25 21:15:49 +0000364 else
365 Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
Stephen Hinesa978a072016-04-20 00:33:06 +0000366
367 if (MarkEOLs && argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000368 MarkEOLs = false;
Reid Klecknere2d03442015-07-15 22:42:37 +0000369 llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000370
371 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
372 // file.
373 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
374 [](const char *A) { return A != nullptr; });
375 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
376 // If -cc1 came from a response file, remove the EOL sentinels.
377 if (MarkEOLs) {
378 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
379 argv.resize(newEnd - argv.begin());
380 }
Sean Silva5d62c262014-08-15 21:40:51 +0000381 return ExecuteCC1Tool(argv, argv[1] + 4);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000382 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000383
Rafael Espindola73d46372009-12-04 19:31:58 +0000384 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000385 for (int i = 1, size = argv.size(); i < size; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000386 // Skip end-of-line response file markers
387 if (argv[i] == nullptr)
388 continue;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000390 CanonicalPrefixes = false;
391 break;
392 }
393 }
394
David Majnemer3a4f9582015-08-10 18:16:32 +0000395 // Handle CL and _CL_ which permits additional command line options to be
396 // prepended or appended.
Pierre Gousseau209b6e22016-09-06 10:48:27 +0000397 if (ClangCLMode) {
David Majnemer3a4f9582015-08-10 18:16:32 +0000398 // Arguments in "CL" are prepended.
399 llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
400 if (OptCL.hasValue()) {
401 SmallVector<const char *, 8> PrependedOpts;
402 getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
403
404 // Insert right after the program name to prepend to the argument list.
405 argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
406 }
407 // Arguments in "_CL_" are appended.
408 llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
409 if (Opt_CL_.hasValue()) {
410 SmallVector<const char *, 8> AppendedOpts;
411 getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
412
413 // Insert at the end of the argument list to append.
414 argv.append(AppendedOpts.begin(), AppendedOpts.end());
415 }
416 }
417
Rafael Espindola2b098e42015-06-13 12:50:07 +0000418 std::set<std::string> SavedStrings;
Bob Wilsona19fad72014-01-15 01:41:52 +0000419 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
Bob Wilson39265b92014-02-23 00:11:56 +0000420 // scenes.
Bob Wilsona19fad72014-01-15 01:41:52 +0000421 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
Chad Rosier3e263e42013-02-21 18:56:55 +0000422 // FIXME: Driver shouldn't take extra initial argument.
423 ApplyQAOverride(argv, OverrideStr, SavedStrings);
Chad Rosier3e263e42013-02-21 18:56:55 +0000424 }
425
Rafael Espindola9678d272013-06-26 05:03:40 +0000426 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000427
Sean Silva22b4a342014-08-15 18:58:12 +0000428 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
429 CreateAndPopulateDiagOpts(argv);
430
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000431 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000432 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Sean Silva965bb992014-08-15 18:58:09 +0000433 FixupDiagPrefixExeName(DiagClient, Path);
Reid Klecknerdc74af12013-09-04 01:37:22 +0000434
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000435 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000436
Douglas Gregor811db4e2012-10-23 22:26:28 +0000437 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000438
439 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
440 auto SerializedConsumer =
441 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
442 &*DiagOpts, /*MergeChildRecords=*/true);
443 Diags.setClient(new ChainedDiagnosticConsumer(
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000444 Diags.takeClient(), std::move(SerializedConsumer)));
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000445 }
446
Chad Rosier5f15a352013-01-15 01:21:53 +0000447 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000448
Alp Toker1761f112014-05-15 22:26:36 +0000449 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000450 SetInstallDir(argv, TheDriver, CanonicalPrefixes);
Serge Pavlov4e769842017-08-29 05:22:26 +0000451 TheDriver.setTargetAndMode(TargetAndMode);
Daniel Dunbar88979912010-08-01 22:29:51 +0000452
Serge Pavlov4e769842017-08-29 05:22:26 +0000453 insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000454
Sean Silva0ee846f2014-08-15 20:59:03 +0000455 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000456
Ahmed Charlesb8984322014-03-07 20:03:18 +0000457 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
Serge Pavlovb43573b2017-05-24 14:57:17 +0000458 int Res = 1;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000459 if (C && !C->containsError()) {
Serge Pavlovb43573b2017-05-24 14:57:17 +0000460 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Chad Rosierdd60e092013-01-29 20:15:05 +0000461 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000462
Serge Pavlovb43573b2017-05-24 14:57:17 +0000463 // Force a crash to test the diagnostics.
464 if (TheDriver.GenReproducer) {
465 Diags.Report(diag::err_drv_force_crash)
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000466 << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
Justin Bognere1a33d12014-10-20 21:02:05 +0000467
Serge Pavlovb43573b2017-05-24 14:57:17 +0000468 // 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 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000474
Serge Pavlovb43573b2017-05-24 14:57:17 +0000475 for (const auto &P : FailingCommands) {
476 int CommandRes = P.first;
477 const Command *FailingCommand = P.second;
478 if (!Res)
479 Res = CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +0000480
Serge Pavlovb43573b2017-05-24 14:57:17 +0000481 // 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;
Nico Weber1865df42018-04-27 19:11:14 +0000486#ifdef _WIN32
Serge Pavlovb43573b2017-05-24 14:57:17 +0000487 DiagnoseCrash |= CommandRes == 3;
Reid Kleckner3b5c6392014-07-07 20:23:27 +0000488#endif
Serge Pavlovb43573b2017-05-24 14:57:17 +0000489 if (DiagnoseCrash) {
490 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
491 break;
492 }
Chad Rosierdd60e092013-01-29 20:15:05 +0000493 }
494 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000495
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000496 Diags.getClient()->finish();
497
Chris Lattner09f8cc82010-03-30 05:39:52 +0000498 // If any timers were active but haven't been destroyed yet, print their
499 // results now. This happens in -disable-free mode.
500 llvm::TimerGroup::printAll(llvm::errs());
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000501
Nico Weber1865df42018-04-27 19:11:14 +0000502#ifdef _WIN32
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000503 // Exit status should not be negative on Win32, unless abnormal termination.
504 // Once abnormal termiation was caught, negative status should not be
505 // propagated.
506 if (Res < 0)
507 Res = 1;
508#endif
509
Chad Rosierdd60e092013-01-29 20:15:05 +0000510 // If we have multiple failing commands, we return the result of the first
511 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000512 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000513}