xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/InstVisitor.h (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1 //===- InstVisitor.h - Instruction visitor templates ------------*- 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 
10 #ifndef LLVM_IR_INSTVISITOR_H
11 #define LLVM_IR_INSTVISITOR_H
12 
13 #include "llvm/IR/Function.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/Intrinsics.h"
17 #include "llvm/IR/Module.h"
18 
19 namespace llvm {
20 
21 // We operate on opaque instruction classes, so forward declare all instruction
22 // types now...
23 //
24 #define HANDLE_INST(NUM, OPCODE, CLASS)   class CLASS;
25 #include "llvm/IR/Instruction.def"
26 
27 #define DELEGATE(CLASS_TO_VISIT) \
28   return static_cast<SubClass*>(this)-> \
29                visit##CLASS_TO_VISIT(static_cast<CLASS_TO_VISIT&>(I))
30 
31 
32 /// Base class for instruction visitors
33 ///
34 /// Instruction visitors are used when you want to perform different actions
35 /// for different kinds of instructions without having to use lots of casts
36 /// and a big switch statement (in your code, that is).
37 ///
38 /// To define your own visitor, inherit from this class, specifying your
39 /// new type for the 'SubClass' template parameter, and "override" visitXXX
40 /// functions in your class. I say "override" because this class is defined
41 /// in terms of statically resolved overloading, not virtual functions.
42 ///
43 /// For example, here is a visitor that counts the number of malloc
44 /// instructions processed:
45 ///
46 ///  /// Declare the class.  Note that we derive from InstVisitor instantiated
47 ///  /// with _our new subclasses_ type.
48 ///  ///
49 ///  struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
50 ///    unsigned Count;
51 ///    CountAllocaVisitor() : Count(0) {}
52 ///
53 ///    void visitAllocaInst(AllocaInst &AI) { ++Count; }
54 ///  };
55 ///
56 ///  And this class would be used like this:
57 ///    CountAllocaVisitor CAV;
58 ///    CAV.visit(function);
59 ///    NumAllocas = CAV.Count;
60 ///
61 /// The defined has 'visit' methods for Instruction, and also for BasicBlock,
62 /// Function, and Module, which recursively process all contained instructions.
63 ///
64 /// Note that if you don't implement visitXXX for some instruction type,
65 /// the visitXXX method for instruction superclass will be invoked. So
66 /// if instructions are added in the future, they will be automatically
67 /// supported, if you handle one of their superclasses.
68 ///
69 /// The optional second template argument specifies the type that instruction
70 /// visitation functions should return. If you specify this, you *MUST* provide
71 /// an implementation of visitInstruction though!.
72 ///
73 /// Note that this class is specifically designed as a template to avoid
74 /// virtual function call overhead.  Defining and using an InstVisitor is just
75 /// as efficient as having your own switch statement over the instruction
76 /// opcode.
77 template<typename SubClass, typename RetTy=void>
78 class InstVisitor {
79   //===--------------------------------------------------------------------===//
80   // Interface code - This is the public interface of the InstVisitor that you
81   // use to visit instructions...
82   //
83 
84 public:
85   // Generic visit method - Allow visitation to all instructions in a range
86   template<class Iterator>
visit(Iterator Start,Iterator End)87   void visit(Iterator Start, Iterator End) {
88     while (Start != End)
89       static_cast<SubClass*>(this)->visit(*Start++);
90   }
91 
92   // Define visitors for functions and basic blocks...
93   //
visit(Module & M)94   void visit(Module &M) {
95     static_cast<SubClass*>(this)->visitModule(M);
96     visit(M.begin(), M.end());
97   }
visit(Function & F)98   void visit(Function &F) {
99     static_cast<SubClass*>(this)->visitFunction(F);
100     visit(F.begin(), F.end());
101   }
visit(BasicBlock & BB)102   void visit(BasicBlock &BB) {
103     static_cast<SubClass*>(this)->visitBasicBlock(BB);
104     visit(BB.begin(), BB.end());
105   }
106 
107   // Forwarding functions so that the user can visit with pointers AND refs.
visit(Module * M)108   void visit(Module       *M)  { visit(*M); }
visit(Function * F)109   void visit(Function     *F)  { visit(*F); }
visit(BasicBlock * BB)110   void visit(BasicBlock   *BB) { visit(*BB); }
visit(Instruction * I)111   RetTy visit(Instruction *I)  { return visit(*I); }
112 
113   // visit - Finally, code to visit an instruction...
114   //
visit(Instruction & I)115   RetTy visit(Instruction &I) {
116     static_assert(std::is_base_of<InstVisitor, SubClass>::value,
117                   "Must pass the derived type to this template!");
118 
119     switch (I.getOpcode()) {
120     default: llvm_unreachable("Unknown instruction type encountered!");
121       // Build the switch statement using the Instruction.def file...
122 #define HANDLE_INST(NUM, OPCODE, CLASS) \
123     case Instruction::OPCODE: return \
124            static_cast<SubClass*>(this)-> \
125                       visit##OPCODE(static_cast<CLASS&>(I));
126 #include "llvm/IR/Instruction.def"
127     }
128   }
129 
130   //===--------------------------------------------------------------------===//
131   // Visitation functions... these functions provide default fallbacks in case
132   // the user does not specify what to do for a particular instruction type.
133   // The default behavior is to generalize the instruction type to its subtype
134   // and try visiting the subtype.  All of this should be inlined perfectly,
135   // because there are no virtual functions to get in the way.
136   //
137 
138   // When visiting a module, function or basic block directly, these methods get
139   // called to indicate when transitioning into a new unit.
140   //
visitModule(Module & M)141   void visitModule    (Module &M) {}
visitFunction(Function & F)142   void visitFunction  (Function &F) {}
visitBasicBlock(BasicBlock & BB)143   void visitBasicBlock(BasicBlock &BB) {}
144 
145   // Define instruction specific visitor functions that can be overridden to
146   // handle SPECIFIC instructions.  These functions automatically define
147   // visitMul to proxy to visitBinaryOperator for instance in case the user does
148   // not need this generality.
149   //
150   // These functions can also implement fan-out, when a single opcode and
151   // instruction have multiple more specific Instruction subclasses. The Call
152   // instruction currently supports this. We implement that by redirecting that
153   // instruction to a special delegation helper.
154 #define HANDLE_INST(NUM, OPCODE, CLASS) \
155     RetTy visit##OPCODE(CLASS &I) { \
156       if (NUM == Instruction::Call) \
157         return delegateCallInst(I); \
158       else \
159         DELEGATE(CLASS); \
160     }
161 #include "llvm/IR/Instruction.def"
162 
163   // Specific Instruction type classes... note that all of the casts are
164   // necessary because we use the instruction classes as opaque types...
165   //
visitICmpInst(ICmpInst & I)166   RetTy visitICmpInst(ICmpInst &I)                { DELEGATE(CmpInst);}
visitFCmpInst(FCmpInst & I)167   RetTy visitFCmpInst(FCmpInst &I)                { DELEGATE(CmpInst);}
visitAllocaInst(AllocaInst & I)168   RetTy visitAllocaInst(AllocaInst &I)            { DELEGATE(UnaryInstruction);}
visitLoadInst(LoadInst & I)169   RetTy visitLoadInst(LoadInst     &I)            { DELEGATE(UnaryInstruction);}
visitStoreInst(StoreInst & I)170   RetTy visitStoreInst(StoreInst   &I)            { DELEGATE(Instruction);}
visitAtomicCmpXchgInst(AtomicCmpXchgInst & I)171   RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { DELEGATE(Instruction);}
visitAtomicRMWInst(AtomicRMWInst & I)172   RetTy visitAtomicRMWInst(AtomicRMWInst &I)      { DELEGATE(Instruction);}
visitFenceInst(FenceInst & I)173   RetTy visitFenceInst(FenceInst   &I)            { DELEGATE(Instruction);}
visitGetElementPtrInst(GetElementPtrInst & I)174   RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction);}
visitPHINode(PHINode & I)175   RetTy visitPHINode(PHINode       &I)            { DELEGATE(Instruction);}
visitTruncInst(TruncInst & I)176   RetTy visitTruncInst(TruncInst &I)              { DELEGATE(CastInst);}
visitZExtInst(ZExtInst & I)177   RetTy visitZExtInst(ZExtInst &I)                { DELEGATE(CastInst);}
visitSExtInst(SExtInst & I)178   RetTy visitSExtInst(SExtInst &I)                { DELEGATE(CastInst);}
visitFPTruncInst(FPTruncInst & I)179   RetTy visitFPTruncInst(FPTruncInst &I)          { DELEGATE(CastInst);}
visitFPExtInst(FPExtInst & I)180   RetTy visitFPExtInst(FPExtInst &I)              { DELEGATE(CastInst);}
visitFPToUIInst(FPToUIInst & I)181   RetTy visitFPToUIInst(FPToUIInst &I)            { DELEGATE(CastInst);}
visitFPToSIInst(FPToSIInst & I)182   RetTy visitFPToSIInst(FPToSIInst &I)            { DELEGATE(CastInst);}
visitUIToFPInst(UIToFPInst & I)183   RetTy visitUIToFPInst(UIToFPInst &I)            { DELEGATE(CastInst);}
visitSIToFPInst(SIToFPInst & I)184   RetTy visitSIToFPInst(SIToFPInst &I)            { DELEGATE(CastInst);}
visitPtrToIntInst(PtrToIntInst & I)185   RetTy visitPtrToIntInst(PtrToIntInst &I)        { DELEGATE(CastInst);}
visitIntToPtrInst(IntToPtrInst & I)186   RetTy visitIntToPtrInst(IntToPtrInst &I)        { DELEGATE(CastInst);}
visitBitCastInst(BitCastInst & I)187   RetTy visitBitCastInst(BitCastInst &I)          { DELEGATE(CastInst);}
visitAddrSpaceCastInst(AddrSpaceCastInst & I)188   RetTy visitAddrSpaceCastInst(AddrSpaceCastInst &I) { DELEGATE(CastInst);}
visitSelectInst(SelectInst & I)189   RetTy visitSelectInst(SelectInst &I)            { DELEGATE(Instruction);}
visitVAArgInst(VAArgInst & I)190   RetTy visitVAArgInst(VAArgInst   &I)            { DELEGATE(UnaryInstruction);}
visitExtractElementInst(ExtractElementInst & I)191   RetTy visitExtractElementInst(ExtractElementInst &I) { DELEGATE(Instruction);}
visitInsertElementInst(InsertElementInst & I)192   RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instruction);}
visitShuffleVectorInst(ShuffleVectorInst & I)193   RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instruction);}
visitExtractValueInst(ExtractValueInst & I)194   RetTy visitExtractValueInst(ExtractValueInst &I){ DELEGATE(UnaryInstruction);}
visitInsertValueInst(InsertValueInst & I)195   RetTy visitInsertValueInst(InsertValueInst &I)  { DELEGATE(Instruction); }
visitLandingPadInst(LandingPadInst & I)196   RetTy visitLandingPadInst(LandingPadInst &I)    { DELEGATE(Instruction); }
visitFuncletPadInst(FuncletPadInst & I)197   RetTy visitFuncletPadInst(FuncletPadInst &I) { DELEGATE(Instruction); }
visitCleanupPadInst(CleanupPadInst & I)198   RetTy visitCleanupPadInst(CleanupPadInst &I) { DELEGATE(FuncletPadInst); }
visitCatchPadInst(CatchPadInst & I)199   RetTy visitCatchPadInst(CatchPadInst &I)     { DELEGATE(FuncletPadInst); }
visitFreezeInst(FreezeInst & I)200   RetTy visitFreezeInst(FreezeInst &I)         { DELEGATE(Instruction); }
201 
202   // Handle the special intrinsic instruction classes.
visitDbgDeclareInst(DbgDeclareInst & I)203   RetTy visitDbgDeclareInst(DbgDeclareInst &I)    { DELEGATE(DbgVariableIntrinsic);}
visitDbgValueInst(DbgValueInst & I)204   RetTy visitDbgValueInst(DbgValueInst &I)        { DELEGATE(DbgVariableIntrinsic);}
visitDbgVariableIntrinsic(DbgVariableIntrinsic & I)205   RetTy visitDbgVariableIntrinsic(DbgVariableIntrinsic &I)
206                                                   { DELEGATE(DbgInfoIntrinsic);}
visitDbgLabelInst(DbgLabelInst & I)207   RetTy visitDbgLabelInst(DbgLabelInst &I)        { DELEGATE(DbgInfoIntrinsic);}
visitDbgInfoIntrinsic(DbgInfoIntrinsic & I)208   RetTy visitDbgInfoIntrinsic(DbgInfoIntrinsic &I){ DELEGATE(IntrinsicInst); }
visitMemSetInst(MemSetInst & I)209   RetTy visitMemSetInst(MemSetInst &I)            { DELEGATE(MemIntrinsic); }
visitMemSetInlineInst(MemSetInlineInst & I)210   RetTy visitMemSetInlineInst(MemSetInlineInst &I){ DELEGATE(MemSetInst); }
visitMemCpyInst(MemCpyInst & I)211   RetTy visitMemCpyInst(MemCpyInst &I)            { DELEGATE(MemTransferInst); }
visitMemCpyInlineInst(MemCpyInlineInst & I)212   RetTy visitMemCpyInlineInst(MemCpyInlineInst &I){ DELEGATE(MemCpyInst); }
visitMemMoveInst(MemMoveInst & I)213   RetTy visitMemMoveInst(MemMoveInst &I)          { DELEGATE(MemTransferInst); }
visitMemTransferInst(MemTransferInst & I)214   RetTy visitMemTransferInst(MemTransferInst &I)  { DELEGATE(MemIntrinsic); }
visitMemIntrinsic(MemIntrinsic & I)215   RetTy visitMemIntrinsic(MemIntrinsic &I)        { DELEGATE(IntrinsicInst); }
visitVAStartInst(VAStartInst & I)216   RetTy visitVAStartInst(VAStartInst &I)          { DELEGATE(IntrinsicInst); }
visitVAEndInst(VAEndInst & I)217   RetTy visitVAEndInst(VAEndInst &I)              { DELEGATE(IntrinsicInst); }
visitVACopyInst(VACopyInst & I)218   RetTy visitVACopyInst(VACopyInst &I)            { DELEGATE(IntrinsicInst); }
visitIntrinsicInst(IntrinsicInst & I)219   RetTy visitIntrinsicInst(IntrinsicInst &I)      { DELEGATE(CallInst); }
visitCallInst(CallInst & I)220   RetTy visitCallInst(CallInst &I)                { DELEGATE(CallBase); }
visitInvokeInst(InvokeInst & I)221   RetTy visitInvokeInst(InvokeInst &I)            { DELEGATE(CallBase); }
visitCallBrInst(CallBrInst & I)222   RetTy visitCallBrInst(CallBrInst &I)            { DELEGATE(CallBase); }
223 
224   // While terminators don't have a distinct type modeling them, we support
225   // intercepting them with dedicated a visitor callback.
visitReturnInst(ReturnInst & I)226   RetTy visitReturnInst(ReturnInst &I) {
227     return static_cast<SubClass *>(this)->visitTerminator(I);
228   }
visitBranchInst(BranchInst & I)229   RetTy visitBranchInst(BranchInst &I) {
230     return static_cast<SubClass *>(this)->visitTerminator(I);
231   }
visitSwitchInst(SwitchInst & I)232   RetTy visitSwitchInst(SwitchInst &I) {
233     return static_cast<SubClass *>(this)->visitTerminator(I);
234   }
visitIndirectBrInst(IndirectBrInst & I)235   RetTy visitIndirectBrInst(IndirectBrInst &I) {
236     return static_cast<SubClass *>(this)->visitTerminator(I);
237   }
visitResumeInst(ResumeInst & I)238   RetTy visitResumeInst(ResumeInst &I) {
239     return static_cast<SubClass *>(this)->visitTerminator(I);
240   }
visitUnreachableInst(UnreachableInst & I)241   RetTy visitUnreachableInst(UnreachableInst &I) {
242     return static_cast<SubClass *>(this)->visitTerminator(I);
243   }
visitCleanupReturnInst(CleanupReturnInst & I)244   RetTy visitCleanupReturnInst(CleanupReturnInst &I) {
245     return static_cast<SubClass *>(this)->visitTerminator(I);
246   }
visitCatchReturnInst(CatchReturnInst & I)247   RetTy visitCatchReturnInst(CatchReturnInst &I) {
248     return static_cast<SubClass *>(this)->visitTerminator(I);
249   }
visitCatchSwitchInst(CatchSwitchInst & I)250   RetTy visitCatchSwitchInst(CatchSwitchInst &I) {
251     return static_cast<SubClass *>(this)->visitTerminator(I);
252   }
visitTerminator(Instruction & I)253   RetTy visitTerminator(Instruction &I)    { DELEGATE(Instruction);}
254 
255   // Next level propagators: If the user does not overload a specific
256   // instruction type, they can overload one of these to get the whole class
257   // of instructions...
258   //
visitCastInst(CastInst & I)259   RetTy visitCastInst(CastInst &I)                { DELEGATE(UnaryInstruction);}
visitUnaryOperator(UnaryOperator & I)260   RetTy visitUnaryOperator(UnaryOperator &I)      { DELEGATE(UnaryInstruction);}
visitBinaryOperator(BinaryOperator & I)261   RetTy visitBinaryOperator(BinaryOperator &I)    { DELEGATE(Instruction);}
visitCmpInst(CmpInst & I)262   RetTy visitCmpInst(CmpInst &I)                  { DELEGATE(Instruction);}
visitUnaryInstruction(UnaryInstruction & I)263   RetTy visitUnaryInstruction(UnaryInstruction &I){ DELEGATE(Instruction);}
264 
265   // The next level delegation for `CallBase` is slightly more complex in order
266   // to support visiting cases where the call is also a terminator.
visitCallBase(CallBase & I)267   RetTy visitCallBase(CallBase &I) {
268     if (isa<InvokeInst>(I) || isa<CallBrInst>(I))
269       return static_cast<SubClass *>(this)->visitTerminator(I);
270 
271     DELEGATE(Instruction);
272   }
273 
274   // If the user wants a 'default' case, they can choose to override this
275   // function.  If this function is not overloaded in the user's subclass, then
276   // this instruction just gets ignored.
277   //
278   // Note that you MUST override this function if your return type is not void.
279   //
visitInstruction(Instruction & I)280   void visitInstruction(Instruction &I) {}  // Ignore unhandled instructions
281 
282 private:
283   // Special helper function to delegate to CallInst subclass visitors.
delegateCallInst(CallInst & I)284   RetTy delegateCallInst(CallInst &I) {
285     if (const Function *F = I.getCalledFunction()) {
286       switch (F->getIntrinsicID()) {
287       default:                     DELEGATE(IntrinsicInst);
288       case Intrinsic::dbg_declare: DELEGATE(DbgDeclareInst);
289       case Intrinsic::dbg_value:   DELEGATE(DbgValueInst);
290       case Intrinsic::dbg_label:   DELEGATE(DbgLabelInst);
291       case Intrinsic::memcpy:      DELEGATE(MemCpyInst);
292       case Intrinsic::memcpy_inline:
293         DELEGATE(MemCpyInlineInst);
294       case Intrinsic::memmove:     DELEGATE(MemMoveInst);
295       case Intrinsic::memset:      DELEGATE(MemSetInst);
296       case Intrinsic::memset_inline:
297         DELEGATE(MemSetInlineInst);
298       case Intrinsic::vastart:     DELEGATE(VAStartInst);
299       case Intrinsic::vaend:       DELEGATE(VAEndInst);
300       case Intrinsic::vacopy:      DELEGATE(VACopyInst);
301       case Intrinsic::not_intrinsic: break;
302       }
303     }
304     DELEGATE(CallInst);
305   }
306 
307   // An overload that will never actually be called, it is used only from dead
308   // code in the dispatching from opcodes to instruction subclasses.
delegateCallInst(Instruction & I)309   RetTy delegateCallInst(Instruction &I) {
310     llvm_unreachable("delegateCallInst called for non-CallInst");
311   }
312 };
313 
314 #undef DELEGATE
315 
316 } // End llvm namespace
317 
318 #endif
319