clang API Documentation

Compilation.cpp
Go to the documentation of this file.
00001 //===--- Compilation.cpp - Compilation Task Implementation ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/Driver/Compilation.h"
00011 
00012 #include "clang/Driver/Action.h"
00013 #include "clang/Driver/ArgList.h"
00014 #include "clang/Driver/Driver.h"
00015 #include "clang/Driver/DriverDiagnostic.h"
00016 #include "clang/Driver/Options.h"
00017 #include "clang/Driver/ToolChain.h"
00018 
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/Support/raw_ostream.h"
00021 #include "llvm/Support/Program.h"
00022 #include <sys/stat.h>
00023 #include <errno.h>
00024 
00025 using namespace clang::driver;
00026 using namespace clang;
00027 
00028 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
00029                          InputArgList *_Args, DerivedArgList *_TranslatedArgs)
00030   : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
00031     TranslatedArgs(_TranslatedArgs), Redirects(0) {
00032 }
00033 
00034 Compilation::~Compilation() {
00035   delete TranslatedArgs;
00036   delete Args;
00037 
00038   // Free any derived arg lists.
00039   for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
00040                       DerivedArgList*>::iterator it = TCArgs.begin(),
00041          ie = TCArgs.end(); it != ie; ++it)
00042     if (it->second != TranslatedArgs)
00043       delete it->second;
00044 
00045   // Free the actions, if built.
00046   for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
00047        it != ie; ++it)
00048     delete *it;
00049 
00050   // Free redirections of stdout/stderr.
00051   if (Redirects) {
00052     delete Redirects[1];
00053     delete Redirects[2];
00054     delete [] Redirects;
00055   }
00056 }
00057 
00058 const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
00059                                                        const char *BoundArch) {
00060   if (!TC)
00061     TC = &DefaultToolChain;
00062 
00063   DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
00064   if (!Entry) {
00065     Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
00066     if (!Entry)
00067       Entry = TranslatedArgs;
00068   }
00069 
00070   return *Entry;
00071 }
00072 
00073 void Compilation::PrintJob(raw_ostream &OS, const Job &J,
00074                            const char *Terminator, bool Quote) const {
00075   if (const Command *C = dyn_cast<Command>(&J)) {
00076     OS << " \"" << C->getExecutable() << '"';
00077     for (ArgStringList::const_iterator it = C->getArguments().begin(),
00078            ie = C->getArguments().end(); it != ie; ++it) {
00079       OS << ' ';
00080       if (!Quote && !std::strpbrk(*it, " \"\\$")) {
00081         OS << *it;
00082         continue;
00083       }
00084 
00085       // Quote the argument and escape shell special characters; this isn't
00086       // really complete but is good enough.
00087       OS << '"';
00088       for (const char *s = *it; *s; ++s) {
00089         if (*s == '"' || *s == '\\' || *s == '$')
00090           OS << '\\';
00091         OS << *s;
00092       }
00093       OS << '"';
00094     }
00095     OS << Terminator;
00096   } else {
00097     const JobList *Jobs = cast<JobList>(&J);
00098     for (JobList::const_iterator
00099            it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
00100       PrintJob(OS, **it, Terminator, Quote);
00101   }
00102 }
00103 
00104 bool Compilation::CleanupFileList(const ArgStringList &Files,
00105                                   bool IssueErrors) const {
00106   bool Success = true;
00107 
00108   for (ArgStringList::const_iterator
00109          it = Files.begin(), ie = Files.end(); it != ie; ++it) {
00110 
00111     llvm::sys::Path P(*it);
00112     std::string Error;
00113 
00114     // Don't try to remove files which we don't have write access to (but may be
00115     // able to remove). Underlying tools may have intentionally not overwritten
00116     // them.
00117     if (!P.canWrite())
00118       continue;
00119 
00120     if (P.eraseFromDisk(false, &Error)) {
00121       // Failure is only failure if the file exists and is "regular". There is
00122       // a race condition here due to the limited interface of
00123       // llvm::sys::Path, we want to know if the removal gave ENOENT.
00124 
00125       // FIXME: Grumble, P.exists() is broken. PR3837.
00126       struct stat buf;
00127       if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
00128                                          (errno != ENOENT)) {
00129         if (IssueErrors)
00130           getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
00131             << Error;
00132         Success = false;
00133       }
00134     }
00135   }
00136 
00137   return Success;
00138 }
00139 
00140 int Compilation::ExecuteCommand(const Command &C,
00141                                 const Command *&FailingCommand) const {
00142   llvm::sys::Path Prog(C.getExecutable());
00143   const char **Argv = new const char*[C.getArguments().size() + 2];
00144   Argv[0] = C.getExecutable();
00145   std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
00146   Argv[C.getArguments().size() + 1] = 0;
00147 
00148   if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
00149        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
00150     raw_ostream *OS = &llvm::errs();
00151 
00152     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
00153     // output stream.
00154     if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
00155       std::string Error;
00156       OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
00157                                     Error,
00158                                     llvm::raw_fd_ostream::F_Append);
00159       if (!Error.empty()) {
00160         getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
00161           << Error;
00162         FailingCommand = &C;
00163         delete OS;
00164         return 1;
00165       }
00166     }
00167 
00168     if (getDriver().CCPrintOptions)
00169       *OS << "[Logging clang options]";
00170 
00171     PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
00172 
00173     if (OS != &llvm::errs())
00174       delete OS;
00175   }
00176 
00177   std::string Error;
00178   int Res =
00179     llvm::sys::Program::ExecuteAndWait(Prog, Argv,
00180                                        /*env*/0, Redirects,
00181                                        /*secondsToWait*/0, /*memoryLimit*/0,
00182                                        &Error);
00183   if (!Error.empty()) {
00184     assert(Res && "Error string set with 0 result code!");
00185     getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
00186   }
00187 
00188   if (Res)
00189     FailingCommand = &C;
00190 
00191   delete[] Argv;
00192   return Res;
00193 }
00194 
00195 int Compilation::ExecuteJob(const Job &J,
00196                             const Command *&FailingCommand) const {
00197   if (const Command *C = dyn_cast<Command>(&J)) {
00198     return ExecuteCommand(*C, FailingCommand);
00199   } else {
00200     const JobList *Jobs = cast<JobList>(&J);
00201     for (JobList::const_iterator
00202            it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
00203       if (int Res = ExecuteJob(**it, FailingCommand))
00204         return Res;
00205     return 0;
00206   }
00207 }
00208 
00209 void Compilation::initCompilationForDiagnostics(void) {
00210   // Free actions and jobs.
00211   DeleteContainerPointers(Actions);
00212   Jobs.clear();
00213 
00214   // Clear temporary/results file lists.
00215   TempFiles.clear();
00216   ResultFiles.clear();
00217 
00218   // Remove any user specified output.  Claim any unclaimed arguments, so as
00219   // to avoid emitting warnings about unused args.
00220   OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
00221                                 options::OPT_MMD };
00222   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
00223     if (TranslatedArgs->hasArg(OutputOpts[i]))
00224       TranslatedArgs->eraseArg(OutputOpts[i]);
00225   }
00226   TranslatedArgs->ClaimAllArgs();
00227 
00228   // Redirect stdout/stderr to /dev/null.
00229   Redirects = new const llvm::sys::Path*[3]();
00230   Redirects[1] = new const llvm::sys::Path();
00231   Redirects[2] = new const llvm::sys::Path();
00232 }
00233 
00234 StringRef Compilation::getSysRoot(void) const {
00235   return getDriver().SysRoot;
00236 }