1//===- llvm/Support/InstVisitor.h - Define instruction visitors -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#ifndef LLVM_SUPPORT_INSTVISITOR_H
12#define LLVM_SUPPORT_INSTVISITOR_H
13
14#include "llvm/Function.h"
15#include "llvm/Instructions.h"
16#include "llvm/Module.h"
17#include "llvm/Support/CallSite.h"
18#include "llvm/Support/ErrorHandling.h"
19
20namespace llvm {
21
22// We operate on opaque instruction classes, so forward declare all instruction
23// types now...
24//
25#define HANDLE_INST(NUM, OPCODE, CLASS)   class CLASS;
26#include "llvm/Instruction.def"
27
28#define DELEGATE(CLASS_TO_VISIT) \
29  return static_cast<SubClass*>(this)-> \
30               visit##CLASS_TO_VISIT(static_cast<CLASS_TO_VISIT&>(I))
31
32
33/// @brief Base class for instruction visitors
34///
35/// Instruction visitors are used when you want to perform different actions
36/// for different kinds of instructions without having to use lots of casts
37/// and a big switch statement (in your code, that is).
38///
39/// To define your own visitor, inherit from this class, specifying your
40/// new type for the 'SubClass' template parameter, and "override" visitXXX
41/// functions in your class. I say "override" because this class is defined
42/// in terms of statically resolved overloading, not virtual functions.
43///
44/// For example, here is a visitor that counts the number of malloc
45/// instructions processed:
46///
47///  /// Declare the class.  Note that we derive from InstVisitor instantiated
48///  /// with _our new subclasses_ type.
49///  ///
50///  struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
51///    unsigned Count;
52///    CountAllocaVisitor() : Count(0) {}
53///
54///    void visitAllocaInst(AllocaInst &AI) { ++Count; }
55///  };
56///
57///  And this class would be used like this:
58///    CountAllocaVisitor CAV;
59///    CAV.visit(function);
60///    NumAllocas = CAV.Count;
61///
62/// The defined has 'visit' methods for Instruction, and also for BasicBlock,
63/// Function, and Module, which recursively process all contained instructions.
64///
65/// Note that if you don't implement visitXXX for some instruction type,
66/// the visitXXX method for instruction superclass will be invoked. So
67/// if instructions are added in the future, they will be automatically
68/// supported, if you handle one of their superclasses.
69///
70/// The optional second template argument specifies the type that instruction
71/// visitation functions should return. If you specify this, you *MUST* provide
72/// an implementation of visitInstruction though!.
73///
74/// Note that this class is specifically designed as a template to avoid
75/// virtual function call overhead.  Defining and using an InstVisitor is just
76/// as efficient as having your own switch statement over the instruction
77/// opcode.
78template<typename SubClass, typename RetTy=void>
79class InstVisitor {
80  //===--------------------------------------------------------------------===//
81  // Interface code - This is the public interface of the InstVisitor that you
82  // use to visit instructions...
83  //
84
85public:
86  // Generic visit method - Allow visitation to all instructions in a range
87  template<class Iterator>
88  void visit(Iterator Start, Iterator End) {
89    while (Start != End)
90      static_cast<SubClass*>(this)->visit(*Start++);
91  }
92
93  // Define visitors for functions and basic blocks...
94  //
95  void visit(Module &M) {
96    static_cast<SubClass*>(this)->visitModule(M);
97    visit(M.begin(), M.end());
98  }
99  void visit(Function &F) {
100    static_cast<SubClass*>(this)->visitFunction(F);
101    visit(F.begin(), F.end());
102  }
103  void visit(BasicBlock &BB) {
104    static_cast<SubClass*>(this)->visitBasicBlock(BB);
105    visit(BB.begin(), BB.end());
106  }
107
108  // Forwarding functions so that the user can visit with pointers AND refs.
109  void visit(Module       *M)  { visit(*M); }
110  void visit(Function     *F)  { visit(*F); }
111  void visit(BasicBlock   *BB) { visit(*BB); }
112  RetTy visit(Instruction *I)  { return visit(*I); }
113
114  // visit - Finally, code to visit an instruction...
115  //
116  RetTy visit(Instruction &I) {
117    switch (I.getOpcode()) {
118    default: llvm_unreachable("Unknown instruction type encountered!");
119      // Build the switch statement using the Instruction.def file...
120#define HANDLE_INST(NUM, OPCODE, CLASS) \
121    case Instruction::OPCODE: return \
122           static_cast<SubClass*>(this)-> \
123                      visit##OPCODE(static_cast<CLASS&>(I));
124#include "llvm/Instruction.def"
125    }
126  }
127
128  //===--------------------------------------------------------------------===//
129  // Visitation functions... these functions provide default fallbacks in case
130  // the user does not specify what to do for a particular instruction type.
131  // The default behavior is to generalize the instruction type to its subtype
132  // and try visiting the subtype.  All of this should be inlined perfectly,
133  // because there are no virtual functions to get in the way.
134  //
135
136  // When visiting a module, function or basic block directly, these methods get
137  // called to indicate when transitioning into a new unit.
138  //
139  void visitModule    (Module &M) {}
140  void visitFunction  (Function &F) {}
141  void visitBasicBlock(BasicBlock &BB) {}
142
143  // Define instruction specific visitor functions that can be overridden to
144  // handle SPECIFIC instructions.  These functions automatically define
145  // visitMul to proxy to visitBinaryOperator for instance in case the user does
146  // not need this generality.
147  //
148  // The one problem case we have to handle here though is that the PHINode
149  // class and opcode name are the exact same.  Because of this, we cannot
150  // define visitPHINode (the inst version) to forward to visitPHINode (the
151  // generic version) without multiply defined symbols and recursion.  To handle
152  // this, we do not autoexpand "Other" instructions, we do it manually.
153  //
154#define HANDLE_INST(NUM, OPCODE, CLASS) \
155    RetTy visit##OPCODE(CLASS &I) { DELEGATE(CLASS); }
156#include "llvm/Instruction.def"
157
158  // Specific Instruction type classes... note that all of the casts are
159  // necessary because we use the instruction classes as opaque types...
160  //
161  RetTy visitReturnInst(ReturnInst &I)            { DELEGATE(TerminatorInst);}
162  RetTy visitBranchInst(BranchInst &I)            { DELEGATE(TerminatorInst);}
163  RetTy visitSwitchInst(SwitchInst &I)            { DELEGATE(TerminatorInst);}
164  RetTy visitIndirectBrInst(IndirectBrInst &I)    { DELEGATE(TerminatorInst);}
165  RetTy visitResumeInst(ResumeInst &I)            { DELEGATE(TerminatorInst);}
166  RetTy visitUnreachableInst(UnreachableInst &I)  { DELEGATE(TerminatorInst);}
167  RetTy visitICmpInst(ICmpInst &I)                { DELEGATE(CmpInst);}
168  RetTy visitFCmpInst(FCmpInst &I)                { DELEGATE(CmpInst);}
169  RetTy visitAllocaInst(AllocaInst &I)            { DELEGATE(UnaryInstruction);}
170  RetTy visitLoadInst(LoadInst     &I)            { DELEGATE(UnaryInstruction);}
171  RetTy visitStoreInst(StoreInst   &I)            { DELEGATE(Instruction);}
172  RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { DELEGATE(Instruction);}
173  RetTy visitAtomicRMWInst(AtomicRMWInst &I)      { DELEGATE(Instruction);}
174  RetTy visitFenceInst(FenceInst   &I)            { DELEGATE(Instruction);}
175  RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction);}
176  RetTy visitPHINode(PHINode       &I)            { DELEGATE(Instruction);}
177  RetTy visitTruncInst(TruncInst &I)              { DELEGATE(CastInst);}
178  RetTy visitZExtInst(ZExtInst &I)                { DELEGATE(CastInst);}
179  RetTy visitSExtInst(SExtInst &I)                { DELEGATE(CastInst);}
180  RetTy visitFPTruncInst(FPTruncInst &I)          { DELEGATE(CastInst);}
181  RetTy visitFPExtInst(FPExtInst &I)              { DELEGATE(CastInst);}
182  RetTy visitFPToUIInst(FPToUIInst &I)            { DELEGATE(CastInst);}
183  RetTy visitFPToSIInst(FPToSIInst &I)            { DELEGATE(CastInst);}
184  RetTy visitUIToFPInst(UIToFPInst &I)            { DELEGATE(CastInst);}
185  RetTy visitSIToFPInst(SIToFPInst &I)            { DELEGATE(CastInst);}
186  RetTy visitPtrToIntInst(PtrToIntInst &I)        { DELEGATE(CastInst);}
187  RetTy visitIntToPtrInst(IntToPtrInst &I)        { DELEGATE(CastInst);}
188  RetTy visitBitCastInst(BitCastInst &I)          { DELEGATE(CastInst);}
189  RetTy visitSelectInst(SelectInst &I)            { DELEGATE(Instruction);}
190  RetTy visitVAArgInst(VAArgInst   &I)            { DELEGATE(UnaryInstruction);}
191  RetTy visitExtractElementInst(ExtractElementInst &I) { DELEGATE(Instruction);}
192  RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instruction);}
193  RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instruction);}
194  RetTy visitExtractValueInst(ExtractValueInst &I){ DELEGATE(UnaryInstruction);}
195  RetTy visitInsertValueInst(InsertValueInst &I)  { DELEGATE(Instruction); }
196  RetTy visitLandingPadInst(LandingPadInst &I)    { DELEGATE(Instruction); }
197
198  // Call and Invoke are slightly different as they delegate first through
199  // a generic CallSite visitor.
200  RetTy visitCallInst(CallInst &I) {
201    return static_cast<SubClass*>(this)->visitCallSite(&I);
202  }
203  RetTy visitInvokeInst(InvokeInst &I) {
204    return static_cast<SubClass*>(this)->visitCallSite(&I);
205  }
206
207  // Next level propagators: If the user does not overload a specific
208  // instruction type, they can overload one of these to get the whole class
209  // of instructions...
210  //
211  RetTy visitCastInst(CastInst &I)                { DELEGATE(UnaryInstruction);}
212  RetTy visitBinaryOperator(BinaryOperator &I)    { DELEGATE(Instruction);}
213  RetTy visitCmpInst(CmpInst &I)                  { DELEGATE(Instruction);}
214  RetTy visitTerminatorInst(TerminatorInst &I)    { DELEGATE(Instruction);}
215  RetTy visitUnaryInstruction(UnaryInstruction &I){ DELEGATE(Instruction);}
216
217  // Provide a special visitor for a 'callsite' that visits both calls and
218  // invokes. When unimplemented, properly delegates to either the terminator or
219  // regular instruction visitor.
220  RetTy visitCallSite(CallSite CS) {
221    assert(CS);
222    Instruction &I = *CS.getInstruction();
223    if (CS.isCall())
224      DELEGATE(Instruction);
225
226    assert(CS.isInvoke());
227    DELEGATE(TerminatorInst);
228  }
229
230  // If the user wants a 'default' case, they can choose to override this
231  // function.  If this function is not overloaded in the user's subclass, then
232  // this instruction just gets ignored.
233  //
234  // Note that you MUST override this function if your return type is not void.
235  //
236  void visitInstruction(Instruction &I) {}  // Ignore unhandled instructions
237};
238
239#undef DELEGATE
240
241} // End llvm namespace
242
243#endif
244