blob: 32d687e5ca8ff17c4f786cb457108c850e06b977 [file] [log] [blame]
Nick Lewycky3fdcc6f2010-12-31 17:31:54 +00001//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
Daniel Dunbar3ede8d02009-03-02 19:59:07 +00002//
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#include "clang/Driver/Compilation.h"
Daniel Dunbar21549232009-03-18 02:55:38 +000011#include "clang/Driver/Action.h"
Daniel Dunbare530ad42009-03-18 22:16:03 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbar265e9ef2009-11-19 04:25:22 +000014#include "clang/Driver/Options.h"
Daniel Dunbar586dc232009-03-16 06:42:30 +000015#include "clang/Driver/ToolChain.h"
Chad Rosier2b819102011-08-02 17:58:04 +000016#include "llvm/ADT/STLExtras.h"
Chad Rosierc91b41a2012-10-31 18:31:33 +000017#include "llvm/ADT/StringSwitch.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000018#include "llvm/Option/ArgList.h"
Rafael Espindolada1f9cb2013-06-18 20:58:25 +000019#include "llvm/Support/FileSystem.h"
Rafael Espindolaa372f402013-06-17 17:23:47 +000020#include "llvm/Support/PathV1.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000021#include "llvm/Support/Program.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "llvm/Support/raw_ostream.h"
Daniel Dunbare530ad42009-03-18 22:16:03 +000023#include <errno.h>
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include <sys/stat.h>
Francois Pichet1c3199a2011-07-23 11:36:43 +000025
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000026using namespace clang::driver;
Francois Pichet1c3199a2011-07-23 11:36:43 +000027using namespace clang;
Reid Klecknerb1e25a12013-06-14 17:17:23 +000028using namespace llvm::opt;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000029
Daniel Dunbar279c1db2010-06-11 22:00:26 +000030Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
31 InputArgList *_Args, DerivedArgList *_TranslatedArgs)
32 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
Chad Rosier2b819102011-08-02 17:58:04 +000033 TranslatedArgs(_TranslatedArgs), Redirects(0) {
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000034}
35
Mike Stump1eb44332009-09-09 15:08:12 +000036Compilation::~Compilation() {
Daniel Dunbar279c1db2010-06-11 22:00:26 +000037 delete TranslatedArgs;
Daniel Dunbar586dc232009-03-16 06:42:30 +000038 delete Args;
Mike Stump1eb44332009-09-09 15:08:12 +000039
Daniel Dunbar586dc232009-03-16 06:42:30 +000040 // Free any derived arg lists.
Daniel Dunbar49540182009-09-09 18:36:01 +000041 for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
42 DerivedArgList*>::iterator it = TCArgs.begin(),
43 ie = TCArgs.end(); it != ie; ++it)
Daniel Dunbar279c1db2010-06-11 22:00:26 +000044 if (it->second != TranslatedArgs)
45 delete it->second;
Daniel Dunbar21549232009-03-18 02:55:38 +000046
47 // Free the actions, if built.
Mike Stump1eb44332009-09-09 15:08:12 +000048 for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar21549232009-03-18 02:55:38 +000049 it != ie; ++it)
50 delete *it;
Chad Rosier2b819102011-08-02 17:58:04 +000051
52 // Free redirections of stdout/stderr.
53 if (Redirects) {
54 delete Redirects[1];
55 delete Redirects[2];
56 delete [] Redirects;
57 }
Daniel Dunbar586dc232009-03-16 06:42:30 +000058}
59
Daniel Dunbar49540182009-09-09 18:36:01 +000060const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
61 const char *BoundArch) {
Daniel Dunbar586dc232009-03-16 06:42:30 +000062 if (!TC)
63 TC = &DefaultToolChain;
64
Daniel Dunbar49540182009-09-09 18:36:01 +000065 DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
Daniel Dunbar279c1db2010-06-11 22:00:26 +000066 if (!Entry) {
67 Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
68 if (!Entry)
69 Entry = TranslatedArgs;
70 }
Daniel Dunbar586dc232009-03-16 06:42:30 +000071
Daniel Dunbaraa3e0d22009-03-18 05:58:45 +000072 return *Entry;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000073}
74
Chris Lattner5f9e2722011-07-23 10:55:15 +000075void Compilation::PrintJob(raw_ostream &OS, const Job &J,
Daniel Dunbar49b98e72009-03-18 22:44:24 +000076 const char *Terminator, bool Quote) const {
77 if (const Command *C = dyn_cast<Command>(&J)) {
Daniel Dunbar24b55602009-03-18 06:49:39 +000078 OS << " \"" << C->getExecutable() << '"';
79 for (ArgStringList::const_iterator it = C->getArguments().begin(),
Daniel Dunbar49b98e72009-03-18 22:44:24 +000080 ie = C->getArguments().end(); it != ie; ++it) {
Daniel Dunbarb86c5fc2010-03-20 08:01:53 +000081 OS << ' ';
Benjamin Kramer5f226142011-10-06 22:53:35 +000082 if (!Quote && !std::strpbrk(*it, " \"\\$")) {
Daniel Dunbarb86c5fc2010-03-20 08:01:53 +000083 OS << *it;
84 continue;
85 }
86
87 // Quote the argument and escape shell special characters; this isn't
88 // really complete but is good enough.
89 OS << '"';
90 for (const char *s = *it; *s; ++s) {
91 if (*s == '"' || *s == '\\' || *s == '$')
92 OS << '\\';
93 OS << *s;
94 }
95 OS << '"';
Daniel Dunbar49b98e72009-03-18 22:44:24 +000096 }
Daniel Dunbar24b55602009-03-18 06:49:39 +000097 OS << Terminator;
Daniel Dunbar24b55602009-03-18 06:49:39 +000098 } else {
Daniel Dunbar49b98e72009-03-18 22:44:24 +000099 const JobList *Jobs = cast<JobList>(&J);
Mike Stump1eb44332009-09-09 15:08:12 +0000100 for (JobList::const_iterator
Daniel Dunbar24b55602009-03-18 06:49:39 +0000101 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000102 PrintJob(OS, **it, Terminator, Quote);
Daniel Dunbar24b55602009-03-18 06:49:39 +0000103 }
104}
105
Chad Rosierc91b41a2012-10-31 18:31:33 +0000106static bool skipArg(const char *Flag, bool &SkipNextArg) {
107 StringRef FlagRef(Flag);
108
109 // Assume we're going to see -Flag <Arg>.
110 SkipNextArg = true;
111
112 // These flags are all of the form -Flag <Arg> and are treated as two
113 // arguments. Therefore, we need to skip the flag and the next argument.
114 bool Res = llvm::StringSwitch<bool>(Flag)
115 .Cases("-I", "-MF", "-MT", "-MQ", true)
116 .Cases("-o", "-coverage-file", "-dependency-file", true)
Douglas Gregor250172a2013-02-07 22:59:12 +0000117 .Cases("-fdebug-compilation-dir", "-idirafter", true)
Chad Rosierc91b41a2012-10-31 18:31:33 +0000118 .Cases("-include", "-include-pch", "-internal-isystem", true)
Chad Rosier1cd46de2012-10-31 21:08:30 +0000119 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
Chad Rosierc91b41a2012-10-31 18:31:33 +0000120 .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
121 .Cases("-resource-dir", "-serialize-diagnostic-file", true)
122 .Case("-dwarf-debug-flags", true)
123 .Default(false);
124
125 // Match found.
126 if (Res)
127 return Res;
128
129 // The remaining flags are treated as a single argument.
130 SkipNextArg = false;
131
132 // These flags are all of the form -Flag and have no second argument.
133 Res = llvm::StringSwitch<bool>(Flag)
134 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
135 .Case("-MMD", true)
136 .Default(false);
137
138 // Match found.
139 if (Res)
140 return Res;
141
142 // These flags are treated as a single argument (e.g., -F<Dir>).
143 if (FlagRef.startswith("-F") || FlagRef.startswith("-I"))
144 return true;
145
146 return false;
147}
148
149static bool quoteNextArg(const char *flag) {
150 return llvm::StringSwitch<bool>(flag)
151 .Case("-D", true)
152 .Default(false);
153}
154
155void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const {
156 if (const Command *C = dyn_cast<Command>(&J)) {
157 OS << C->getExecutable();
158 unsigned QuoteNextArg = 0;
159 for (ArgStringList::const_iterator it = C->getArguments().begin(),
160 ie = C->getArguments().end(); it != ie; ++it) {
161
162 bool SkipNext;
163 if (skipArg(*it, SkipNext)) {
164 if (SkipNext) ++it;
165 continue;
166 }
167
168 if (!QuoteNextArg)
169 QuoteNextArg = quoteNextArg(*it) ? 2 : 0;
170
171 OS << ' ';
172
173 if (QuoteNextArg == 1)
174 OS << '"';
175
176 if (!std::strpbrk(*it, " \"\\$")) {
177 OS << *it;
178 } else {
179 // Quote the argument and escape shell special characters; this isn't
180 // really complete but is good enough.
181 OS << '"';
182 for (const char *s = *it; *s; ++s) {
183 if (*s == '"' || *s == '\\' || *s == '$')
184 OS << '\\';
185 OS << *s;
186 }
187 OS << '"';
188 }
189
190 if (QuoteNextArg) {
191 if (QuoteNextArg == 1)
192 OS << '"';
193 --QuoteNextArg;
194 }
195 }
196 OS << '\n';
197 } else {
198 const JobList *Jobs = cast<JobList>(&J);
199 for (JobList::const_iterator
200 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
201 PrintDiagnosticJob(OS, **it);
202 }
203}
204
Chad Rosier9d718632013-01-24 19:14:47 +0000205bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
206 llvm::sys::Path P(File);
207 std::string Error;
208
209 // Don't try to remove files which we don't have write access to (but may be
210 // able to remove), or non-regular files. Underlying tools may have
211 // intentionally not overwritten them.
Rafael Espindolada1f9cb2013-06-18 20:58:25 +0000212 if (!llvm::sys::fs::can_write(File) || !P.isRegularFile())
Chad Rosier9d718632013-01-24 19:14:47 +0000213 return true;
214
215 if (P.eraseFromDisk(false, &Error)) {
216 // Failure is only failure if the file exists and is "regular". There is
217 // a race condition here due to the limited interface of
218 // llvm::sys::Path, we want to know if the removal gave ENOENT.
219
220 // FIXME: Grumble, P.exists() is broken. PR3837.
221 struct stat buf;
222 if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
223 (errno != ENOENT)) {
224 if (IssueErrors)
225 getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
226 << Error;
227 return false;
228 }
229 }
230 return true;
231}
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233bool Compilation::CleanupFileList(const ArgStringList &Files,
Daniel Dunbare530ad42009-03-18 22:16:03 +0000234 bool IssueErrors) const {
235 bool Success = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000236 for (ArgStringList::const_iterator
Chad Rosier9d718632013-01-24 19:14:47 +0000237 it = Files.begin(), ie = Files.end(); it != ie; ++it)
238 Success &= CleanupFile(*it, IssueErrors);
239 return Success;
240}
241
242bool Compilation::CleanupFileMap(const ArgStringMap &Files,
243 const JobAction *JA,
244 bool IssueErrors) const {
245 bool Success = true;
246 for (ArgStringMap::const_iterator
Daniel Dunbare530ad42009-03-18 22:16:03 +0000247 it = Files.begin(), ie = Files.end(); it != ie; ++it) {
Edward O'Callaghan56eec2b2009-11-24 15:23:21 +0000248
Chad Rosier9d718632013-01-24 19:14:47 +0000249 // If specified, only delete the files associated with the JobAction.
250 // Otherwise, delete all files in the map.
251 if (JA && it->first != JA)
Daniel Dunbar8ac127a2011-04-25 20:43:05 +0000252 continue;
Chad Rosier9d718632013-01-24 19:14:47 +0000253 Success &= CleanupFile(it->second, IssueErrors);
Daniel Dunbare530ad42009-03-18 22:16:03 +0000254 }
Daniel Dunbare530ad42009-03-18 22:16:03 +0000255 return Success;
256}
257
Daniel Dunbar31c11eb2009-07-01 19:14:39 +0000258int Compilation::ExecuteCommand(const Command &C,
259 const Command *&FailingCommand) const {
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000260 llvm::sys::Path Prog(C.getExecutable());
261 const char **Argv = new const char*[C.getArguments().size() + 2];
262 Argv[0] = C.getExecutable();
263 std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
264 Argv[C.getArguments().size() + 1] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chad Rosier2b819102011-08-02 17:58:04 +0000266 if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
267 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000268 raw_ostream *OS = &llvm::errs();
Daniel Dunbar4c00fcd2010-03-20 08:01:59 +0000269
270 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
271 // output stream.
272 if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
273 std::string Error;
274 OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
275 Error,
276 llvm::raw_fd_ostream::F_Append);
277 if (!Error.empty()) {
278 getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
279 << Error;
280 FailingCommand = &C;
281 delete OS;
282 return 1;
283 }
284 }
285
286 if (getDriver().CCPrintOptions)
287 *OS << "[Logging clang options]";
288
289 PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
290
291 if (OS != &llvm::errs())
292 delete OS;
293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000295 std::string Error;
Chad Rosierc48d5752013-03-26 23:41:30 +0000296 bool ExecutionFailed;
Rafael Espindola57a3bbf2013-06-13 20:08:52 +0000297 int Res = llvm::sys::ExecuteAndWait(Prog.str(), Argv, /*env*/ 0, Redirects,
Rafael Espindolaa6035692013-06-12 20:44:26 +0000298 /*secondsToWait*/ 0, /*memoryLimit*/ 0,
299 &Error, &ExecutionFailed);
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000300 if (!Error.empty()) {
301 assert(Res && "Error string set with 0 result code!");
302 getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
303 }
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Daniel Dunbar31c11eb2009-07-01 19:14:39 +0000305 if (Res)
306 FailingCommand = &C;
307
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000308 delete[] Argv;
Chad Rosierc48d5752013-03-26 23:41:30 +0000309 return ExecutionFailed ? 1 : Res;
Daniel Dunbarceafbc82009-03-19 08:01:45 +0000310}
311
Chad Rosier4c4df452013-02-27 18:46:04 +0000312typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
313
314static bool ActionFailed(const Action *A,
315 const FailingCommandList &FailingCommands) {
316
317 if (FailingCommands.empty())
318 return false;
319
320 for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
321 CE = FailingCommands.end(); CI != CE; ++CI)
322 if (A == &(CI->second->getSource()))
323 return true;
324
325 for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
326 if (ActionFailed(*AI, FailingCommands))
327 return true;
328
329 return false;
330}
331
332static bool InputsOk(const Command &C,
333 const FailingCommandList &FailingCommands) {
334 return !ActionFailed(&C.getSource(), FailingCommands);
335}
336
Chad Rosiera16355c2013-01-29 20:15:05 +0000337void Compilation::ExecuteJob(const Job &J,
Chad Rosier4c4df452013-02-27 18:46:04 +0000338 FailingCommandList &FailingCommands) const {
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000339 if (const Command *C = dyn_cast<Command>(&J)) {
Chad Rosier4c4df452013-02-27 18:46:04 +0000340 if (!InputsOk(*C, FailingCommands))
341 return;
Chad Rosiera16355c2013-01-29 20:15:05 +0000342 const Command *FailingCommand = 0;
343 if (int Res = ExecuteCommand(*C, FailingCommand))
344 FailingCommands.push_back(std::make_pair(Res, FailingCommand));
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000345 } else {
346 const JobList *Jobs = cast<JobList>(&J);
Chad Rosiera16355c2013-01-29 20:15:05 +0000347 for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
348 it != ie; ++it)
349 ExecuteJob(**it, FailingCommands);
Daniel Dunbar49b98e72009-03-18 22:44:24 +0000350 }
351}
Chad Rosier2b819102011-08-02 17:58:04 +0000352
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000353void Compilation::initCompilationForDiagnostics() {
Chad Rosier2b819102011-08-02 17:58:04 +0000354 // Free actions and jobs.
355 DeleteContainerPointers(Actions);
356 Jobs.clear();
357
358 // Clear temporary/results file lists.
359 TempFiles.clear();
360 ResultFiles.clear();
Chad Rosier8425a542013-01-29 23:57:10 +0000361 FailureResultFiles.clear();
Chad Rosier2b819102011-08-02 17:58:04 +0000362
363 // Remove any user specified output. Claim any unclaimed arguments, so as
364 // to avoid emitting warnings about unused args.
Peter Collingbourne54db68b2011-11-06 00:40:05 +0000365 OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
366 options::OPT_MMD };
Chad Rosierf9e156c2012-05-03 21:25:34 +0000367 for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
Peter Collingbourne54db68b2011-11-06 00:40:05 +0000368 if (TranslatedArgs->hasArg(OutputOpts[i]))
369 TranslatedArgs->eraseArg(OutputOpts[i]);
370 }
Chad Rosier2b819102011-08-02 17:58:04 +0000371 TranslatedArgs->ClaimAllArgs();
372
373 // Redirect stdout/stderr to /dev/null.
Rafael Espindola57a3bbf2013-06-13 20:08:52 +0000374 Redirects = new const StringRef*[3]();
375 Redirects[0] = 0;
376 Redirects[1] = new const StringRef();
377 Redirects[2] = new const StringRef();
Chad Rosier2b819102011-08-02 17:58:04 +0000378}
Sebastian Pop4762a2d2012-04-16 04:16:43 +0000379
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000380StringRef Compilation::getSysRoot() const {
Sebastian Pop4762a2d2012-04-16 04:16:43 +0000381 return getDriver().SysRoot;
382}