LLVM  mainline
InstVisitor.h
Go to the documentation of this file.
00001 //===- InstVisitor.h - Instruction visitor templates ------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 
00011 #ifndef LLVM_IR_INSTVISITOR_H
00012 #define LLVM_IR_INSTVISITOR_H
00013 
00014 #include "llvm/IR/CallSite.h"
00015 #include "llvm/IR/Function.h"
00016 #include "llvm/IR/Instructions.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/Intrinsics.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 
00022 namespace llvm {
00023 
00024 // We operate on opaque instruction classes, so forward declare all instruction
00025 // types now...
00026 //
00027 #define HANDLE_INST(NUM, OPCODE, CLASS)   class CLASS;
00028 #include "llvm/IR/Instruction.def"
00029 
00030 #define DELEGATE(CLASS_TO_VISIT) \
00031   return static_cast<SubClass*>(this)-> \
00032                visit##CLASS_TO_VISIT(static_cast<CLASS_TO_VISIT&>(I))
00033 
00034 
00035 /// @brief Base class for instruction visitors
00036 ///
00037 /// Instruction visitors are used when you want to perform different actions
00038 /// for different kinds of instructions without having to use lots of casts
00039 /// and a big switch statement (in your code, that is).
00040 ///
00041 /// To define your own visitor, inherit from this class, specifying your
00042 /// new type for the 'SubClass' template parameter, and "override" visitXXX
00043 /// functions in your class. I say "override" because this class is defined
00044 /// in terms of statically resolved overloading, not virtual functions.
00045 ///
00046 /// For example, here is a visitor that counts the number of malloc
00047 /// instructions processed:
00048 ///
00049 ///  /// Declare the class.  Note that we derive from InstVisitor instantiated
00050 ///  /// with _our new subclasses_ type.
00051 ///  ///
00052 ///  struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
00053 ///    unsigned Count;
00054 ///    CountAllocaVisitor() : Count(0) {}
00055 ///
00056 ///    void visitAllocaInst(AllocaInst &AI) { ++Count; }
00057 ///  };
00058 ///
00059 ///  And this class would be used like this:
00060 ///    CountAllocaVisitor CAV;
00061 ///    CAV.visit(function);
00062 ///    NumAllocas = CAV.Count;
00063 ///
00064 /// The defined has 'visit' methods for Instruction, and also for BasicBlock,
00065 /// Function, and Module, which recursively process all contained instructions.
00066 ///
00067 /// Note that if you don't implement visitXXX for some instruction type,
00068 /// the visitXXX method for instruction superclass will be invoked. So
00069 /// if instructions are added in the future, they will be automatically
00070 /// supported, if you handle one of their superclasses.
00071 ///
00072 /// The optional second template argument specifies the type that instruction
00073 /// visitation functions should return. If you specify this, you *MUST* provide
00074 /// an implementation of visitInstruction though!.
00075 ///
00076 /// Note that this class is specifically designed as a template to avoid
00077 /// virtual function call overhead.  Defining and using an InstVisitor is just
00078 /// as efficient as having your own switch statement over the instruction
00079 /// opcode.
00080 template<typename SubClass, typename RetTy=void>
00081 class InstVisitor {
00082   //===--------------------------------------------------------------------===//
00083   // Interface code - This is the public interface of the InstVisitor that you
00084   // use to visit instructions...
00085   //
00086 
00087 public:
00088   // Generic visit method - Allow visitation to all instructions in a range
00089   template<class Iterator>
00090   void visit(Iterator Start, Iterator End) {
00091     while (Start != End)
00092       static_cast<SubClass*>(this)->visit(*Start++);
00093   }
00094 
00095   // Define visitors for functions and basic blocks...
00096   //
00097   void visit(Module &M) {
00098     static_cast<SubClass*>(this)->visitModule(M);
00099     visit(M.begin(), M.end());
00100   }
00101   void visit(Function &F) {
00102     static_cast<SubClass*>(this)->visitFunction(F);
00103     visit(F.begin(), F.end());
00104   }
00105   void visit(BasicBlock &BB) {
00106     static_cast<SubClass*>(this)->visitBasicBlock(BB);
00107     visit(BB.begin(), BB.end());
00108   }
00109 
00110   // Forwarding functions so that the user can visit with pointers AND refs.
00111   void visit(Module       *M)  { visit(*M); }
00112   void visit(Function     *F)  { visit(*F); }
00113   void visit(BasicBlock   *BB) { visit(*BB); }
00114   RetTy visit(Instruction *I)  { return visit(*I); }
00115 
00116   // visit - Finally, code to visit an instruction...
00117   //
00118   RetTy visit(Instruction &I) {
00119     switch (I.getOpcode()) {
00120     default: llvm_unreachable("Unknown instruction type encountered!");
00121       // Build the switch statement using the Instruction.def file...
00122 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00123     case Instruction::OPCODE: return \
00124            static_cast<SubClass*>(this)-> \
00125                       visit##OPCODE(static_cast<CLASS&>(I));
00126 #include "llvm/IR/Instruction.def"
00127     }
00128   }
00129 
00130   //===--------------------------------------------------------------------===//
00131   // Visitation functions... these functions provide default fallbacks in case
00132   // the user does not specify what to do for a particular instruction type.
00133   // The default behavior is to generalize the instruction type to its subtype
00134   // and try visiting the subtype.  All of this should be inlined perfectly,
00135   // because there are no virtual functions to get in the way.
00136   //
00137 
00138   // When visiting a module, function or basic block directly, these methods get
00139   // called to indicate when transitioning into a new unit.
00140   //
00141   void visitModule    (Module &M) {}
00142   void visitFunction  (Function &F) {}
00143   void visitBasicBlock(BasicBlock &BB) {}
00144 
00145   // Define instruction specific visitor functions that can be overridden to
00146   // handle SPECIFIC instructions.  These functions automatically define
00147   // visitMul to proxy to visitBinaryOperator for instance in case the user does
00148   // not need this generality.
00149   //
00150   // These functions can also implement fan-out, when a single opcode and
00151   // instruction have multiple more specific Instruction subclasses. The Call
00152   // instruction currently supports this. We implement that by redirecting that
00153   // instruction to a special delegation helper.
00154 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00155     RetTy visit##OPCODE(CLASS &I) { \
00156       if (NUM == Instruction::Call) \
00157         return delegateCallInst(I); \
00158       else \
00159         DELEGATE(CLASS); \
00160     }
00161 #include "llvm/IR/Instruction.def"
00162 
00163   // Specific Instruction type classes... note that all of the casts are
00164   // necessary because we use the instruction classes as opaque types...
00165   //
00166   RetTy visitReturnInst(ReturnInst &I)            { DELEGATE(TerminatorInst);}
00167   RetTy visitBranchInst(BranchInst &I)            { DELEGATE(TerminatorInst);}
00168   RetTy visitSwitchInst(SwitchInst &I)            { DELEGATE(TerminatorInst);}
00169   RetTy visitIndirectBrInst(IndirectBrInst &I)    { DELEGATE(TerminatorInst);}
00170   RetTy visitResumeInst(ResumeInst &I)            { DELEGATE(TerminatorInst);}
00171   RetTy visitUnreachableInst(UnreachableInst &I)  { DELEGATE(TerminatorInst);}
00172   RetTy visitCleanupReturnInst(CleanupReturnInst &I) { DELEGATE(TerminatorInst);}
00173   RetTy visitCatchReturnInst(CatchReturnInst &I)  { DELEGATE(TerminatorInst); }
00174   RetTy visitCatchSwitchInst(CatchSwitchInst &I)  { DELEGATE(TerminatorInst);}
00175   RetTy visitICmpInst(ICmpInst &I)                { DELEGATE(CmpInst);}
00176   RetTy visitFCmpInst(FCmpInst &I)                { DELEGATE(CmpInst);}
00177   RetTy visitAllocaInst(AllocaInst &I)            { DELEGATE(UnaryInstruction);}
00178   RetTy visitLoadInst(LoadInst     &I)            { DELEGATE(UnaryInstruction);}
00179   RetTy visitStoreInst(StoreInst   &I)            { DELEGATE(Instruction);}
00180   RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { DELEGATE(Instruction);}
00181   RetTy visitAtomicRMWInst(AtomicRMWInst &I)      { DELEGATE(Instruction);}
00182   RetTy visitFenceInst(FenceInst   &I)            { DELEGATE(Instruction);}
00183   RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction);}
00184   RetTy visitPHINode(PHINode       &I)            { DELEGATE(Instruction);}
00185   RetTy visitTruncInst(TruncInst &I)              { DELEGATE(CastInst);}
00186   RetTy visitZExtInst(ZExtInst &I)                { DELEGATE(CastInst);}
00187   RetTy visitSExtInst(SExtInst &I)                { DELEGATE(CastInst);}
00188   RetTy visitFPTruncInst(FPTruncInst &I)          { DELEGATE(CastInst);}
00189   RetTy visitFPExtInst(FPExtInst &I)              { DELEGATE(CastInst);}
00190   RetTy visitFPToUIInst(FPToUIInst &I)            { DELEGATE(CastInst);}
00191   RetTy visitFPToSIInst(FPToSIInst &I)            { DELEGATE(CastInst);}
00192   RetTy visitUIToFPInst(UIToFPInst &I)            { DELEGATE(CastInst);}
00193   RetTy visitSIToFPInst(SIToFPInst &I)            { DELEGATE(CastInst);}
00194   RetTy visitPtrToIntInst(PtrToIntInst &I)        { DELEGATE(CastInst);}
00195   RetTy visitIntToPtrInst(IntToPtrInst &I)        { DELEGATE(CastInst);}
00196   RetTy visitBitCastInst(BitCastInst &I)          { DELEGATE(CastInst);}
00197   RetTy visitAddrSpaceCastInst(AddrSpaceCastInst &I) { DELEGATE(CastInst);}
00198   RetTy visitSelectInst(SelectInst &I)            { DELEGATE(Instruction);}
00199   RetTy visitVAArgInst(VAArgInst   &I)            { DELEGATE(UnaryInstruction);}
00200   RetTy visitExtractElementInst(ExtractElementInst &I) { DELEGATE(Instruction);}
00201   RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instruction);}
00202   RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instruction);}
00203   RetTy visitExtractValueInst(ExtractValueInst &I){ DELEGATE(UnaryInstruction);}
00204   RetTy visitInsertValueInst(InsertValueInst &I)  { DELEGATE(Instruction); }
00205   RetTy visitLandingPadInst(LandingPadInst &I)    { DELEGATE(Instruction); }
00206   RetTy visitFuncletPadInst(FuncletPadInst &I) { DELEGATE(Instruction); }
00207   RetTy visitCleanupPadInst(CleanupPadInst &I) { DELEGATE(FuncletPadInst); }
00208   RetTy visitCatchPadInst(CatchPadInst &I)     { DELEGATE(FuncletPadInst); }
00209 
00210   // Handle the special instrinsic instruction classes.
00211   RetTy visitDbgDeclareInst(DbgDeclareInst &I)    { DELEGATE(DbgInfoIntrinsic);}
00212   RetTy visitDbgValueInst(DbgValueInst &I)        { DELEGATE(DbgInfoIntrinsic);}
00213   RetTy visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) { DELEGATE(IntrinsicInst); }
00214   RetTy visitMemSetInst(MemSetInst &I)            { DELEGATE(MemIntrinsic); }
00215   RetTy visitMemCpyInst(MemCpyInst &I)            { DELEGATE(MemTransferInst); }
00216   RetTy visitMemMoveInst(MemMoveInst &I)          { DELEGATE(MemTransferInst); }
00217   RetTy visitMemTransferInst(MemTransferInst &I)  { DELEGATE(MemIntrinsic); }
00218   RetTy visitMemIntrinsic(MemIntrinsic &I)        { DELEGATE(IntrinsicInst); }
00219   RetTy visitVAStartInst(VAStartInst &I)          { DELEGATE(IntrinsicInst); }
00220   RetTy visitVAEndInst(VAEndInst &I)              { DELEGATE(IntrinsicInst); }
00221   RetTy visitVACopyInst(VACopyInst &I)            { DELEGATE(IntrinsicInst); }
00222   RetTy visitIntrinsicInst(IntrinsicInst &I)      { DELEGATE(CallInst); }
00223 
00224   // Call and Invoke are slightly different as they delegate first through
00225   // a generic CallSite visitor.
00226   RetTy visitCallInst(CallInst &I) {
00227     return static_cast<SubClass*>(this)->visitCallSite(&I);
00228   }
00229   RetTy visitInvokeInst(InvokeInst &I) {
00230     return static_cast<SubClass*>(this)->visitCallSite(&I);
00231   }
00232 
00233   // Next level propagators: If the user does not overload a specific
00234   // instruction type, they can overload one of these to get the whole class
00235   // of instructions...
00236   //
00237   RetTy visitCastInst(CastInst &I)                { DELEGATE(UnaryInstruction);}
00238   RetTy visitBinaryOperator(BinaryOperator &I)    { DELEGATE(Instruction);}
00239   RetTy visitCmpInst(CmpInst &I)                  { DELEGATE(Instruction);}
00240   RetTy visitTerminatorInst(TerminatorInst &I)    { DELEGATE(Instruction);}
00241   RetTy visitUnaryInstruction(UnaryInstruction &I){ DELEGATE(Instruction);}
00242 
00243   // Provide a special visitor for a 'callsite' that visits both calls and
00244   // invokes. When unimplemented, properly delegates to either the terminator or
00245   // regular instruction visitor.
00246   RetTy visitCallSite(CallSite CS) {
00247     assert(CS);
00248     Instruction &I = *CS.getInstruction();
00249     if (CS.isCall())
00250       DELEGATE(Instruction);
00251 
00252     assert(CS.isInvoke());
00253     DELEGATE(TerminatorInst);
00254   }
00255 
00256   // If the user wants a 'default' case, they can choose to override this
00257   // function.  If this function is not overloaded in the user's subclass, then
00258   // this instruction just gets ignored.
00259   //
00260   // Note that you MUST override this function if your return type is not void.
00261   //
00262   void visitInstruction(Instruction &I) {}  // Ignore unhandled instructions
00263 
00264 private:
00265   // Special helper function to delegate to CallInst subclass visitors.
00266   RetTy delegateCallInst(CallInst &I) {
00267     if (const Function *F = I.getCalledFunction()) {
00268       switch (F->getIntrinsicID()) {
00269       default:                     DELEGATE(IntrinsicInst);
00270       case Intrinsic::dbg_declare: DELEGATE(DbgDeclareInst);
00271       case Intrinsic::dbg_value:   DELEGATE(DbgValueInst);
00272       case Intrinsic::memcpy:      DELEGATE(MemCpyInst);
00273       case Intrinsic::memmove:     DELEGATE(MemMoveInst);
00274       case Intrinsic::memset:      DELEGATE(MemSetInst);
00275       case Intrinsic::vastart:     DELEGATE(VAStartInst);
00276       case Intrinsic::vaend:       DELEGATE(VAEndInst);
00277       case Intrinsic::vacopy:      DELEGATE(VACopyInst);
00278       case Intrinsic::not_intrinsic: break;
00279       }
00280     }
00281     DELEGATE(CallInst);
00282   }
00283 
00284   // An overload that will never actually be called, it is used only from dead
00285   // code in the dispatching from opcodes to instruction subclasses.
00286   RetTy delegateCallInst(Instruction &I) {
00287     llvm_unreachable("delegateCallInst called for non-CallInst");
00288   }
00289 };
00290 
00291 #undef DELEGATE
00292 
00293 } // End llvm namespace
00294 
00295 #endif