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