blob: 40c5a6198a85cc5bc80082f097d6f6cfc48ecb6e [file] [log] [blame]
Daniel Dunbar544ecd12009-03-02 19:59:07 +00001//===-- 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//
Daniel Dunbarb2da9332009-03-03 05:55:11 +000010// This is the entry point to the clang driver; it is a thin wrapper
11// for functionality in the Driver clang library.
Daniel Dunbar544ecd12009-03-02 19:59:07 +000012//
13//===----------------------------------------------------------------------===//
14
Jordan Rosea7d03842013-02-08 22:30:41 +000015#include "clang/Basic/CharInfo.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000016#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbar544ecd12009-03-02 19:59:07 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
Richard Smith940a6d72012-12-25 21:56:27 +000019#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000020#include "clang/Driver/Options.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000021#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000022#include "clang/Frontend/CompilerInvocation.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000023#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar12ee3802010-02-25 03:23:43 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Chad Rosierd6f716a2012-03-13 20:09:56 +000025#include "clang/Frontend/Utils.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000026#include "llvm/ADT/ArrayRef.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000027#include "llvm/ADT/STLExtras.h"
Daniel Dunbard9b80c22009-03-18 02:11:26 +000028#include "llvm/ADT/SmallString.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000029#include "llvm/ADT/SmallVector.h"
Alp Toker1d257e12014-06-04 03:28:55 +000030#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000031#include "llvm/Option/ArgList.h"
32#include "llvm/Option/OptTable.h"
33#include "llvm/Option/Option.h"
Reid Kleckner61b23b72013-07-18 20:00:53 +000034#include "llvm/Support/CommandLine.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000035#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000036#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000037#include "llvm/Support/Host.h"
Daniel Dunbar2608c542009-03-18 01:38:48 +000038#include "llvm/Support/ManagedStatic.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Path.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000041#include "llvm/Support/PrettyStackTrace.h"
David Majnemer3f8f8c92013-10-07 07:33:27 +000042#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000044#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000045#include "llvm/Support/Signals.h"
Rafael Espindola2b098e42015-06-13 12:50:07 +000046#include "llvm/Support/StringSaver.h"
Evan Cheng494eb062011-08-24 18:09:14 +000047#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000049#include "llvm/Support/Timer.h"
50#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000051#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000052#include <system_error>
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000053using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000054using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000055using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000056
Rafael Espindola9678d272013-06-26 05:03:40 +000057std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000058 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000059 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000060
Daniel Dunbarda382a82009-03-18 20:25:53 +000061 // 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;
Rafael Espindola9678d272013-06-26 05:03:40 +000064 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000065}
66
Sean Silva6a9b0f92014-08-15 19:23:53 +000067static const char *GetStableCStr(std::set<std::string> &SavedStrings,
68 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000069 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///
Daniel Dunbar54091b82009-07-16 21:32:51 +000078/// '#': Silence information about the changes to the command line arguments.
79///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000080/// '^': 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///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000084/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
85/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000086///
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.
Daniel Dunbar54091b82009-07-16 21:32:51 +000094///
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.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000099static void ApplyOneQAOverride(raw_ostream &OS,
100 SmallVectorImpl<const char*> &Args,
101 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000102 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000103 // This does not need to be efficient.
104
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000105 if (Edit[0] == '^') {
106 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000107 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000108 OS << "### Adding argument " << Str << " at beginning\n";
109 Args.insert(Args.begin() + 1, Str);
110 } else if (Edit[0] == '+') {
111 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000112 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000113 OS << "### Adding argument " << Str << " at end\n";
114 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000115 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 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;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000119 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
120
121 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000122 // Ignore end-of-line response file markers
123 if (Args[i] == nullptr)
124 continue;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000125 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
126
127 if (Repl != Args[i]) {
128 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000129 Args[i] = GetStableCStr(SavedStrings, Repl);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000130 }
131 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000132 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
133 std::string Option = Edit.substr(1, std::string::npos);
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];
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000151 // Ignore end-of-line response file markers
152 if (A == nullptr)
153 continue;
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000154 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";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000164 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000165 } else {
166 OS << "### Unrecognized edit: " << Edit << "\n";
167 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000168}
169
170/// ApplyQAOverride - Apply a comma separate list of edits to the
171/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000172static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000173 const char *OverrideStr,
174 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000175 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000176
Daniel Dunbar54091b82009-07-16 21:32:51 +0000177 if (OverrideStr[0] == '#') {
178 ++OverrideStr;
179 OS = &llvm::nulls();
180 }
181
Bob Wilsona19fad72014-01-15 01:41:52 +0000182 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000183
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)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000192 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000193 S = End;
194 if (*S != '\0')
195 ++S;
196 }
197}
198
Sean Silva070cd2d2014-08-15 21:38:36 +0000199extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
200 void *MainAddr);
201extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
202 void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000203
Hans Wennborg1a27e042014-10-17 17:07:59 +0000204struct DriverSuffix {
205 const char *Suffix;
206 const char *ModeFlag;
207};
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000208
Hans Wennborg1a27e042014-10-17 17:07:59 +0000209static const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
210 // A list of known driver suffixes. Suffixes are compared against the
211 // program name in order. If there is a match, the frontend type if updated as
212 // necessary by applying the ModeFlag.
213 static const DriverSuffix DriverSuffixes[] = {
214 {"clang", nullptr},
215 {"clang++", "--driver-mode=g++"},
216 {"clang-c++", "--driver-mode=g++"},
217 {"clang-cc", nullptr},
218 {"clang-cpp", "--driver-mode=cpp"},
219 {"clang-g++", "--driver-mode=g++"},
220 {"clang-gcc", nullptr},
221 {"clang-cl", "--driver-mode=cl"},
222 {"cc", nullptr},
223 {"cpp", "--driver-mode=cpp"},
224 {"cl", "--driver-mode=cl"},
225 {"++", "--driver-mode=g++"},
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000226 };
Hans Wennborg1a27e042014-10-17 17:07:59 +0000227
228 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
229 if (ProgName.endswith(DriverSuffixes[i].Suffix))
230 return &DriverSuffixes[i];
231 return nullptr;
232}
233
Reid Klecknere2d03442015-07-15 22:42:37 +0000234/// Normalize the program name from argv[0] by stripping the file extension if
235/// present and lower-casing the string on Windows.
236static std::string normalizeProgramName(const char *Argv0) {
237 std::string ProgName = llvm::sys::path::stem(Argv0);
238#ifdef LLVM_ON_WIN32
239 // Transform to lowercase for case insensitive file systems.
240 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
241#endif
242 return ProgName;
243}
244
245static const DriverSuffix *parseDriverSuffix(StringRef ProgName) {
Hans Wennborg1a27e042014-10-17 17:07:59 +0000246 // Try to infer frontend type and default target from the program name by
247 // comparing it against DriverSuffixes in order.
248
249 // If there is a match, the function tries to identify a target as prefix.
250 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
251 // prefix "x86_64-linux". If such a target prefix is found, is gets added via
252 // -target as implicit first argument.
Reid Klecknere2d03442015-07-15 22:42:37 +0000253 const DriverSuffix *DS = FindDriverSuffix(ProgName);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000254
Hans Wennborg1a27e042014-10-17 17:07:59 +0000255 if (!DS) {
256 // Try again after stripping any trailing version number:
257 // clang++3.5 -> clang++
Reid Klecknere2d03442015-07-15 22:42:37 +0000258 ProgName = ProgName.rtrim("0123456789.");
259 DS = FindDriverSuffix(ProgName);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000260 }
261
Hans Wennborg1a27e042014-10-17 17:07:59 +0000262 if (!DS) {
263 // Try again after stripping trailing -component.
264 // clang++-tot -> clang++
Reid Klecknere2d03442015-07-15 22:42:37 +0000265 ProgName = ProgName.slice(0, ProgName.rfind('-'));
266 DS = FindDriverSuffix(ProgName);
267 }
268 return DS;
269}
270
271static void insertArgsFromProgramName(StringRef ProgName,
272 const DriverSuffix *DS,
273 SmallVectorImpl<const char *> &ArgVector,
274 std::set<std::string> &SavedStrings) {
275 if (!DS)
276 return;
277
278 if (const char *Flag = DS->ModeFlag) {
279 // Add Flag to the arguments.
280 auto it = ArgVector.begin();
281 if (it != ArgVector.end())
282 ++it;
283 ArgVector.insert(it, Flag);
Hans Wennborg1a27e042014-10-17 17:07:59 +0000284 }
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000285
Reid Klecknere2d03442015-07-15 22:42:37 +0000286 StringRef::size_type LastComponent = ProgName.rfind(
287 '-', ProgName.size() - strlen(DS->Suffix));
288 if (LastComponent == StringRef::npos)
289 return;
Hans Wennborg1a27e042014-10-17 17:07:59 +0000290
Reid Klecknere2d03442015-07-15 22:42:37 +0000291 // Infer target from the prefix.
292 StringRef Prefix = ProgName.slice(0, LastComponent);
293 std::string IgnoredError;
294 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
295 auto it = ArgVector.begin();
296 if (it != ArgVector.end())
297 ++it;
298 const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) };
299 ArgVector.insert(it, std::begin(arr), std::end(arr));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000300 }
301}
302
Sean Silva0ee846f2014-08-15 20:59:03 +0000303static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
Sean Silva2103c382014-08-15 18:50:00 +0000304 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
305 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
306 if (TheDriver.CCPrintOptions)
307 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
308
309 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
310 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
311 if (TheDriver.CCPrintHeaders)
312 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
313
314 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
315 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
316 if (TheDriver.CCLogDiagnostics)
317 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
318}
319
Sean Silva965bb992014-08-15 18:58:09 +0000320static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
321 const std::string &Path) {
322 // If the clang binary happens to be named cl.exe for compatibility reasons,
323 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
324 StringRef ExeBasename(llvm::sys::path::filename(Path));
325 if (ExeBasename.equals_lower("cl.exe"))
326 ExeBasename = "clang-cl.exe";
327 DiagClient->setPrefix(ExeBasename);
328}
329
Sean Silva22b4a342014-08-15 18:58:12 +0000330// This lets us create the DiagnosticsEngine with a properly-filled-out
331// DiagnosticOptions instance.
332static DiagnosticOptions *
David Blaikie6d492ad2015-06-21 06:32:36 +0000333CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
Sean Silva22b4a342014-08-15 18:58:12 +0000334 auto *DiagOpts = new DiagnosticOptions;
335 std::unique_ptr<OptTable> Opts(createDriverOptTable());
336 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000337 InputArgList Args =
338 Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
Sean Silva22b4a342014-08-15 18:58:12 +0000339 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
340 // Any errors that would be diagnosed here will also be diagnosed later,
341 // when the DiagnosticsEngine actually exists.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000342 (void)ParseDiagnosticArgs(*DiagOpts, Args);
Sean Silva22b4a342014-08-15 18:58:12 +0000343 return DiagOpts;
344}
345
Sean Silvab5060472014-08-15 18:58:15 +0000346static void SetInstallDir(SmallVectorImpl<const char *> &argv,
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000347 Driver &TheDriver, bool CanonicalPrefixes) {
Sean Silvab5060472014-08-15 18:58:15 +0000348 // Attempt to find the original path used to invoke the driver, to determine
349 // the installed path. We do this manually, because we want to support that
350 // path being a symlink.
351 SmallString<128> InstalledPath(argv[0]);
352
353 // Do a PATH lookup, if there are no directory components.
Michael J. Spencerb011d482014-11-07 21:30:32 +0000354 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
355 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
356 llvm::sys::path::filename(InstalledPath.str())))
Michael J. Spencer04162ea2014-11-04 01:30:55 +0000357 InstalledPath = *Tmp;
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000358
359 // FIXME: We don't actually canonicalize this, we just make it absolute.
360 if (CanonicalPrefixes)
361 llvm::sys::fs::make_absolute(InstalledPath);
362
Sean Silvab5060472014-08-15 18:58:15 +0000363 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
Rafael Espindola611505f2014-09-11 18:10:13 +0000364 if (llvm::sys::fs::exists(InstalledPath.c_str()))
Sean Silvab5060472014-08-15 18:58:15 +0000365 TheDriver.setInstalledDir(InstalledPath);
366}
367
Sean Silva5d62c262014-08-15 21:40:51 +0000368static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
Sean Silva070cd2d2014-08-15 21:38:36 +0000369 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000370 if (Tool == "")
Sean Silva070cd2d2014-08-15 21:38:36 +0000371 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000372 if (Tool == "as")
Sean Silva070cd2d2014-08-15 21:38:36 +0000373 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000374
375 // Reject unknown tools.
376 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
377 return 1;
378}
379
Rafael Espindola77a067a2010-07-19 15:20:12 +0000380int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000381 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000382 llvm::PrettyStackTraceProgram X(argc_, argv_);
383
David Majnemer33498722014-10-06 23:52:23 +0000384 if (llvm::sys::Process::FixupStandardFileDescriptors())
385 return 1;
386
David Majnemer3f8f8c92013-10-07 07:33:27 +0000387 SmallVector<const char *, 256> argv;
388 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
Rafael Espindolac0809172014-06-12 14:02:15 +0000389 std::error_code EC = llvm::sys::Process::GetArgumentVector(
Craig Topper8c2a2a02014-08-30 16:55:39 +0000390 argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
David Majnemer3f8f8c92013-10-07 07:33:27 +0000391 if (EC) {
392 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
393 return 1;
394 }
395
Reid Klecknere2d03442015-07-15 22:42:37 +0000396 std::string ProgName = normalizeProgramName(argv[0]);
397 const DriverSuffix *DS = parseDriverSuffix(ProgName);
398
Rafael Espindola2b098e42015-06-13 12:50:07 +0000399 llvm::BumpPtrAllocator A;
400 llvm::BumpPtrStringSaver Saver(A);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000401
Reid Klecknere2d03442015-07-15 22:42:37 +0000402 // Parse response files using the GNU syntax, unless we're in CL mode. There
403 // are two ways to put clang in CL compatibility mode: argv[0] is either
404 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
405 // command line parsing can't happen until after response file parsing, so we
406 // have to manually search for a --driver-mode=cl argument the hard way.
407 // Finally, our -cc1 tools don't care which tokenization mode we use because
408 // response files written by clang will tokenize the same way in either mode.
409 llvm::cl::TokenizerCallback Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
410 if ((DS && DS->ModeFlag && strcmp(DS->ModeFlag, "--driver-mode=cl") == 0) ||
411 std::find_if(argv.begin(), argv.end(), [](const char *F) {
412 return F && strcmp(F, "--driver-mode=cl") == 0;
413 }) != argv.end()) {
414 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
415 }
416
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000417 // Determines whether we want nullptr markers in argv to indicate response
418 // files end-of-lines. We only use this for the /LINK driver argument.
419 bool MarkEOLs = true;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000420 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000421 MarkEOLs = false;
Reid Klecknere2d03442015-07-15 22:42:37 +0000422 llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000423
424 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
425 // file.
426 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
427 [](const char *A) { return A != nullptr; });
428 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
429 // If -cc1 came from a response file, remove the EOL sentinels.
430 if (MarkEOLs) {
431 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
432 argv.resize(newEnd - argv.begin());
433 }
Sean Silva5d62c262014-08-15 21:40:51 +0000434 return ExecuteCC1Tool(argv, argv[1] + 4);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000435 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000436
Rafael Espindola73d46372009-12-04 19:31:58 +0000437 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000438 for (int i = 1, size = argv.size(); i < size; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000439 // Skip end-of-line response file markers
440 if (argv[i] == nullptr)
441 continue;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000442 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000443 CanonicalPrefixes = false;
444 break;
445 }
446 }
447
Rafael Espindola2b098e42015-06-13 12:50:07 +0000448 std::set<std::string> SavedStrings;
Bob Wilsona19fad72014-01-15 01:41:52 +0000449 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
Bob Wilson39265b92014-02-23 00:11:56 +0000450 // scenes.
Bob Wilsona19fad72014-01-15 01:41:52 +0000451 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
Chad Rosier3e263e42013-02-21 18:56:55 +0000452 // FIXME: Driver shouldn't take extra initial argument.
453 ApplyQAOverride(argv, OverrideStr, SavedStrings);
Chad Rosier3e263e42013-02-21 18:56:55 +0000454 }
455
Rafael Espindola9678d272013-06-26 05:03:40 +0000456 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000457
Sean Silva22b4a342014-08-15 18:58:12 +0000458 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
459 CreateAndPopulateDiagOpts(argv);
460
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000461 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000462 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Sean Silva965bb992014-08-15 18:58:09 +0000463 FixupDiagPrefixExeName(DiagClient, Path);
Reid Klecknerdc74af12013-09-04 01:37:22 +0000464
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000465 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000466
Douglas Gregor811db4e2012-10-23 22:26:28 +0000467 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000468
469 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
470 auto SerializedConsumer =
471 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
472 &*DiagOpts, /*MergeChildRecords=*/true);
473 Diags.setClient(new ChainedDiagnosticConsumer(
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000474 Diags.takeClient(), std::move(SerializedConsumer)));
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000475 }
476
Chad Rosier5f15a352013-01-15 01:21:53 +0000477 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000478
Alp Toker1761f112014-05-15 22:26:36 +0000479 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000480 SetInstallDir(argv, TheDriver, CanonicalPrefixes);
Daniel Dunbar88979912010-08-01 22:29:51 +0000481
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000482 llvm::InitializeAllTargets();
Reid Klecknere2d03442015-07-15 22:42:37 +0000483 insertArgsFromProgramName(ProgName, DS, argv, SavedStrings);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000484
Sean Silva0ee846f2014-08-15 20:59:03 +0000485 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000486
Ahmed Charlesb8984322014-03-07 20:03:18 +0000487 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000488 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000489 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000490 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000491 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000492
Chad Rosier681e4b82012-04-20 17:08:59 +0000493 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000494 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
495 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Justin Bognere1a33d12014-10-20 21:02:05 +0000496
497 // Pretend that every command failed.
498 FailingCommands.clear();
499 for (const auto &J : C->getJobs())
500 if (const Command *C = dyn_cast<Command>(&J))
501 FailingCommands.push_back(std::make_pair(-1, C));
Richard Smith940a6d72012-12-25 21:56:27 +0000502 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000503
Sean Silvabbabefe2014-08-15 19:23:50 +0000504 for (const auto &P : FailingCommands) {
505 int CommandRes = P.first;
506 const Command *FailingCommand = P.second;
Chad Rosierdd60e092013-01-29 20:15:05 +0000507 if (!Res)
508 Res = CommandRes;
509
510 // If result status is < 0, then the driver command signalled an error.
511 // If result status is 70, then the driver command reported a fatal error.
Reid Kleckner3b5c6392014-07-07 20:23:27 +0000512 // On Windows, abort will return an exit code of 3. In these cases,
513 // generate additional diagnostic information if possible.
514 bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
515#ifdef LLVM_ON_WIN32
516 DiagnoseCrash |= CommandRes == 3;
517#endif
518 if (DiagnoseCrash) {
Justin Bognere1a33d12014-10-20 21:02:05 +0000519 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000520 break;
521 }
522 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000523
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000524 Diags.getClient()->finish();
525
Chris Lattner09f8cc82010-03-30 05:39:52 +0000526 // If any timers were active but haven't been destroyed yet, print their
527 // results now. This happens in -disable-free mode.
528 llvm::TimerGroup::printAll(llvm::errs());
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000529
Daniel Dunbar2608c542009-03-18 01:38:48 +0000530 llvm::llvm_shutdown();
531
Hans Wennborg501eadb2014-03-12 16:07:46 +0000532#ifdef LLVM_ON_WIN32
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000533 // Exit status should not be negative on Win32, unless abnormal termination.
534 // Once abnormal termiation was caught, negative status should not be
535 // propagated.
536 if (Res < 0)
537 Res = 1;
538#endif
539
Chad Rosierdd60e092013-01-29 20:15:05 +0000540 // If we have multiple failing commands, we return the result of the first
541 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000542 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000543}