clang 23.0.0git
Compilation.h
Go to the documentation of this file.
1//===- Compilation.h - Compilation Task Data Structure ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_DRIVER_COMPILATION_H
10#define LLVM_CLANG_DRIVER_COMPILATION_H
11
12#include "clang/Basic/LLVM.h"
14#include "clang/Driver/Action.h"
15#include "clang/Driver/Job.h"
16#include "clang/Driver/Util.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Option/Option.h"
21#include <cassert>
22#include <iterator>
23#include <map>
24#include <memory>
25#include <optional>
26#include <utility>
27#include <vector>
28
29namespace llvm {
30namespace opt {
31
32class DerivedArgList;
33class InputArgList;
34
35} // namespace opt
36} // namespace llvm
37
38namespace clang {
39namespace driver {
40
41class Driver;
42class ToolChain;
43
44/// Compilation - A set of tasks to perform for a single driver
45/// invocation.
47 /// The driver we were created by.
48 const Driver &TheDriver;
49
50 /// The default tool chain.
51 const ToolChain &DefaultToolChain;
52
53 /// A mask of all the programming models the host has to support in the
54 /// current compilation.
55 unsigned ActiveOffloadMask = 0;
56
57 /// Array with the toolchains of offloading host and devices in the order they
58 /// were requested by the user. We are preserving that order in case the code
59 /// generation needs to derive a programming-model-specific semantic out of
60 /// it.
61 std::multimap<Action::OffloadKind, const ToolChain *>
62 OrderedOffloadingToolchains;
63
64 /// The original (untranslated) input argument list.
65 llvm::opt::InputArgList *Args;
66
67 /// The driver translated arguments. Note that toolchains may perform their
68 /// own argument translation.
69 llvm::opt::DerivedArgList *TranslatedArgs;
70
71 /// The list of actions we've created via MakeAction. This is not accessible
72 /// to consumers; it's here just to manage ownership.
73 std::vector<std::unique_ptr<Action>> AllActions;
74
75 /// The list of actions. This is maintained and modified by consumers, via
76 /// getActions().
77 ActionList Actions;
78
79 /// The root list of jobs.
80 JobList Jobs;
81
82 /// Cache of translated arguments for a particular tool chain, bound
83 /// architecture, and device offload kind.
84 struct TCArgsKey final {
85 const ToolChain *TC = nullptr;
86 BoundArch BoundArchitecture;
87 Action::OffloadKind DeviceOffloadKind = Action::OFK_None;
88
89 TCArgsKey(const ToolChain *TC, BoundArch BA,
90 Action::OffloadKind DeviceOffloadKind)
91 : TC(TC), BoundArchitecture(BA), DeviceOffloadKind(DeviceOffloadKind) {}
92
93 bool operator<(const TCArgsKey &K) const {
94 return std::tie(TC, BoundArchitecture, DeviceOffloadKind) <
95 std::tie(K.TC, K.BoundArchitecture, K.DeviceOffloadKind);
96 }
97 };
98 std::map<TCArgsKey, llvm::opt::DerivedArgList *> TCArgs;
99
100 /// Temporary files which should be removed on exit.
101 llvm::opt::ArgStringList TempFiles;
102
103 /// Result files which should be removed on failure.
104 ArgStringMap ResultFiles;
105
106 /// Result files which are generated correctly on failure, and which should
107 /// only be removed if we crash.
108 ArgStringMap FailureResultFiles;
109
110 /// -ftime-trace result files.
111 ArgStringMap TimeTraceFiles;
112
113 /// Optional redirection for stdin, stdout, stderr.
114 std::vector<std::optional<StringRef>> Redirects;
115
116 /// Callback called after compilation job has been finished.
117 /// Arguments of the callback are the compilation job as an instance of
118 /// class Command and the exit status of the corresponding child process.
119 std::function<void(const Command &, int)> PostCallback;
120
121 /// Whether we're compiling for diagnostic purposes.
122 bool ForDiagnostics = false;
123
124 /// Whether an error during the parsing of the input args.
125 bool ContainsError;
126
127 /// Whether to keep temporary files regardless of -save-temps.
128 bool ForceKeepTempFiles = false;
129
130 /// The bound architecture currently being built, if any. Set around
131 /// ConstructJob calls so addCommand can stamp it onto each new Command.
132 BoundArch CurrentBoundArch;
133
134public:
135 Compilation(const Driver &D, const ToolChain &DefaultToolChain,
136 llvm::opt::InputArgList *Args,
137 llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError);
138 ~Compilation();
139
140 const Driver &getDriver() const { return TheDriver; }
141
142 const ToolChain &getDefaultToolChain() const { return DefaultToolChain; }
143
145 return ActiveOffloadMask & Kind;
146 }
147
148 unsigned getActiveOffloadKinds() const { return ActiveOffloadMask; }
149
150 /// Iterator that visits device toolchains of a given kind.
152 const std::multimap<Action::OffloadKind,
157
158 template <Action::OffloadKind Kind>
160 return OrderedOffloadingToolchains.equal_range(Kind);
161 }
162
165 return OrderedOffloadingToolchains.equal_range(Kind);
166 }
167
168 /// Return true if an offloading tool chain of a given kind exists.
169 template <Action::OffloadKind Kind> bool hasOffloadToolChain() const {
170 return OrderedOffloadingToolchains.find(Kind) !=
171 OrderedOffloadingToolchains.end();
172 }
173
174 /// Return an offload toolchain of the provided kind. Only one is expected to
175 /// exist.
176 template <Action::OffloadKind Kind>
178 auto TCs = getOffloadToolChains<Kind>();
179
180 assert(TCs.first != TCs.second &&
181 "No tool chains of the selected kind exist!");
182 assert(std::next(TCs.first) == TCs.second &&
183 "More than one tool chain of the this kind exist.");
184 return TCs.first->second;
185 }
186
187 void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain,
188 Action::OffloadKind OffloadKind) {
189 assert(OffloadKind != Action::OFK_Host && OffloadKind != Action::OFK_None &&
190 "This is not a device tool chain!");
191
192 // Update the host offload kind to also contain this kind.
193 ActiveOffloadMask |= OffloadKind;
194 OrderedOffloadingToolchains.insert(
195 std::make_pair(OffloadKind, DeviceToolChain));
196 }
197
198 const llvm::opt::InputArgList &getInputArgs() const { return *Args; }
199
200 const llvm::opt::DerivedArgList &getArgs() const { return *TranslatedArgs; }
201
202 llvm::opt::DerivedArgList &getArgs() { return *TranslatedArgs; }
203
204 ActionList &getActions() { return Actions; }
205 const ActionList &getActions() const { return Actions; }
206
207 /// Creates a new Action owned by this Compilation.
208 ///
209 /// The new Action is *not* added to the list returned by getActions().
210 template <typename T, typename... Args> T *MakeAction(Args &&... Arg) {
211 T *RawPtr = new T(std::forward<Args>(Arg)...);
212 AllActions.push_back(std::unique_ptr<Action>(RawPtr));
213 return RawPtr;
214 }
215
216 JobList &getJobs() { return Jobs; }
217 const JobList &getJobs() const { return Jobs; }
218
219 void addCommand(std::unique_ptr<Command> Cmd) {
220 Cmd->setBoundArch(CurrentBoundArch);
221 Jobs.addJob(std::move(Cmd));
222 }
223
224 BoundArch getCurrentBoundArch() const { return CurrentBoundArch; }
225 void setCurrentBoundArch(BoundArch BA) { CurrentBoundArch = BA; }
226
227 llvm::opt::ArgStringList &getTempFiles() { return TempFiles; }
228 const llvm::opt::ArgStringList &getTempFiles() const { return TempFiles; }
229
230 const ArgStringMap &getResultFiles() const { return ResultFiles; }
231
233 return FailureResultFiles;
234 }
235
236 /// Installs a handler that is executed when a compilation job is finished.
237 /// The arguments of the callback specify the compilation job as an instance
238 /// of class Command and the exit status of the child process executed that
239 /// job.
240 void setPostCallback(const std::function<void(const Command &, int)> &CB) {
241 PostCallback = CB;
242 }
243
244 /// Returns the sysroot path.
245 StringRef getSysRoot() const;
246
247 /// getArgsForToolChain - Return the derived argument list for the
248 /// tool chain \p TC (or the default tool chain, if TC is not specified).
249 /// If a device offloading kind is specified, a translation specific for that
250 /// kind is performed, if any.
251 ///
252 /// \param BA - The bound architecture.
253 /// \param DeviceOffloadKind - The offload device kind that should be used in
254 /// the translation, if any.
255 const llvm::opt::DerivedArgList &
257 Action::OffloadKind DeviceOffloadKind);
258
259 /// addTempFile - Add a file to remove on exit, and returns its
260 /// argument.
261 const char *addTempFile(const char *Name) {
262 TempFiles.push_back(Name);
263 return Name;
264 }
265
266 /// addResultFile - Add a file to remove on failure, and returns its
267 /// argument.
268 const char *addResultFile(const char *Name, const JobAction *JA) {
269 ResultFiles[JA] = Name;
270 return Name;
271 }
272
273 /// addFailureResultFile - Add a file to remove if we crash, and returns its
274 /// argument.
275 const char *addFailureResultFile(const char *Name, const JobAction *JA) {
276 FailureResultFiles[JA] = Name;
277 return Name;
278 }
279
280 const char *getTimeTraceFile(const JobAction *JA) const {
281 return TimeTraceFiles.lookup(JA);
282 }
283 void addTimeTraceFile(const char *Name, const JobAction *JA) {
284 assert(!TimeTraceFiles.contains(JA));
285 TimeTraceFiles[JA] = Name;
286 }
287
288 /// CleanupFile - Delete a given file.
289 ///
290 /// \param IssueErrors - Report failures as errors.
291 /// \return Whether the file was removed successfully.
292 bool CleanupFile(const char *File, bool IssueErrors = false) const;
293
294 /// CleanupFileList - Remove the files in the given list.
295 ///
296 /// \param IssueErrors - Report failures as errors.
297 /// \return Whether all files were removed successfully.
298 bool CleanupFileList(const llvm::opt::ArgStringList &Files,
299 bool IssueErrors = false) const;
300
301 /// CleanupFileMap - Remove the files in the given map.
302 ///
303 /// \param JA - If specified, only delete the files associated with this
304 /// JobAction. Otherwise, delete all files in the map.
305 /// \param IssueErrors - Report failures as errors.
306 /// \return Whether all files were removed successfully.
307 bool CleanupFileMap(const ArgStringMap &Files,
308 const JobAction *JA,
309 bool IssueErrors = false) const;
310
311 /// ExecuteCommand - Execute an actual command.
312 ///
313 /// \param FailingCommand - For non-zero results, this will be set to the
314 /// Command which failed, if any.
315 /// \param LogOnly - When true, only tries to log the command, not actually
316 /// execute it.
317 /// \return The result code of the subprocess.
318 int ExecuteCommand(const Command &C, const Command *&FailingCommand,
319 bool LogOnly = false) const;
320
321 /// ExecuteJob - Execute a single job.
322 ///
323 /// \param FailingCommands - For non-zero results, this will be a vector of
324 /// failing commands and their associated result code.
325 /// \param LogOnly - When true, only tries to log the command, not actually
326 /// execute it.
327 void
328 ExecuteJobs(const JobList &Jobs,
329 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands,
330 bool LogOnly = false) const;
331
332 /// initCompilationForDiagnostics - Remove stale state and suppress output
333 /// so compilation can be reexecuted to generate additional diagnostic
334 /// information (e.g., preprocessed source(s)).
336
337 /// Return true if we're compiling for diagnostics.
338 bool isForDiagnostics() const { return ForDiagnostics; }
339
340 /// Return whether an error during the parsing of the input args.
341 bool containsError() const { return ContainsError; }
342
343 /// Force driver to fail before toolchain is created. This is necessary when
344 /// error happens in action builder.
345 void setContainsError() { ContainsError = true; }
346
347 /// Redirect - Redirect output of this compilation. Can only be done once.
348 ///
349 /// \param Redirects - array of optional paths. The array should have a size
350 /// of three. The inferior process's stdin(0), stdout(1), and stderr(2) will
351 /// be redirected to the corresponding paths, if provided (not std::nullopt).
352 void Redirect(ArrayRef<std::optional<StringRef>> Redirects);
353};
354
355} // namespace driver
356} // namespace clang
357
358#endif // LLVM_CLANG_DRIVER_COMPILATION_H
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
void addCommand(std::unique_ptr< Command > Cmd)
bool hasOffloadToolChain() const
Return true if an offloading tool chain of a given kind exists.
const JobList & getJobs() const
int ExecuteCommand(const Command &C, const Command *&FailingCommand, bool LogOnly=false) const
ExecuteCommand - Execute an actual command.
llvm::opt::ArgStringList & getTempFiles()
bool CleanupFileMap(const ArgStringMap &Files, const JobAction *JA, bool IssueErrors=false) const
CleanupFileMap - Remove the files in the given map.
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
const ActionList & getActions() const
void setPostCallback(const std::function< void(const Command &, int)> &CB)
Installs a handler that is executed when a compilation job is finished.
const_offload_toolchains_range getOffloadToolChains(Action::OffloadKind Kind) const
bool CleanupFile(const char *File, bool IssueErrors=false) const
CleanupFile - Delete a given file.
const ArgStringMap & getFailureResultFiles() const
llvm::opt::DerivedArgList & getArgs()
const char * getTimeTraceFile(const JobAction *JA) const
unsigned isOffloadingHostKind(Action::OffloadKind Kind) const
Compilation(const Driver &D, const ToolChain &DefaultToolChain, llvm::opt::InputArgList *Args, llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError)
T * MakeAction(Args &&... Arg)
Creates a new Action owned by this Compilation.
bool CleanupFileList(const llvm::opt::ArgStringList &Files, bool IssueErrors=false) const
CleanupFileList - Remove the files in the given list.
const ArgStringMap & getResultFiles() const
const llvm::opt::DerivedArgList & getArgsForToolChain(const ToolChain *TC, BoundArch BA, Action::OffloadKind DeviceOffloadKind)
getArgsForToolChain - Return the derived argument list for the tool chain TC (or the default tool cha...
StringRef getSysRoot() const
Returns the sysroot path.
void setCurrentBoundArch(BoundArch BA)
void setContainsError()
Force driver to fail before toolchain is created.
const_offload_toolchains_range getOffloadToolChains() const
const std::multimap< Action::OffloadKind, const ToolChain * >::const_iterator const_offload_toolchains_iterator
Iterator that visits device toolchains of a given kind.
unsigned getActiveOffloadKinds() const
const char * addFailureResultFile(const char *Name, const JobAction *JA)
addFailureResultFile - Add a file to remove if we crash, and returns its argument.
void Redirect(ArrayRef< std::optional< StringRef > > Redirects)
Redirect - Redirect output of this compilation.
const ToolChain & getDefaultToolChain() const
const char * addResultFile(const char *Name, const JobAction *JA)
addResultFile - Add a file to remove on failure, and returns its argument.
void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain, Action::OffloadKind OffloadKind)
void initCompilationForDiagnostics()
initCompilationForDiagnostics - Remove stale state and suppress output so compilation can be reexecut...
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
const llvm::opt::InputArgList & getInputArgs() const
const llvm::opt::ArgStringList & getTempFiles() const
void addTimeTraceFile(const char *Name, const JobAction *JA)
const llvm::opt::DerivedArgList & getArgs() const
void ExecuteJobs(const JobList &Jobs, SmallVectorImpl< std::pair< int, const Command * > > &FailingCommands, bool LogOnly=false) const
ExecuteJob - Execute a single job.
bool containsError() const
Return whether an error during the parsing of the input args.
bool isForDiagnostics() const
Return true if we're compiling for diagnostics.
const ToolChain * getSingleOffloadToolChain() const
Return an offload toolchain of the provided kind.
BoundArch getCurrentBoundArch() const
const Driver & getDriver() const
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
JobList - A sequence of jobs to perform.
Definition Job.h:269
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:96
SmallVector< Action *, 3 > ActionList
ActionList - Type used for lists of actions.
Definition Util.h:25
llvm::DenseMap< const JobAction *, const char * > ArgStringMap
ArgStringMap - Type used to map a JobAction to its result file.
Definition Util.h:22
The JSON file list parser is used to communicate input to InstallAPI.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
Represents a bound architecture for offload / multiple architecture compilation.