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 
21 using namespace clang::driver;
22 using namespace clang;
23 using namespace llvm::opt;
24 
25 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
26                          InputArgList *_Args, DerivedArgList *_TranslatedArgs,
27                          bool ContainsError)
28     : TheDriver(D), DefaultToolChain(_DefaultToolChain), ActiveOffloadMask(0u),
29       Args(_Args), TranslatedArgs(_TranslatedArgs), ForDiagnostics(false),
30       ContainsError(ContainsError) {
31   // The offloading host toolchain is the default tool chain.
32   OrderedOffloadingToolchains.insert(
33       std::make_pair(Action::OFK_Host, &DefaultToolChain));
34 }
35 
36 Compilation::~Compilation() {
37   delete TranslatedArgs;
38   delete Args;
39 
40   // Free any derived arg lists.
41   for (auto Arg : TCArgs)
42     if (Arg.second != TranslatedArgs)
43       delete Arg.second;
44 }
45 
46 const DerivedArgList &
47 Compilation::getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
48                                  Action::OffloadKind DeviceOffloadKind) {
49   if (!TC)
50     TC = &DefaultToolChain;
51 
52   DerivedArgList *&Entry = TCArgs[{TC, BoundArch, DeviceOffloadKind}];
53   if (!Entry) {
54     SmallVector<Arg *, 4> AllocatedArgs;
55     // Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.
56     DerivedArgList *OpenMPArgs = TC->TranslateOpenMPTargetArgs(
57         *TranslatedArgs, DeviceOffloadKind, AllocatedArgs);
58     if (!OpenMPArgs) {
59       Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch, DeviceOffloadKind);
60     } else {
61       Entry = TC->TranslateArgs(*OpenMPArgs, BoundArch, DeviceOffloadKind);
62       delete OpenMPArgs;
63     }
64 
65     if (!Entry)
66       Entry = TranslatedArgs;
67 
68     // Add allocated arguments to the final DAL.
69     for (auto ArgPtr : AllocatedArgs) {
70       Entry->AddSynthesizedArg(ArgPtr);
71     }
72   }
73 
74   return *Entry;
75 }
76 
77 bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
78   // FIXME: Why are we trying to remove files that we have not created? For
79   // example we should only try to remove a temporary assembly file if
80   // "clang -cc1" succeed in writing it. Was this a workaround for when
81   // clang was writing directly to a .s file and sometimes leaving it behind
82   // during a failure?
83 
84   // FIXME: If this is necessary, we can still try to split
85   // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
86   // duplicated stat from is_regular_file.
87 
88   // Don't try to remove files which we don't have write access to (but may be
89   // able to remove), or non-regular files. Underlying tools may have
90   // intentionally not overwritten them.
91   if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
92     return true;
93 
94   if (std::error_code EC = llvm::sys::fs::remove(File)) {
95     // Failure is only failure if the file exists and is "regular". We checked
96     // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
97     // so we don't need to check again.
98 
99     if (IssueErrors)
100       getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
101         << EC.message();
102     return false;
103   }
104   return true;
105 }
106 
107 bool Compilation::CleanupFileList(const ArgStringList &Files,
108                                   bool IssueErrors) const {
109   bool Success = true;
110   for (ArgStringList::const_iterator
111          it = Files.begin(), ie = Files.end(); it != ie; ++it)
112     Success &= CleanupFile(*it, IssueErrors);
113   return Success;
114 }
115 
116 bool Compilation::CleanupFileMap(const ArgStringMap &Files,
117                                  const JobAction *JA,
118                                  bool IssueErrors) const {
119   bool Success = true;
120   for (ArgStringMap::const_iterator
121          it = Files.begin(), ie = Files.end(); it != ie; ++it) {
122 
123     // If specified, only delete the files associated with the JobAction.
124     // Otherwise, delete all files in the map.
125     if (JA && it->first != JA)
126       continue;
127     Success &= CleanupFile(it->second, IssueErrors);
128   }
129   return Success;
130 }
131 
132 int Compilation::ExecuteCommand(const Command &C,
133                                 const Command *&FailingCommand) const {
134   if ((getDriver().CCPrintOptions ||
135        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
136     raw_ostream *OS = &llvm::errs();
137 
138     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
139     // output stream.
140     if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
141       std::error_code EC;
142       OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
143                                     llvm::sys::fs::F_Append |
144                                         llvm::sys::fs::F_Text);
145       if (EC) {
146         getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
147             << EC.message();
148         FailingCommand = &C;
149         delete OS;
150         return 1;
151       }
152     }
153 
154     if (getDriver().CCPrintOptions)
155       *OS << "[Logging clang options]";
156 
157     C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
158 
159     if (OS != &llvm::errs())
160       delete OS;
161   }
162 
163   std::string Error;
164   bool ExecutionFailed;
165   int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
166   if (!Error.empty()) {
167     assert(Res && "Error string set with 0 result code!");
168     getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
169   }
170 
171   if (Res)
172     FailingCommand = &C;
173 
174   return ExecutionFailed ? 1 : Res;
175 }
176 
177 void Compilation::ExecuteJobs(
178     const JobList &Jobs,
179     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) const {
180   for (const auto &Job : Jobs) {
181     const Command *FailingCommand = nullptr;
182     if (int Res = ExecuteCommand(Job, FailingCommand)) {
183       FailingCommands.push_back(std::make_pair(Res, FailingCommand));
184       // Bail as soon as one command fails, so we don't output duplicate error
185       // messages if we die on e.g. the same file.
186       return;
187     }
188   }
189 }
190 
191 void Compilation::initCompilationForDiagnostics() {
192   ForDiagnostics = true;
193 
194   // Free actions and jobs.
195   Actions.clear();
196   AllActions.clear();
197   Jobs.clear();
198 
199   // Clear temporary/results file lists.
200   TempFiles.clear();
201   ResultFiles.clear();
202   FailureResultFiles.clear();
203 
204   // Remove any user specified output.  Claim any unclaimed arguments, so as
205   // to avoid emitting warnings about unused args.
206   OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
207                                 options::OPT_MMD };
208   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
209     if (TranslatedArgs->hasArg(OutputOpts[i]))
210       TranslatedArgs->eraseArg(OutputOpts[i]);
211   }
212   TranslatedArgs->ClaimAllArgs();
213 
214   // Redirect stdout/stderr to /dev/null.
215   Redirects = {None, {""}, {""}};
216 }
217 
218 StringRef Compilation::getSysRoot() const {
219   return getDriver().SysRoot;
220 }
221 
222 void Compilation::Redirect(ArrayRef<Optional<StringRef>> Redirects) {
223   this->Redirects = Redirects;
224 }
225