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