IR: Remove unnecessary specialization of getSymTab(), NFC
[oota-llvm.git] / include / llvm / IR / BasicBlock.h
1 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- 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 // This file contains the declaration of the BasicBlock class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_BASICBLOCK_H
15 #define LLVM_IR_BASICBLOCK_H
16
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/IR/SymbolTableListTraits.h"
21 #include "llvm/Support/CBindingWrapping.h"
22 #include "llvm/Support/DataTypes.h"
23
24 namespace llvm {
25
26 class CallInst;
27 class LandingPadInst;
28 class TerminatorInst;
29 class LLVMContext;
30 class BlockAddress;
31 class Function;
32
33 // Traits for intrusive list of basic blocks...
34 template<> struct ilist_traits<BasicBlock>
35   : public SymbolTableListTraits<BasicBlock, Function> {
36
37   BasicBlock *createSentinel() const;
38   static void destroySentinel(BasicBlock*) {}
39
40   BasicBlock *provideInitialHead() const { return createSentinel(); }
41   BasicBlock *ensureHead(BasicBlock*) const { return createSentinel(); }
42   static void noteHead(BasicBlock*, BasicBlock*) {}
43 private:
44   mutable ilist_half_node<BasicBlock> Sentinel;
45 };
46
47
48 /// \brief LLVM Basic Block Representation
49 ///
50 /// This represents a single basic block in LLVM. A basic block is simply a
51 /// container of instructions that execute sequentially. Basic blocks are Values
52 /// because they are referenced by instructions such as branches and switch
53 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
54 /// represents a label to which a branch can jump.
55 ///
56 /// A well formed basic block is formed of a list of non-terminating
57 /// instructions followed by a single TerminatorInst instruction.
58 /// TerminatorInst's may not occur in the middle of basic blocks, and must
59 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
60 /// occur because it may be useful in the intermediate stage of constructing or
61 /// modifying a program. However, the verifier will ensure that basic blocks
62 /// are "well formed".
63 class BasicBlock : public Value, // Basic blocks are data objects also
64                    public ilist_node<BasicBlock> {
65   friend class BlockAddress;
66 public:
67   typedef iplist<Instruction> InstListType;
68 private:
69   InstListType InstList;
70   Function *Parent;
71
72   void setParent(Function *parent);
73   friend class SymbolTableListTraits<BasicBlock, Function>;
74
75   BasicBlock(const BasicBlock &) = delete;
76   void operator=(const BasicBlock &) = delete;
77
78   /// \brief Constructor.
79   ///
80   /// If the function parameter is specified, the basic block is automatically
81   /// inserted at either the end of the function (if InsertBefore is null), or
82   /// before the specified basic block.
83   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
84                       Function *Parent = nullptr,
85                       BasicBlock *InsertBefore = nullptr);
86 public:
87   /// \brief Get the context in which this basic block lives.
88   LLVMContext &getContext() const;
89
90   /// Instruction iterators...
91   typedef InstListType::iterator iterator;
92   typedef InstListType::const_iterator const_iterator;
93   typedef InstListType::reverse_iterator reverse_iterator;
94   typedef InstListType::const_reverse_iterator const_reverse_iterator;
95
96   /// \brief Creates a new BasicBlock.
97   ///
98   /// If the Parent parameter is specified, the basic block is automatically
99   /// inserted at either the end of the function (if InsertBefore is 0), or
100   /// before the specified basic block.
101   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
102                             Function *Parent = nullptr,
103                             BasicBlock *InsertBefore = nullptr) {
104     return new BasicBlock(Context, Name, Parent, InsertBefore);
105   }
106   ~BasicBlock() override;
107
108   /// \brief Return the enclosing method, or null if none.
109   const Function *getParent() const { return Parent; }
110         Function *getParent()       { return Parent; }
111
112   /// \brief Return the module owning the function this basic block belongs to,
113   /// or nullptr it the function does not have a module.
114   ///
115   /// Note: this is undefined behavior if the block does not have a parent.
116   const Module *getModule() const;
117   Module *getModule();
118
119   /// \brief Returns the terminator instruction if the block is well formed or
120   /// null if the block is not well formed.
121   TerminatorInst *getTerminator();
122   const TerminatorInst *getTerminator() const;
123
124   /// \brief Returns the call instruction marked 'musttail' prior to the
125   /// terminating return instruction of this basic block, if such a call is
126   /// present.  Otherwise, returns null.
127   CallInst *getTerminatingMustTailCall();
128   const CallInst *getTerminatingMustTailCall() const {
129     return const_cast<BasicBlock *>(this)->getTerminatingMustTailCall();
130   }
131
132   /// \brief Returns a pointer to the first instruction in this block that is
133   /// not a PHINode instruction.
134   ///
135   /// When adding instructions to the beginning of the basic block, they should
136   /// be added before the returned value, not before the first instruction,
137   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
138   Instruction* getFirstNonPHI();
139   const Instruction* getFirstNonPHI() const {
140     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
141   }
142
143   /// \brief Returns a pointer to the first instruction in this block that is not
144   /// a PHINode or a debug intrinsic.
145   Instruction* getFirstNonPHIOrDbg();
146   const Instruction* getFirstNonPHIOrDbg() const {
147     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
148   }
149
150   /// \brief Returns a pointer to the first instruction in this block that is not
151   /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
152   Instruction* getFirstNonPHIOrDbgOrLifetime();
153   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
154     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
155   }
156
157   /// \brief Returns an iterator to the first instruction in this block that is
158   /// suitable for inserting a non-PHI instruction.
159   ///
160   /// In particular, it skips all PHIs and LandingPad instructions.
161   iterator getFirstInsertionPt();
162   const_iterator getFirstInsertionPt() const {
163     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
164   }
165
166   /// \brief Unlink 'this' from the containing function, but do not delete it.
167   void removeFromParent();
168
169   /// \brief Unlink 'this' from the containing function and delete it.
170   ///
171   // \returns an iterator pointing to the element after the erased one.
172   iplist<BasicBlock>::iterator eraseFromParent();
173
174   /// \brief Unlink this basic block from its current function and insert it
175   /// into the function that \p MovePos lives in, right before \p MovePos.
176   void moveBefore(BasicBlock *MovePos);
177
178   /// \brief Unlink this basic block from its current function and insert it
179   /// right after \p MovePos in the function \p MovePos lives in.
180   void moveAfter(BasicBlock *MovePos);
181
182   /// \brief Insert unlinked basic block into a function.
183   ///
184   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
185   /// provided, inserts before that basic block, otherwise inserts at the end.
186   ///
187   /// \pre \a getParent() is \c nullptr.
188   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
189
190   /// \brief Return the predecessor of this block if it has a single predecessor
191   /// block. Otherwise return a null pointer.
192   BasicBlock *getSinglePredecessor();
193   const BasicBlock *getSinglePredecessor() const {
194     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
195   }
196
197   /// \brief Return the predecessor of this block if it has a unique predecessor
198   /// block. Otherwise return a null pointer.
199   ///
200   /// Note that unique predecessor doesn't mean single edge, there can be
201   /// multiple edges from the unique predecessor to this block (for example a
202   /// switch statement with multiple cases having the same destination).
203   BasicBlock *getUniquePredecessor();
204   const BasicBlock *getUniquePredecessor() const {
205     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
206   }
207
208   /// \brief Return the successor of this block if it has a single successor.
209   /// Otherwise return a null pointer.
210   ///
211   /// This method is analogous to getSinglePredecessor above.
212   BasicBlock *getSingleSuccessor();
213   const BasicBlock *getSingleSuccessor() const {
214     return const_cast<BasicBlock*>(this)->getSingleSuccessor();
215   }
216
217   /// \brief Return the successor of this block if it has a unique successor.
218   /// Otherwise return a null pointer.
219   ///
220   /// This method is analogous to getUniquePredecessor above.
221   BasicBlock *getUniqueSuccessor();
222   const BasicBlock *getUniqueSuccessor() const {
223     return const_cast<BasicBlock*>(this)->getUniqueSuccessor();
224   }
225
226   //===--------------------------------------------------------------------===//
227   /// Instruction iterator methods
228   ///
229   inline iterator                begin()       { return InstList.begin(); }
230   inline const_iterator          begin() const { return InstList.begin(); }
231   inline iterator                end  ()       { return InstList.end();   }
232   inline const_iterator          end  () const { return InstList.end();   }
233
234   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
235   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
236   inline reverse_iterator        rend  ()       { return InstList.rend();   }
237   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
238
239   inline size_t                   size() const { return InstList.size();  }
240   inline bool                    empty() const { return InstList.empty(); }
241   inline const Instruction      &front() const { return InstList.front(); }
242   inline       Instruction      &front()       { return InstList.front(); }
243   inline const Instruction       &back() const { return InstList.back();  }
244   inline       Instruction       &back()       { return InstList.back();  }
245
246   /// \brief Return the underlying instruction list container.
247   ///
248   /// Currently you need to access the underlying instruction list container
249   /// directly if you want to modify it.
250   const InstListType &getInstList() const { return InstList; }
251         InstListType &getInstList()       { return InstList; }
252
253   /// \brief Returns a pointer to a member of the instruction list.
254   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
255     return &BasicBlock::InstList;
256   }
257
258   /// \brief Returns a pointer to the symbol table if one exists.
259   ValueSymbolTable *getValueSymbolTable();
260
261   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
262   static inline bool classof(const Value *V) {
263     return V->getValueID() == Value::BasicBlockVal;
264   }
265
266   /// \brief Cause all subinstructions to "let go" of all the references that
267   /// said subinstructions are maintaining.
268   ///
269   /// This allows one to 'delete' a whole class at a time, even though there may
270   /// be circular references... first all references are dropped, and all use
271   /// counts go to zero.  Then everything is delete'd for real.  Note that no
272   /// operations are valid on an object that has "dropped all references",
273   /// except operator delete.
274   void dropAllReferences();
275
276   /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
277   /// able to reach it.
278   ///
279   /// This is actually not used to update the Predecessor list, but is actually
280   /// used to update the PHI nodes that reside in the block.  Note that this
281   /// should be called while the predecessor still refers to this block.
282   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
283
284   bool canSplitPredecessors() const;
285
286   /// \brief Split the basic block into two basic blocks at the specified
287   /// instruction.
288   ///
289   /// Note that all instructions BEFORE the specified iterator stay as part of
290   /// the original basic block, an unconditional branch is added to the original
291   /// BB, and the rest of the instructions in the BB are moved to the new BB,
292   /// including the old terminator.  The newly formed BasicBlock is returned.
293   /// This function invalidates the specified iterator.
294   ///
295   /// Note that this only works on well formed basic blocks (must have a
296   /// terminator), and 'I' must not be the end of instruction list (which would
297   /// cause a degenerate basic block to be formed, having a terminator inside of
298   /// the basic block).
299   ///
300   /// Also note that this doesn't preserve any passes. To split blocks while
301   /// keeping loop information consistent, use the SplitBlock utility function.
302   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
303
304   /// \brief Returns true if there are any uses of this basic block other than
305   /// direct branches, switches, etc. to it.
306   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
307
308   /// \brief Update all phi nodes in this basic block's successors to refer to
309   /// basic block \p New instead of to it.
310   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
311
312   /// \brief Return true if this basic block is an exception handling block.
313   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
314
315   /// \brief Return true if this basic block is a landing pad.
316   ///
317   /// Being a ``landing pad'' means that the basic block is the destination of
318   /// the 'unwind' edge of an invoke instruction.
319   bool isLandingPad() const;
320
321   /// \brief Return the landingpad instruction associated with the landing pad.
322   LandingPadInst *getLandingPadInst();
323   const LandingPadInst *getLandingPadInst() const;
324
325 private:
326   /// \brief Increment the internal refcount of the number of BlockAddresses
327   /// referencing this BasicBlock by \p Amt.
328   ///
329   /// This is almost always 0, sometimes one possibly, but almost never 2, and
330   /// inconceivably 3 or more.
331   void AdjustBlockAddressRefCount(int Amt) {
332     setValueSubclassData(getSubclassDataFromValue()+Amt);
333     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
334            "Refcount wrap-around");
335   }
336   /// \brief Shadow Value::setValueSubclassData with a private forwarding method
337   /// so that any future subclasses cannot accidentally use it.
338   void setValueSubclassData(unsigned short D) {
339     Value::setValueSubclassData(D);
340   }
341 };
342
343 // createSentinel is used to get hold of the node that marks the end of the
344 // list... (same trick used here as in ilist_traits<Instruction>)
345 inline BasicBlock *ilist_traits<BasicBlock>::createSentinel() const {
346     return static_cast<BasicBlock*>(&Sentinel);
347 }
348
349 // Create wrappers for C Binding types (see CBindingWrapping.h).
350 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
351
352 } // End llvm namespace
353
354 #endif