Pass.h revision 360660
1//===- llvm/Pass.h - Base class for Passes ----------------------*- 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// This file defines a base class that indicates that a specified class is a
10// transformation pass implementation.
11//
12// Passes are designed this way so that it is possible to run passes in a cache
13// and organizationally optimal order without having to specify it at the front
14// end.  This allows arbitrary passes to be strung together and have them
15// executed as efficiently as possible.
16//
17// Passes should extend one of the classes below, depending on the guarantees
18// that it can make about what will be modified as it is run.  For example, most
19// global optimizations should derive from FunctionPass, because they do not add
20// or delete functions, they operate on the internals of the function.
21//
22// Note that this file #includes PassSupport.h and PassAnalysisSupport.h (at the
23// bottom), so the APIs exposed by these files are also automatically available
24// to all users of this file.
25//
26//===----------------------------------------------------------------------===//
27
28#ifndef LLVM_PASS_H
29#define LLVM_PASS_H
30
31#include "llvm/ADT/StringRef.h"
32#include <string>
33
34namespace llvm {
35
36class AnalysisResolver;
37class AnalysisUsage;
38class BasicBlock;
39class Function;
40class ImmutablePass;
41class Module;
42class PassInfo;
43class PMDataManager;
44class PMStack;
45class raw_ostream;
46
47// AnalysisID - Use the PassInfo to identify a pass...
48using AnalysisID = const void *;
49
50/// Different types of internal pass managers. External pass managers
51/// (PassManager and FunctionPassManager) are not represented here.
52/// Ordering of pass manager types is important here.
53enum PassManagerType {
54  PMT_Unknown = 0,
55  PMT_ModulePassManager = 1, ///< MPPassManager
56  PMT_CallGraphPassManager,  ///< CGPassManager
57  PMT_FunctionPassManager,   ///< FPPassManager
58  PMT_LoopPassManager,       ///< LPPassManager
59  PMT_RegionPassManager,     ///< RGPassManager
60  PMT_BasicBlockPassManager, ///< BBPassManager
61  PMT_Last
62};
63
64// Different types of passes.
65enum PassKind {
66  PT_BasicBlock,
67  PT_Region,
68  PT_Loop,
69  PT_Function,
70  PT_CallGraphSCC,
71  PT_Module,
72  PT_PassManager
73};
74
75//===----------------------------------------------------------------------===//
76/// Pass interface - Implemented by all 'passes'.  Subclass this if you are an
77/// interprocedural optimization or you do not fit into any of the more
78/// constrained passes described below.
79///
80class Pass {
81  AnalysisResolver *Resolver = nullptr;  // Used to resolve analysis
82  const void *PassID;
83  PassKind Kind;
84
85public:
86  explicit Pass(PassKind K, char &pid) : PassID(&pid), Kind(K) {}
87  Pass(const Pass &) = delete;
88  Pass &operator=(const Pass &) = delete;
89  virtual ~Pass();
90
91  PassKind getPassKind() const { return Kind; }
92
93  /// getPassName - Return a nice clean name for a pass.  This usually
94  /// implemented in terms of the name that is registered by one of the
95  /// Registration templates, but can be overloaded directly.
96  virtual StringRef getPassName() const;
97
98  /// getPassID - Return the PassID number that corresponds to this pass.
99  AnalysisID getPassID() const {
100    return PassID;
101  }
102
103  /// doInitialization - Virtual method overridden by subclasses to do
104  /// any necessary initialization before any pass is run.
105  virtual bool doInitialization(Module &)  { return false; }
106
107  /// doFinalization - Virtual method overriden by subclasses to do any
108  /// necessary clean up after all passes have run.
109  virtual bool doFinalization(Module &) { return false; }
110
111  /// print - Print out the internal state of the pass.  This is called by
112  /// Analyze to print out the contents of an analysis.  Otherwise it is not
113  /// necessary to implement this method.  Beware that the module pointer MAY be
114  /// null.  This automatically forwards to a virtual function that does not
115  /// provide the Module* in case the analysis doesn't need it it can just be
116  /// ignored.
117  virtual void print(raw_ostream &OS, const Module *M) const;
118
119  void dump() const; // dump - Print to stderr.
120
121  /// createPrinterPass - Get a Pass appropriate to print the IR this
122  /// pass operates on (Module, Function or MachineFunction).
123  virtual Pass *createPrinterPass(raw_ostream &OS,
124                                  const std::string &Banner) const = 0;
125
126  /// Each pass is responsible for assigning a pass manager to itself.
127  /// PMS is the stack of available pass manager.
128  virtual void assignPassManager(PMStack &,
129                                 PassManagerType) {}
130
131  /// Check if available pass managers are suitable for this pass or not.
132  virtual void preparePassManager(PMStack &);
133
134  ///  Return what kind of Pass Manager can manage this pass.
135  virtual PassManagerType getPotentialPassManagerType() const;
136
137  // Access AnalysisResolver
138  void setResolver(AnalysisResolver *AR);
139  AnalysisResolver *getResolver() const { return Resolver; }
140
141  /// getAnalysisUsage - This function should be overriden by passes that need
142  /// analysis information to do their job.  If a pass specifies that it uses a
143  /// particular analysis result to this function, it can then use the
144  /// getAnalysis<AnalysisType>() function, below.
145  virtual void getAnalysisUsage(AnalysisUsage &) const;
146
147  /// releaseMemory() - This member can be implemented by a pass if it wants to
148  /// be able to release its memory when it is no longer needed.  The default
149  /// behavior of passes is to hold onto memory for the entire duration of their
150  /// lifetime (which is the entire compile time).  For pipelined passes, this
151  /// is not a big deal because that memory gets recycled every time the pass is
152  /// invoked on another program unit.  For IP passes, it is more important to
153  /// free memory when it is unused.
154  ///
155  /// Optionally implement this function to release pass memory when it is no
156  /// longer used.
157  virtual void releaseMemory();
158
159  /// getAdjustedAnalysisPointer - This method is used when a pass implements
160  /// an analysis interface through multiple inheritance.  If needed, it should
161  /// override this to adjust the this pointer as needed for the specified pass
162  /// info.
163  virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
164  virtual ImmutablePass *getAsImmutablePass();
165  virtual PMDataManager *getAsPMDataManager();
166
167  /// verifyAnalysis() - This member can be implemented by a analysis pass to
168  /// check state of analysis information.
169  virtual void verifyAnalysis() const;
170
171  // dumpPassStructure - Implement the -debug-passes=PassStructure option
172  virtual void dumpPassStructure(unsigned Offset = 0);
173
174  // lookupPassInfo - Return the pass info object for the specified pass class,
175  // or null if it is not known.
176  static const PassInfo *lookupPassInfo(const void *TI);
177
178  // lookupPassInfo - Return the pass info object for the pass with the given
179  // argument string, or null if it is not known.
180  static const PassInfo *lookupPassInfo(StringRef Arg);
181
182  // createPass - Create a object for the specified pass class,
183  // or null if it is not known.
184  static Pass *createPass(AnalysisID ID);
185
186  /// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
187  /// get analysis information that might be around, for example to update it.
188  /// This is different than getAnalysis in that it can fail (if the analysis
189  /// results haven't been computed), so should only be used if you can handle
190  /// the case when the analysis is not available.  This method is often used by
191  /// transformation APIs to update analysis results for a pass automatically as
192  /// the transform is performed.
193  template<typename AnalysisType> AnalysisType *
194    getAnalysisIfAvailable() const; // Defined in PassAnalysisSupport.h
195
196  /// mustPreserveAnalysisID - This method serves the same function as
197  /// getAnalysisIfAvailable, but works if you just have an AnalysisID.  This
198  /// obviously cannot give you a properly typed instance of the class if you
199  /// don't have the class name available (use getAnalysisIfAvailable if you
200  /// do), but it can tell you if you need to preserve the pass at least.
201  bool mustPreserveAnalysisID(char &AID) const;
202
203  /// getAnalysis<AnalysisType>() - This function is used by subclasses to get
204  /// to the analysis information that they claim to use by overriding the
205  /// getAnalysisUsage function.
206  template<typename AnalysisType>
207  AnalysisType &getAnalysis() const; // Defined in PassAnalysisSupport.h
208
209  template<typename AnalysisType>
210  AnalysisType &getAnalysis(Function &F); // Defined in PassAnalysisSupport.h
211
212  template<typename AnalysisType>
213  AnalysisType &getAnalysisID(AnalysisID PI) const;
214
215  template<typename AnalysisType>
216  AnalysisType &getAnalysisID(AnalysisID PI, Function &F);
217};
218
219//===----------------------------------------------------------------------===//
220/// ModulePass class - This class is used to implement unstructured
221/// interprocedural optimizations and analyses.  ModulePasses may do anything
222/// they want to the program.
223///
224class ModulePass : public Pass {
225public:
226  explicit ModulePass(char &pid) : Pass(PT_Module, pid) {}
227
228  // Force out-of-line virtual method.
229  ~ModulePass() override;
230
231  /// createPrinterPass - Get a module printer pass.
232  Pass *createPrinterPass(raw_ostream &OS,
233                          const std::string &Banner) const override;
234
235  /// runOnModule - Virtual method overriden by subclasses to process the module
236  /// being operated on.
237  virtual bool runOnModule(Module &M) = 0;
238
239  void assignPassManager(PMStack &PMS, PassManagerType T) override;
240
241  ///  Return what kind of Pass Manager can manage this pass.
242  PassManagerType getPotentialPassManagerType() const override;
243
244protected:
245  /// Optional passes call this function to check whether the pass should be
246  /// skipped. This is the case when optimization bisect is over the limit.
247  bool skipModule(Module &M) const;
248};
249
250//===----------------------------------------------------------------------===//
251/// ImmutablePass class - This class is used to provide information that does
252/// not need to be run.  This is useful for things like target information and
253/// "basic" versions of AnalysisGroups.
254///
255class ImmutablePass : public ModulePass {
256public:
257  explicit ImmutablePass(char &pid) : ModulePass(pid) {}
258
259  // Force out-of-line virtual method.
260  ~ImmutablePass() override;
261
262  /// initializePass - This method may be overriden by immutable passes to allow
263  /// them to perform various initialization actions they require.  This is
264  /// primarily because an ImmutablePass can "require" another ImmutablePass,
265  /// and if it does, the overloaded version of initializePass may get access to
266  /// these passes with getAnalysis<>.
267  virtual void initializePass();
268
269  ImmutablePass *getAsImmutablePass() override { return this; }
270
271  /// ImmutablePasses are never run.
272  bool runOnModule(Module &) override { return false; }
273};
274
275//===----------------------------------------------------------------------===//
276/// FunctionPass class - This class is used to implement most global
277/// optimizations.  Optimizations should subclass this class if they meet the
278/// following constraints:
279///
280///  1. Optimizations are organized globally, i.e., a function at a time
281///  2. Optimizing a function does not cause the addition or removal of any
282///     functions in the module
283///
284class FunctionPass : public Pass {
285public:
286  explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
287
288  /// createPrinterPass - Get a function printer pass.
289  Pass *createPrinterPass(raw_ostream &OS,
290                          const std::string &Banner) const override;
291
292  /// runOnFunction - Virtual method overriden by subclasses to do the
293  /// per-function processing of the pass.
294  virtual bool runOnFunction(Function &F) = 0;
295
296  void assignPassManager(PMStack &PMS, PassManagerType T) override;
297
298  ///  Return what kind of Pass Manager can manage this pass.
299  PassManagerType getPotentialPassManagerType() const override;
300
301protected:
302  /// Optional passes call this function to check whether the pass should be
303  /// skipped. This is the case when Attribute::OptimizeNone is set or when
304  /// optimization bisect is over the limit.
305  bool skipFunction(const Function &F) const;
306};
307
308//===----------------------------------------------------------------------===//
309/// BasicBlockPass class - This class is used to implement most local
310/// optimizations.  Optimizations should subclass this class if they
311/// meet the following constraints:
312///   1. Optimizations are local, operating on either a basic block or
313///      instruction at a time.
314///   2. Optimizations do not modify the CFG of the contained function, or any
315///      other basic block in the function.
316///   3. Optimizations conform to all of the constraints of FunctionPasses.
317///
318class BasicBlockPass : public Pass {
319public:
320  explicit BasicBlockPass(char &pid) : Pass(PT_BasicBlock, pid) {}
321
322  /// createPrinterPass - Get a basic block printer pass.
323  Pass *createPrinterPass(raw_ostream &OS,
324                          const std::string &Banner) const override;
325
326  using llvm::Pass::doInitialization;
327  using llvm::Pass::doFinalization;
328
329  /// doInitialization - Virtual method overridden by BasicBlockPass subclasses
330  /// to do any necessary per-function initialization.
331  virtual bool doInitialization(Function &);
332
333  /// runOnBasicBlock - Virtual method overriden by subclasses to do the
334  /// per-basicblock processing of the pass.
335  virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
336
337  /// doFinalization - Virtual method overriden by BasicBlockPass subclasses to
338  /// do any post processing needed after all passes have run.
339  virtual bool doFinalization(Function &);
340
341  void assignPassManager(PMStack &PMS, PassManagerType T) override;
342
343  ///  Return what kind of Pass Manager can manage this pass.
344  PassManagerType getPotentialPassManagerType() const override;
345
346protected:
347  /// Optional passes call this function to check whether the pass should be
348  /// skipped. This is the case when Attribute::OptimizeNone is set or when
349  /// optimization bisect is over the limit.
350  bool skipBasicBlock(const BasicBlock &BB) const;
351};
352
353/// If the user specifies the -time-passes argument on an LLVM tool command line
354/// then the value of this boolean will be true, otherwise false.
355/// This is the storage for the -time-passes option.
356extern bool TimePassesIsEnabled;
357
358} // end namespace llvm
359
360// Include support files that contain important APIs commonly used by Passes,
361// but that we want to separate out to make it easier to read the header files.
362#include "llvm/InitializePasses.h"
363#include "llvm/PassAnalysisSupport.h"
364#include "llvm/PassSupport.h"
365
366#endif // LLVM_PASS_H
367