Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:52

0001 //===- Compilation.h - Compilation Task Data Structure ----------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLVM_CLANG_DRIVER_COMPILATION_H
0010 #define LLVM_CLANG_DRIVER_COMPILATION_H
0011 
0012 #include "clang/Basic/LLVM.h"
0013 #include "clang/Driver/Action.h"
0014 #include "clang/Driver/Job.h"
0015 #include "clang/Driver/Util.h"
0016 #include "llvm/ADT/ArrayRef.h"
0017 #include "llvm/ADT/DenseMap.h"
0018 #include "llvm/ADT/StringRef.h"
0019 #include "llvm/Option/Option.h"
0020 #include <cassert>
0021 #include <iterator>
0022 #include <map>
0023 #include <memory>
0024 #include <optional>
0025 #include <utility>
0026 #include <vector>
0027 
0028 namespace llvm {
0029 namespace opt {
0030 
0031 class DerivedArgList;
0032 class InputArgList;
0033 
0034 } // namespace opt
0035 } // namespace llvm
0036 
0037 namespace clang {
0038 namespace driver {
0039 
0040 class Driver;
0041 class ToolChain;
0042 
0043 /// Compilation - A set of tasks to perform for a single driver
0044 /// invocation.
0045 class Compilation {
0046   /// The driver we were created by.
0047   const Driver &TheDriver;
0048 
0049   /// The default tool chain.
0050   const ToolChain &DefaultToolChain;
0051 
0052   /// A mask of all the programming models the host has to support in the
0053   /// current compilation.
0054   unsigned ActiveOffloadMask = 0;
0055 
0056   /// Array with the toolchains of offloading host and devices in the order they
0057   /// were requested by the user. We are preserving that order in case the code
0058   /// generation needs to derive a programming-model-specific semantic out of
0059   /// it.
0060   std::multimap<Action::OffloadKind, const ToolChain *>
0061       OrderedOffloadingToolchains;
0062 
0063   /// The original (untranslated) input argument list.
0064   llvm::opt::InputArgList *Args;
0065 
0066   /// The driver translated arguments. Note that toolchains may perform their
0067   /// own argument translation.
0068   llvm::opt::DerivedArgList *TranslatedArgs;
0069 
0070   /// The list of actions we've created via MakeAction.  This is not accessible
0071   /// to consumers; it's here just to manage ownership.
0072   std::vector<std::unique_ptr<Action>> AllActions;
0073 
0074   /// The list of actions.  This is maintained and modified by consumers, via
0075   /// getActions().
0076   ActionList Actions;
0077 
0078   /// The root list of jobs.
0079   JobList Jobs;
0080 
0081   /// Cache of translated arguments for a particular tool chain, bound
0082   /// architecture, and device offload kind.
0083   struct TCArgsKey final {
0084     const ToolChain *TC = nullptr;
0085     StringRef BoundArch;
0086     Action::OffloadKind DeviceOffloadKind = Action::OFK_None;
0087 
0088     TCArgsKey(const ToolChain *TC, StringRef BoundArch,
0089               Action::OffloadKind DeviceOffloadKind)
0090         : TC(TC), BoundArch(BoundArch), DeviceOffloadKind(DeviceOffloadKind) {}
0091 
0092     bool operator<(const TCArgsKey &K) const {
0093       if (TC < K.TC)
0094         return true;
0095       else if (TC == K.TC && BoundArch < K.BoundArch)
0096         return true;
0097       else if (TC == K.TC && BoundArch == K.BoundArch &&
0098                DeviceOffloadKind < K.DeviceOffloadKind)
0099         return true;
0100       return false;
0101     }
0102   };
0103   std::map<TCArgsKey, llvm::opt::DerivedArgList *> TCArgs;
0104 
0105   /// Temporary files which should be removed on exit.
0106   llvm::opt::ArgStringList TempFiles;
0107 
0108   /// Result files which should be removed on failure.
0109   ArgStringMap ResultFiles;
0110 
0111   /// Result files which are generated correctly on failure, and which should
0112   /// only be removed if we crash.
0113   ArgStringMap FailureResultFiles;
0114 
0115   /// -ftime-trace result files.
0116   ArgStringMap TimeTraceFiles;
0117 
0118   /// Optional redirection for stdin, stdout, stderr.
0119   std::vector<std::optional<StringRef>> Redirects;
0120 
0121   /// Callback called after compilation job has been finished.
0122   /// Arguments of the callback are the compilation job as an instance of
0123   /// class Command and the exit status of the corresponding child process.
0124   std::function<void(const Command &, int)> PostCallback;
0125 
0126   /// Whether we're compiling for diagnostic purposes.
0127   bool ForDiagnostics = false;
0128 
0129   /// Whether an error during the parsing of the input args.
0130   bool ContainsError;
0131 
0132   /// Whether to keep temporary files regardless of -save-temps.
0133   bool ForceKeepTempFiles = false;
0134 
0135 public:
0136   Compilation(const Driver &D, const ToolChain &DefaultToolChain,
0137               llvm::opt::InputArgList *Args,
0138               llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError);
0139   ~Compilation();
0140 
0141   const Driver &getDriver() const { return TheDriver; }
0142 
0143   const ToolChain &getDefaultToolChain() const { return DefaultToolChain; }
0144 
0145   unsigned isOffloadingHostKind(Action::OffloadKind Kind) const {
0146     return ActiveOffloadMask & Kind;
0147   }
0148 
0149   unsigned getActiveOffloadKinds() const { return ActiveOffloadMask; }
0150 
0151   /// Iterator that visits device toolchains of a given kind.
0152   using const_offload_toolchains_iterator =
0153       const std::multimap<Action::OffloadKind,
0154                           const ToolChain *>::const_iterator;
0155   using const_offload_toolchains_range =
0156       std::pair<const_offload_toolchains_iterator,
0157                 const_offload_toolchains_iterator>;
0158 
0159   template <Action::OffloadKind Kind>
0160   const_offload_toolchains_range getOffloadToolChains() const {
0161     return OrderedOffloadingToolchains.equal_range(Kind);
0162   }
0163 
0164   const_offload_toolchains_range
0165   getOffloadToolChains(Action::OffloadKind Kind) const {
0166     return OrderedOffloadingToolchains.equal_range(Kind);
0167   }
0168 
0169   /// Return true if an offloading tool chain of a given kind exists.
0170   template <Action::OffloadKind Kind> bool hasOffloadToolChain() const {
0171     return OrderedOffloadingToolchains.find(Kind) !=
0172            OrderedOffloadingToolchains.end();
0173   }
0174 
0175   /// Return an offload toolchain of the provided kind. Only one is expected to
0176   /// exist.
0177   template <Action::OffloadKind Kind>
0178   const ToolChain *getSingleOffloadToolChain() const {
0179     auto TCs = getOffloadToolChains<Kind>();
0180 
0181     assert(TCs.first != TCs.second &&
0182            "No tool chains of the selected kind exist!");
0183     assert(std::next(TCs.first) == TCs.second &&
0184            "More than one tool chain of the this kind exist.");
0185     return TCs.first->second;
0186   }
0187 
0188   void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain,
0189                                  Action::OffloadKind OffloadKind) {
0190     assert(OffloadKind != Action::OFK_Host && OffloadKind != Action::OFK_None &&
0191            "This is not a device tool chain!");
0192 
0193     // Update the host offload kind to also contain this kind.
0194     ActiveOffloadMask |= OffloadKind;
0195     OrderedOffloadingToolchains.insert(
0196         std::make_pair(OffloadKind, DeviceToolChain));
0197   }
0198 
0199   const llvm::opt::InputArgList &getInputArgs() const { return *Args; }
0200 
0201   const llvm::opt::DerivedArgList &getArgs() const { return *TranslatedArgs; }
0202 
0203   llvm::opt::DerivedArgList &getArgs() { return *TranslatedArgs; }
0204 
0205   ActionList &getActions() { return Actions; }
0206   const ActionList &getActions() const { return Actions; }
0207 
0208   /// Creates a new Action owned by this Compilation.
0209   ///
0210   /// The new Action is *not* added to the list returned by getActions().
0211   template <typename T, typename... Args> T *MakeAction(Args &&... Arg) {
0212     T *RawPtr = new T(std::forward<Args>(Arg)...);
0213     AllActions.push_back(std::unique_ptr<Action>(RawPtr));
0214     return RawPtr;
0215   }
0216 
0217   JobList &getJobs() { return Jobs; }
0218   const JobList &getJobs() const { return Jobs; }
0219 
0220   void addCommand(std::unique_ptr<Command> C) { Jobs.addJob(std::move(C)); }
0221 
0222   llvm::opt::ArgStringList &getTempFiles() { return TempFiles; }
0223   const llvm::opt::ArgStringList &getTempFiles() const { return TempFiles; }
0224 
0225   const ArgStringMap &getResultFiles() const { return ResultFiles; }
0226 
0227   const ArgStringMap &getFailureResultFiles() const {
0228     return FailureResultFiles;
0229   }
0230 
0231   /// Installs a handler that is executed when a compilation job is finished.
0232   /// The arguments of the callback specify the compilation job as an instance
0233   /// of class Command and the exit status of the child process executed that
0234   /// job.
0235   void setPostCallback(const std::function<void(const Command &, int)> &CB) {
0236     PostCallback = CB;
0237   }
0238 
0239   /// Returns the sysroot path.
0240   StringRef getSysRoot() const;
0241 
0242   /// getArgsForToolChain - Return the derived argument list for the
0243   /// tool chain \p TC (or the default tool chain, if TC is not specified).
0244   /// If a device offloading kind is specified, a translation specific for that
0245   /// kind is performed, if any.
0246   ///
0247   /// \param BoundArch - The bound architecture name, or 0.
0248   /// \param DeviceOffloadKind - The offload device kind that should be used in
0249   /// the translation, if any.
0250   const llvm::opt::DerivedArgList &
0251   getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
0252                       Action::OffloadKind DeviceOffloadKind);
0253 
0254   /// addTempFile - Add a file to remove on exit, and returns its
0255   /// argument.
0256   const char *addTempFile(const char *Name) {
0257     TempFiles.push_back(Name);
0258     return Name;
0259   }
0260 
0261   /// addResultFile - Add a file to remove on failure, and returns its
0262   /// argument.
0263   const char *addResultFile(const char *Name, const JobAction *JA) {
0264     ResultFiles[JA] = Name;
0265     return Name;
0266   }
0267 
0268   /// addFailureResultFile - Add a file to remove if we crash, and returns its
0269   /// argument.
0270   const char *addFailureResultFile(const char *Name, const JobAction *JA) {
0271     FailureResultFiles[JA] = Name;
0272     return Name;
0273   }
0274 
0275   const char *getTimeTraceFile(const JobAction *JA) const {
0276     return TimeTraceFiles.lookup(JA);
0277   }
0278   void addTimeTraceFile(const char *Name, const JobAction *JA) {
0279     assert(!TimeTraceFiles.contains(JA));
0280     TimeTraceFiles[JA] = Name;
0281   }
0282 
0283   /// CleanupFile - Delete a given file.
0284   ///
0285   /// \param IssueErrors - Report failures as errors.
0286   /// \return Whether the file was removed successfully.
0287   bool CleanupFile(const char *File, bool IssueErrors = false) const;
0288 
0289   /// CleanupFileList - Remove the files in the given list.
0290   ///
0291   /// \param IssueErrors - Report failures as errors.
0292   /// \return Whether all files were removed successfully.
0293   bool CleanupFileList(const llvm::opt::ArgStringList &Files,
0294                        bool IssueErrors = false) const;
0295 
0296   /// CleanupFileMap - Remove the files in the given map.
0297   ///
0298   /// \param JA - If specified, only delete the files associated with this
0299   /// JobAction.  Otherwise, delete all files in the map.
0300   /// \param IssueErrors - Report failures as errors.
0301   /// \return Whether all files were removed successfully.
0302   bool CleanupFileMap(const ArgStringMap &Files,
0303                       const JobAction *JA,
0304                       bool IssueErrors = false) const;
0305 
0306   /// ExecuteCommand - Execute an actual command.
0307   ///
0308   /// \param FailingCommand - For non-zero results, this will be set to the
0309   /// Command which failed, if any.
0310   /// \param LogOnly - When true, only tries to log the command, not actually
0311   /// execute it.
0312   /// \return The result code of the subprocess.
0313   int ExecuteCommand(const Command &C, const Command *&FailingCommand,
0314                      bool LogOnly = false) const;
0315 
0316   /// ExecuteJob - Execute a single job.
0317   ///
0318   /// \param FailingCommands - For non-zero results, this will be a vector of
0319   /// failing commands and their associated result code.
0320   /// \param LogOnly - When true, only tries to log the command, not actually
0321   /// execute it.
0322   void
0323   ExecuteJobs(const JobList &Jobs,
0324               SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands,
0325               bool LogOnly = false) const;
0326 
0327   /// initCompilationForDiagnostics - Remove stale state and suppress output
0328   /// so compilation can be reexecuted to generate additional diagnostic
0329   /// information (e.g., preprocessed source(s)).
0330   void initCompilationForDiagnostics();
0331 
0332   /// Return true if we're compiling for diagnostics.
0333   bool isForDiagnostics() const { return ForDiagnostics; }
0334 
0335   /// Return whether an error during the parsing of the input args.
0336   bool containsError() const { return ContainsError; }
0337 
0338   /// Force driver to fail before toolchain is created. This is necessary when
0339   /// error happens in action builder.
0340   void setContainsError() { ContainsError = true; }
0341 
0342   /// Redirect - Redirect output of this compilation. Can only be done once.
0343   ///
0344   /// \param Redirects - array of optional paths. The array should have a size
0345   /// of three. The inferior process's stdin(0), stdout(1), and stderr(2) will
0346   /// be redirected to the corresponding paths, if provided (not std::nullopt).
0347   void Redirect(ArrayRef<std::optional<StringRef>> Redirects);
0348 };
0349 
0350 } // namespace driver
0351 } // namespace clang
0352 
0353 #endif // LLVM_CLANG_DRIVER_COMPILATION_H