Compilation.cpp revision 263508
1//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
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
10#include "clang/Driver/Compilation.h"
11#include "clang/Driver/Action.h"
12#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
14#include "clang/Driver/Options.h"
15#include "clang/Driver/ToolChain.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/Option/ArgList.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/raw_ostream.h"
20#include <errno.h>
21#include <sys/stat.h>
22
23using namespace clang::driver;
24using namespace clang;
25using namespace llvm::opt;
26
27Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
28                         InputArgList *_Args, DerivedArgList *_TranslatedArgs)
29  : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
30    TranslatedArgs(_TranslatedArgs), Redirects(0) {
31}
32
33Compilation::~Compilation() {
34  delete TranslatedArgs;
35  delete Args;
36
37  // Free any derived arg lists.
38  for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
39                      DerivedArgList*>::iterator it = TCArgs.begin(),
40         ie = TCArgs.end(); it != ie; ++it)
41    if (it->second != TranslatedArgs)
42      delete it->second;
43
44  // Free the actions, if built.
45  for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
46       it != ie; ++it)
47    delete *it;
48
49  // Free redirections of stdout/stderr.
50  if (Redirects) {
51    delete Redirects[1];
52    delete Redirects[2];
53    delete [] Redirects;
54  }
55}
56
57const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
58                                                       const char *BoundArch) {
59  if (!TC)
60    TC = &DefaultToolChain;
61
62  DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
63  if (!Entry) {
64    Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
65    if (!Entry)
66      Entry = TranslatedArgs;
67  }
68
69  return *Entry;
70}
71
72bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
73  std::string P(File);
74
75  // FIXME: Why are we trying to remove files that we have not created? For
76  // example we should only try to remove a temporary assembly file if
77  // "clang -cc1" succeed in writing it. Was this a workaround for when
78  // clang was writing directly to a .s file and sometimes leaving it behind
79  // during a failure?
80
81  // FIXME: If this is necessary, we can still try to split
82  // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
83  // duplicated stat from is_regular_file.
84
85  // Don't try to remove files which we don't have write access to (but may be
86  // able to remove), or non-regular files. Underlying tools may have
87  // intentionally not overwritten them.
88  if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
89    return true;
90
91  if (llvm::error_code EC = llvm::sys::fs::remove(File)) {
92    // Failure is only failure if the file exists and is "regular". We checked
93    // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
94    // so we don't need to check again.
95
96    if (IssueErrors)
97      getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
98        << EC.message();
99    return false;
100  }
101  return true;
102}
103
104bool Compilation::CleanupFileList(const ArgStringList &Files,
105                                  bool IssueErrors) const {
106  bool Success = true;
107  for (ArgStringList::const_iterator
108         it = Files.begin(), ie = Files.end(); it != ie; ++it)
109    Success &= CleanupFile(*it, IssueErrors);
110  return Success;
111}
112
113bool Compilation::CleanupFileMap(const ArgStringMap &Files,
114                                 const JobAction *JA,
115                                 bool IssueErrors) const {
116  bool Success = true;
117  for (ArgStringMap::const_iterator
118         it = Files.begin(), ie = Files.end(); it != ie; ++it) {
119
120    // If specified, only delete the files associated with the JobAction.
121    // Otherwise, delete all files in the map.
122    if (JA && it->first != JA)
123      continue;
124    Success &= CleanupFile(it->second, IssueErrors);
125  }
126  return Success;
127}
128
129int Compilation::ExecuteCommand(const Command &C,
130                                const Command *&FailingCommand) const {
131  if ((getDriver().CCPrintOptions ||
132       getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
133    raw_ostream *OS = &llvm::errs();
134
135    // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
136    // output stream.
137    if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
138      std::string Error;
139      OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, Error,
140                                    llvm::sys::fs::F_Append);
141      if (!Error.empty()) {
142        getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
143          << Error;
144        FailingCommand = &C;
145        delete OS;
146        return 1;
147      }
148    }
149
150    if (getDriver().CCPrintOptions)
151      *OS << "[Logging clang options]";
152
153    C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
154
155    if (OS != &llvm::errs())
156      delete OS;
157  }
158
159  std::string Error;
160  bool ExecutionFailed;
161  int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
162  if (!Error.empty()) {
163    assert(Res && "Error string set with 0 result code!");
164    getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
165  }
166
167  if (Res)
168    FailingCommand = &C;
169
170  return ExecutionFailed ? 1 : Res;
171}
172
173typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
174
175static bool ActionFailed(const Action *A,
176                         const FailingCommandList &FailingCommands) {
177
178  if (FailingCommands.empty())
179    return false;
180
181  for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
182         CE = FailingCommands.end(); CI != CE; ++CI)
183    if (A == &(CI->second->getSource()))
184      return true;
185
186  for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
187    if (ActionFailed(*AI, FailingCommands))
188      return true;
189
190  return false;
191}
192
193static bool InputsOk(const Command &C,
194                     const FailingCommandList &FailingCommands) {
195  return !ActionFailed(&C.getSource(), FailingCommands);
196}
197
198void Compilation::ExecuteJob(const Job &J,
199                             FailingCommandList &FailingCommands) const {
200  if (const Command *C = dyn_cast<Command>(&J)) {
201    if (!InputsOk(*C, FailingCommands))
202      return;
203    const Command *FailingCommand = 0;
204    if (int Res = ExecuteCommand(*C, FailingCommand))
205      FailingCommands.push_back(std::make_pair(Res, FailingCommand));
206  } else {
207    const JobList *Jobs = cast<JobList>(&J);
208    for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
209         it != ie; ++it)
210      ExecuteJob(**it, FailingCommands);
211  }
212}
213
214void Compilation::initCompilationForDiagnostics() {
215  // Free actions and jobs.
216  DeleteContainerPointers(Actions);
217  Jobs.clear();
218
219  // Clear temporary/results file lists.
220  TempFiles.clear();
221  ResultFiles.clear();
222  FailureResultFiles.clear();
223
224  // Remove any user specified output.  Claim any unclaimed arguments, so as
225  // to avoid emitting warnings about unused args.
226  OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
227                                options::OPT_MMD };
228  for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
229    if (TranslatedArgs->hasArg(OutputOpts[i]))
230      TranslatedArgs->eraseArg(OutputOpts[i]);
231  }
232  TranslatedArgs->ClaimAllArgs();
233
234  // Redirect stdout/stderr to /dev/null.
235  Redirects = new const StringRef*[3]();
236  Redirects[0] = 0;
237  Redirects[1] = new const StringRef();
238  Redirects[2] = new const StringRef();
239}
240
241StringRef Compilation::getSysRoot() const {
242  return getDriver().SysRoot;
243}
244