1 //===--- Compilation.cpp - Compilation Task Implementation ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Compilation.h"
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/ArgList.h"
14 #include "clang/Driver/Driver.h"
15 #include "clang/Driver/DriverDiagnostic.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/ToolChain.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Program.h"
26 using namespace clang::driver;
27 using namespace clang;
29 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
30 InputArgList *_Args, DerivedArgList *_TranslatedArgs)
31 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
32 TranslatedArgs(_TranslatedArgs), Redirects(0) {
35 Compilation::~Compilation() {
36 delete TranslatedArgs;
39 // Free any derived arg lists.
40 for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
41 DerivedArgList*>::iterator it = TCArgs.begin(),
42 ie = TCArgs.end(); it != ie; ++it)
43 if (it->second != TranslatedArgs)
46 // Free the actions, if built.
47 for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
51 // Free redirections of stdout/stderr.
59 const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
60 const char *BoundArch) {
62 TC = &DefaultToolChain;
64 DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
66 Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
68 Entry = TranslatedArgs;
74 void Compilation::PrintJob(raw_ostream &OS, const Job &J,
75 const char *Terminator, bool Quote) const {
76 if (const Command *C = dyn_cast<Command>(&J)) {
77 OS << " \"" << C->getExecutable() << '"';
78 for (ArgStringList::const_iterator it = C->getArguments().begin(),
79 ie = C->getArguments().end(); it != ie; ++it) {
81 if (!Quote && !std::strpbrk(*it, " \"\\$")) {
86 // Quote the argument and escape shell special characters; this isn't
87 // really complete but is good enough.
89 for (const char *s = *it; *s; ++s) {
90 if (*s == '"' || *s == '\\' || *s == '$')
98 const JobList *Jobs = cast<JobList>(&J);
99 for (JobList::const_iterator
100 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
101 PrintJob(OS, **it, Terminator, Quote);
105 static bool skipArg(const char *Flag, bool &SkipNextArg) {
106 StringRef FlagRef(Flag);
108 // Assume we're going to see -Flag <Arg>.
111 // These flags are all of the form -Flag <Arg> and are treated as two
112 // arguments. Therefore, we need to skip the flag and the next argument.
113 bool Res = llvm::StringSwitch<bool>(Flag)
114 .Cases("-I", "-MF", "-MT", "-MQ", true)
115 .Cases("-o", "-coverage-file", "-dependency-file", true)
116 .Cases("-fdebug-compilation-dir", "-fmodule-cache-path", "-idirafter", true)
117 .Cases("-include", "-include-pch", "-internal-isystem", true)
118 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
119 .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
120 .Cases("-resource-dir", "-serialize-diagnostic-file", true)
121 .Case("-dwarf-debug-flags", true)
128 // The remaining flags are treated as a single argument.
131 // These flags are all of the form -Flag and have no second argument.
132 Res = llvm::StringSwitch<bool>(Flag)
133 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
141 // These flags are treated as a single argument (e.g., -F<Dir>).
142 if (FlagRef.startswith("-F") || FlagRef.startswith("-I"))
148 static bool quoteNextArg(const char *flag) {
149 return llvm::StringSwitch<bool>(flag)
154 void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const {
155 if (const Command *C = dyn_cast<Command>(&J)) {
156 OS << C->getExecutable();
157 unsigned QuoteNextArg = 0;
158 for (ArgStringList::const_iterator it = C->getArguments().begin(),
159 ie = C->getArguments().end(); it != ie; ++it) {
162 if (skipArg(*it, SkipNext)) {
168 QuoteNextArg = quoteNextArg(*it) ? 2 : 0;
172 if (QuoteNextArg == 1)
175 if (!std::strpbrk(*it, " \"\\$")) {
178 // Quote the argument and escape shell special characters; this isn't
179 // really complete but is good enough.
181 for (const char *s = *it; *s; ++s) {
182 if (*s == '"' || *s == '\\' || *s == '$')
190 if (QuoteNextArg == 1)
197 const JobList *Jobs = cast<JobList>(&J);
198 for (JobList::const_iterator
199 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
200 PrintDiagnosticJob(OS, **it);
204 bool Compilation::CleanupFileList(const ArgStringList &Files,
205 bool IssueErrors) const {
208 for (ArgStringList::const_iterator
209 it = Files.begin(), ie = Files.end(); it != ie; ++it) {
211 llvm::sys::Path P(*it);
214 // Don't try to remove files which we don't have write access to (but may be
215 // able to remove). Underlying tools may have intentionally not overwritten
220 if (P.eraseFromDisk(false, &Error)) {
221 // Failure is only failure if the file exists and is "regular". There is
222 // a race condition here due to the limited interface of
223 // llvm::sys::Path, we want to know if the removal gave ENOENT.
225 // FIXME: Grumble, P.exists() is broken. PR3837.
227 if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
230 getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
240 int Compilation::ExecuteCommand(const Command &C,
241 const Command *&FailingCommand) const {
242 llvm::sys::Path Prog(C.getExecutable());
243 const char **Argv = new const char*[C.getArguments().size() + 2];
244 Argv[0] = C.getExecutable();
245 std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
246 Argv[C.getArguments().size() + 1] = 0;
248 if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
249 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
250 raw_ostream *OS = &llvm::errs();
252 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
254 if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
256 OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
258 llvm::raw_fd_ostream::F_Append);
259 if (!Error.empty()) {
260 getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
268 if (getDriver().CCPrintOptions)
269 *OS << "[Logging clang options]";
271 PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
273 if (OS != &llvm::errs())
279 llvm::sys::Program::ExecuteAndWait(Prog, Argv,
281 /*secondsToWait*/0, /*memoryLimit*/0,
283 if (!Error.empty()) {
284 assert(Res && "Error string set with 0 result code!");
285 getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
295 int Compilation::ExecuteJob(const Job &J,
296 const Command *&FailingCommand) const {
297 if (const Command *C = dyn_cast<Command>(&J)) {
298 return ExecuteCommand(*C, FailingCommand);
300 const JobList *Jobs = cast<JobList>(&J);
301 for (JobList::const_iterator
302 it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
303 if (int Res = ExecuteJob(**it, FailingCommand))
309 void Compilation::initCompilationForDiagnostics(void) {
310 // Free actions and jobs.
311 DeleteContainerPointers(Actions);
314 // Clear temporary/results file lists.
318 // Remove any user specified output. Claim any unclaimed arguments, so as
319 // to avoid emitting warnings about unused args.
320 OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
322 for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
323 if (TranslatedArgs->hasArg(OutputOpts[i]))
324 TranslatedArgs->eraseArg(OutputOpts[i]);
326 TranslatedArgs->ClaimAllArgs();
328 // Redirect stdout/stderr to /dev/null.
329 Redirects = new const llvm::sys::Path*[3]();
330 Redirects[1] = new const llvm::sys::Path();
331 Redirects[2] = new const llvm::sys::Path();
334 StringRef Compilation::getSysRoot(void) const {
335 return getDriver().SysRoot;