blob: 57db0261a7b4489d0b35aa0c55da82c30d048cf4 [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"
Chad Rosierd6f716a2012-03-13 20:09:56 +000021#include "clang/Frontend/CompilerInvocation.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000022#include "clang/Frontend/ChainedDiagnosticConsumer.h"
23#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"
Evan Cheng494eb062011-08-24 18:09:14 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000048#include "llvm/Support/Timer.h"
49#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000050#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000051#include <system_error>
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000052using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000053using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000054using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000055
Rafael Espindola9678d272013-06-26 05:03:40 +000056std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000057 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000058 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000059
Daniel Dunbarda382a82009-03-18 20:25:53 +000060 // This just needs to be some symbol in the binary; C++ doesn't
61 // allow taking the address of ::main however.
62 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000063 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000064}
65
Sean Silva6a9b0f92014-08-15 19:23:53 +000066static const char *GetStableCStr(std::set<std::string> &SavedStrings,
67 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000068 return SavedStrings.insert(S).first->c_str();
69}
70
71/// ApplyQAOverride - Apply a list of edits to the input argument lists.
72///
73/// The input string is a space separate list of edits to perform,
74/// they are applied in order to the input argument lists. Edits
75/// should be one of the following forms:
76///
Daniel Dunbar54091b82009-07-16 21:32:51 +000077/// '#': Silence information about the changes to the command line arguments.
78///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000079/// '^': Add FOO as a new argument at the beginning of the command line.
80///
81/// '+': Add FOO as a new argument at the end of the command line.
82///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000083/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
84/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000085///
86/// 'xOPTION': Removes all instances of the literal argument OPTION.
87///
88/// 'XOPTION': Removes all instances of the literal argument OPTION,
89/// and the following argument.
90///
91/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
92/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000093///
94/// \param OS - The stream to write edit information to.
95/// \param Args - The vector of command line arguments.
96/// \param Edit - The override command to perform.
97/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000098static void ApplyOneQAOverride(raw_ostream &OS,
99 SmallVectorImpl<const char*> &Args,
100 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000101 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000102 // This does not need to be efficient.
103
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000104 if (Edit[0] == '^') {
105 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000106 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000107 OS << "### Adding argument " << Str << " at beginning\n";
108 Args.insert(Args.begin() + 1, Str);
109 } else if (Edit[0] == '+') {
110 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000111 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000112 OS << "### Adding argument " << Str << " at end\n";
113 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000114 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000115 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
116 StringRef MatchPattern = Edit.substr(2).split('/').first;
117 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000118 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
119
120 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000121 // Ignore end-of-line response file markers
122 if (Args[i] == nullptr)
123 continue;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000124 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
125
126 if (Repl != Args[i]) {
127 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000128 Args[i] = GetStableCStr(SavedStrings, Repl);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000129 }
130 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000131 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
132 std::string Option = Edit.substr(1, std::string::npos);
133 for (unsigned i = 1; i < Args.size();) {
134 if (Option == Args[i]) {
135 OS << "### Deleting argument " << Args[i] << '\n';
136 Args.erase(Args.begin() + i);
137 if (Edit[0] == 'X') {
138 if (i < Args.size()) {
139 OS << "### Deleting argument " << Args[i] << '\n';
140 Args.erase(Args.begin() + i);
141 } else
142 OS << "### Invalid X edit, end of command line!\n";
143 }
144 } else
145 ++i;
146 }
147 } else if (Edit[0] == 'O') {
148 for (unsigned i = 1; i < Args.size();) {
149 const char *A = Args[i];
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000150 // Ignore end-of-line response file markers
151 if (A == nullptr)
152 continue;
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000153 if (A[0] == '-' && A[1] == 'O' &&
154 (A[2] == '\0' ||
155 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
156 ('0' <= A[2] && A[2] <= '9'))))) {
157 OS << "### Deleting argument " << Args[i] << '\n';
158 Args.erase(Args.begin() + i);
159 } else
160 ++i;
161 }
162 OS << "### Adding argument " << Edit << " at end\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000163 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000164 } else {
165 OS << "### Unrecognized edit: " << Edit << "\n";
166 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000167}
168
169/// ApplyQAOverride - Apply a comma separate list of edits to the
170/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000171static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000172 const char *OverrideStr,
173 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000174 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000175
Daniel Dunbar54091b82009-07-16 21:32:51 +0000176 if (OverrideStr[0] == '#') {
177 ++OverrideStr;
178 OS = &llvm::nulls();
179 }
180
Bob Wilsona19fad72014-01-15 01:41:52 +0000181 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000182
183 // This does not need to be efficient.
184
185 const char *S = OverrideStr;
186 while (*S) {
187 const char *End = ::strchr(S, ' ');
188 if (!End)
189 End = S + strlen(S);
190 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000191 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000192 S = End;
193 if (*S != '\0')
194 ++S;
195 }
196}
197
Sean Silva070cd2d2014-08-15 21:38:36 +0000198extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
199 void *MainAddr);
200extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
201 void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000202
Hans Wennborg1a27e042014-10-17 17:07:59 +0000203struct DriverSuffix {
204 const char *Suffix;
205 const char *ModeFlag;
206};
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000207
Hans Wennborg1a27e042014-10-17 17:07:59 +0000208static const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
209 // A list of known driver suffixes. Suffixes are compared against the
210 // program name in order. If there is a match, the frontend type if updated as
211 // necessary by applying the ModeFlag.
212 static const DriverSuffix DriverSuffixes[] = {
213 {"clang", nullptr},
214 {"clang++", "--driver-mode=g++"},
215 {"clang-c++", "--driver-mode=g++"},
216 {"clang-cc", nullptr},
217 {"clang-cpp", "--driver-mode=cpp"},
218 {"clang-g++", "--driver-mode=g++"},
219 {"clang-gcc", nullptr},
220 {"clang-cl", "--driver-mode=cl"},
221 {"cc", nullptr},
222 {"cpp", "--driver-mode=cpp"},
223 {"cl", "--driver-mode=cl"},
224 {"++", "--driver-mode=g++"},
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000225 };
Hans Wennborg1a27e042014-10-17 17:07:59 +0000226
227 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
228 if (ProgName.endswith(DriverSuffixes[i].Suffix))
229 return &DriverSuffixes[i];
230 return nullptr;
231}
232
233static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
234 std::set<std::string> &SavedStrings) {
235 // Try to infer frontend type and default target from the program name by
236 // comparing it against DriverSuffixes in order.
237
238 // If there is a match, the function tries to identify a target as prefix.
239 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
240 // prefix "x86_64-linux". If such a target prefix is found, is gets added via
241 // -target as implicit first argument.
242
243 std::string ProgName =llvm::sys::path::stem(ArgVector[0]);
Hans Wennborg501eadb2014-03-12 16:07:46 +0000244#ifdef LLVM_ON_WIN32
Hans Wennborgae1c5a82014-03-11 23:42:29 +0000245 // Transform to lowercase for case insensitive file systems.
Hans Wennborg1a27e042014-10-17 17:07:59 +0000246 ProgName = StringRef(ProgName).lower();
Hans Wennborgae1c5a82014-03-11 23:42:29 +0000247#endif
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000248
Hans Wennborg1a27e042014-10-17 17:07:59 +0000249 StringRef ProgNameRef = ProgName;
250 const DriverSuffix *DS = FindDriverSuffix(ProgNameRef);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000251
Hans Wennborg1a27e042014-10-17 17:07:59 +0000252 if (!DS) {
253 // Try again after stripping any trailing version number:
254 // clang++3.5 -> clang++
255 ProgNameRef = ProgNameRef.rtrim("0123456789.");
256 DS = FindDriverSuffix(ProgNameRef);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000257 }
258
Hans Wennborg1a27e042014-10-17 17:07:59 +0000259 if (!DS) {
260 // Try again after stripping trailing -component.
261 // clang++-tot -> clang++
262 ProgNameRef = ProgNameRef.slice(0, ProgNameRef.rfind('-'));
263 DS = FindDriverSuffix(ProgNameRef);
264 }
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000265
Hans Wennborg1a27e042014-10-17 17:07:59 +0000266 if (DS) {
267 if (const char *Flag = DS->ModeFlag) {
268 // Add Flag to the arguments.
269 auto it = ArgVector.begin();
270 if (it != ArgVector.end())
271 ++it;
272 ArgVector.insert(it, Flag);
273 }
274
275 StringRef::size_type LastComponent = ProgNameRef.rfind(
276 '-', ProgNameRef.size() - strlen(DS->Suffix));
277 if (LastComponent == StringRef::npos)
278 return;
279
280 // Infer target from the prefix.
281 StringRef Prefix = ProgNameRef.slice(0, LastComponent);
282 std::string IgnoredError;
283 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
284 auto it = ArgVector.begin();
285 if (it != ArgVector.end())
286 ++it;
287 const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) };
288 ArgVector.insert(it, std::begin(arr), std::end(arr));
289 }
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000290 }
291}
292
Sean Silvabcd500e2014-08-15 23:39:12 +0000293namespace {
294 class StringSetSaver : public llvm::cl::StringSaver {
295 public:
296 StringSetSaver(std::set<std::string> &Storage) : Storage(Storage) {}
297 const char *SaveString(const char *Str) override {
298 return GetStableCStr(Storage, Str);
299 }
300 private:
301 std::set<std::string> &Storage;
302 };
303}
304
Sean Silva0ee846f2014-08-15 20:59:03 +0000305static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
Sean Silva2103c382014-08-15 18:50:00 +0000306 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
307 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
308 if (TheDriver.CCPrintOptions)
309 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
310
311 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
312 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
313 if (TheDriver.CCPrintHeaders)
314 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
315
316 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
317 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
318 if (TheDriver.CCLogDiagnostics)
319 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
320}
321
Sean Silva965bb992014-08-15 18:58:09 +0000322static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
323 const std::string &Path) {
324 // If the clang binary happens to be named cl.exe for compatibility reasons,
325 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
326 StringRef ExeBasename(llvm::sys::path::filename(Path));
327 if (ExeBasename.equals_lower("cl.exe"))
328 ExeBasename = "clang-cl.exe";
329 DiagClient->setPrefix(ExeBasename);
330}
331
Sean Silva22b4a342014-08-15 18:58:12 +0000332// This lets us create the DiagnosticsEngine with a properly-filled-out
333// DiagnosticOptions instance.
334static DiagnosticOptions *
335CreateAndPopulateDiagOpts(SmallVectorImpl<const char *> &argv) {
336 auto *DiagOpts = new DiagnosticOptions;
337 std::unique_ptr<OptTable> Opts(createDriverOptTable());
338 unsigned MissingArgIndex, MissingArgCount;
339 std::unique_ptr<InputArgList> Args(Opts->ParseArgs(
340 argv.begin() + 1, argv.end(), MissingArgIndex, MissingArgCount));
341 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
342 // Any errors that would be diagnosed here will also be diagnosed later,
343 // when the DiagnosticsEngine actually exists.
344 (void) ParseDiagnosticArgs(*DiagOpts, *Args);
345 return DiagOpts;
346}
347
Sean Silvab5060472014-08-15 18:58:15 +0000348static void SetInstallDir(SmallVectorImpl<const char *> &argv,
349 Driver &TheDriver) {
350 // Attempt to find the original path used to invoke the driver, to determine
351 // the installed path. We do this manually, because we want to support that
352 // path being a symlink.
353 SmallString<128> InstalledPath(argv[0]);
354
355 // Do a PATH lookup, if there are no directory components.
Michael J. Spencerb011d482014-11-07 21:30:32 +0000356 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
357 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
358 llvm::sys::path::filename(InstalledPath.str())))
Michael J. Spencer04162ea2014-11-04 01:30:55 +0000359 InstalledPath = *Tmp;
Sean Silvab5060472014-08-15 18:58:15 +0000360 llvm::sys::fs::make_absolute(InstalledPath);
361 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
Rafael Espindola611505f2014-09-11 18:10:13 +0000362 if (llvm::sys::fs::exists(InstalledPath.c_str()))
Sean Silvab5060472014-08-15 18:58:15 +0000363 TheDriver.setInstalledDir(InstalledPath);
364}
365
Sean Silva5d62c262014-08-15 21:40:51 +0000366static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
Sean Silva070cd2d2014-08-15 21:38:36 +0000367 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000368 if (Tool == "")
Sean Silva070cd2d2014-08-15 21:38:36 +0000369 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000370 if (Tool == "as")
Sean Silva070cd2d2014-08-15 21:38:36 +0000371 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000372
373 // Reject unknown tools.
374 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
375 return 1;
376}
377
Rafael Espindola77a067a2010-07-19 15:20:12 +0000378int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000379 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000380 llvm::PrettyStackTraceProgram X(argc_, argv_);
381
David Majnemer33498722014-10-06 23:52:23 +0000382 if (llvm::sys::Process::FixupStandardFileDescriptors())
383 return 1;
384
David Majnemer3f8f8c92013-10-07 07:33:27 +0000385 SmallVector<const char *, 256> argv;
386 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
Rafael Espindolac0809172014-06-12 14:02:15 +0000387 std::error_code EC = llvm::sys::Process::GetArgumentVector(
Craig Topper8c2a2a02014-08-30 16:55:39 +0000388 argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
David Majnemer3f8f8c92013-10-07 07:33:27 +0000389 if (EC) {
390 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
391 return 1;
392 }
393
Rafael Espindola77a067a2010-07-19 15:20:12 +0000394 std::set<std::string> SavedStrings;
Sean Silvabcd500e2014-08-15 23:39:12 +0000395 StringSetSaver Saver(SavedStrings);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000396
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000397 // Determines whether we want nullptr markers in argv to indicate response
398 // files end-of-lines. We only use this for the /LINK driver argument.
399 bool MarkEOLs = true;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000400 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000401 MarkEOLs = false;
402 llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, argv,
403 MarkEOLs);
404
405 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
406 // file.
407 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
408 [](const char *A) { return A != nullptr; });
409 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
410 // If -cc1 came from a response file, remove the EOL sentinels.
411 if (MarkEOLs) {
412 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
413 argv.resize(newEnd - argv.begin());
414 }
Sean Silva5d62c262014-08-15 21:40:51 +0000415 return ExecuteCC1Tool(argv, argv[1] + 4);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000416 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000417
Rafael Espindola73d46372009-12-04 19:31:58 +0000418 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000419 for (int i = 1, size = argv.size(); i < size; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000420 // Skip end-of-line response file markers
421 if (argv[i] == nullptr)
422 continue;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000423 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000424 CanonicalPrefixes = false;
425 break;
426 }
427 }
428
Bob Wilsona19fad72014-01-15 01:41:52 +0000429 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
Bob Wilson39265b92014-02-23 00:11:56 +0000430 // scenes.
Bob Wilsona19fad72014-01-15 01:41:52 +0000431 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
Chad Rosier3e263e42013-02-21 18:56:55 +0000432 // FIXME: Driver shouldn't take extra initial argument.
433 ApplyQAOverride(argv, OverrideStr, SavedStrings);
Chad Rosier3e263e42013-02-21 18:56:55 +0000434 }
435
Rafael Espindola9678d272013-06-26 05:03:40 +0000436 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000437
Sean Silva22b4a342014-08-15 18:58:12 +0000438 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
439 CreateAndPopulateDiagOpts(argv);
440
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000441 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000442 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Sean Silva965bb992014-08-15 18:58:09 +0000443 FixupDiagPrefixExeName(DiagClient, Path);
Reid Klecknerdc74af12013-09-04 01:37:22 +0000444
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000445 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000446
Douglas Gregor811db4e2012-10-23 22:26:28 +0000447 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000448
449 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
450 auto SerializedConsumer =
451 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
452 &*DiagOpts, /*MergeChildRecords=*/true);
453 Diags.setClient(new ChainedDiagnosticConsumer(
454 std::unique_ptr<DiagnosticConsumer>(Diags.takeClient()),
455 std::move(SerializedConsumer)));
456 }
457
Chad Rosier5f15a352013-01-15 01:21:53 +0000458 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000459
Alp Toker1761f112014-05-15 22:26:36 +0000460 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
Sean Silvab5060472014-08-15 18:58:15 +0000461 SetInstallDir(argv, TheDriver);
Daniel Dunbar88979912010-08-01 22:29:51 +0000462
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000463 llvm::InitializeAllTargets();
Hans Wennborg1a27e042014-10-17 17:07:59 +0000464 ParseProgName(argv, SavedStrings);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000465
Sean Silva0ee846f2014-08-15 20:59:03 +0000466 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000467
Ahmed Charlesb8984322014-03-07 20:03:18 +0000468 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000469 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000470 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000471 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000472 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000473
Chad Rosier681e4b82012-04-20 17:08:59 +0000474 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000475 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
476 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Justin Bognere1a33d12014-10-20 21:02:05 +0000477
478 // Pretend that every command failed.
479 FailingCommands.clear();
480 for (const auto &J : C->getJobs())
481 if (const Command *C = dyn_cast<Command>(&J))
482 FailingCommands.push_back(std::make_pair(-1, C));
Richard Smith940a6d72012-12-25 21:56:27 +0000483 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000484
Sean Silvabbabefe2014-08-15 19:23:50 +0000485 for (const auto &P : FailingCommands) {
486 int CommandRes = P.first;
487 const Command *FailingCommand = P.second;
Chad Rosierdd60e092013-01-29 20:15:05 +0000488 if (!Res)
489 Res = CommandRes;
490
491 // If result status is < 0, then the driver command signalled an error.
492 // If result status is 70, then the driver command reported a fatal error.
Reid Kleckner3b5c6392014-07-07 20:23:27 +0000493 // On Windows, abort will return an exit code of 3. In these cases,
494 // generate additional diagnostic information if possible.
495 bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
496#ifdef LLVM_ON_WIN32
497 DiagnoseCrash |= CommandRes == 3;
498#endif
499 if (DiagnoseCrash) {
Justin Bognere1a33d12014-10-20 21:02:05 +0000500 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000501 break;
502 }
503 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000504
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000505 Diags.getClient()->finish();
506
Chris Lattner09f8cc82010-03-30 05:39:52 +0000507 // If any timers were active but haven't been destroyed yet, print their
508 // results now. This happens in -disable-free mode.
509 llvm::TimerGroup::printAll(llvm::errs());
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000510
Daniel Dunbar2608c542009-03-18 01:38:48 +0000511 llvm::llvm_shutdown();
512
Hans Wennborg501eadb2014-03-12 16:07:46 +0000513#ifdef LLVM_ON_WIN32
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000514 // Exit status should not be negative on Win32, unless abnormal termination.
515 // Once abnormal termiation was caught, negative status should not be
516 // propagated.
517 if (Res < 0)
518 Res = 1;
519#endif
520
Chad Rosierdd60e092013-01-29 20:15:05 +0000521 // If we have multiple failing commands, we return the result of the first
522 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000523 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000524}