Cache the fairly expensive last split point computation and provide a fast
[oota-llvm.git] / include / llvm / CodeGen / MachineBasicBlock.h
1 //===-- llvm/CodeGen/MachineBasicBlock.h ------------------------*- 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 // Collect the sequence of machine instructions for a basic block.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
15 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
16
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/ADT/GraphTraits.h"
19 #include <functional>
20
21 namespace llvm {
22
23 class Pass;
24 class BasicBlock;
25 class MachineFunction;
26 class MCSymbol;
27 class SlotIndexes;
28 class StringRef;
29 class raw_ostream;
30
31 template <>
32 struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
33 private:
34   mutable ilist_half_node<MachineInstr> Sentinel;
35
36   // this is only set by the MachineBasicBlock owning the LiveList
37   friend class MachineBasicBlock;
38   MachineBasicBlock* Parent;
39
40 public:
41   MachineInstr *createSentinel() const {
42     return static_cast<MachineInstr*>(&Sentinel);
43   }
44   void destroySentinel(MachineInstr *) const {}
45
46   MachineInstr *provideInitialHead() const { return createSentinel(); }
47   MachineInstr *ensureHead(MachineInstr*) const { return createSentinel(); }
48   static void noteHead(MachineInstr*, MachineInstr*) {}
49
50   void addNodeToList(MachineInstr* N);
51   void removeNodeFromList(MachineInstr* N);
52   void transferNodesFromList(ilist_traits &SrcTraits,
53                              ilist_iterator<MachineInstr> first,
54                              ilist_iterator<MachineInstr> last);
55   void deleteNode(MachineInstr *N);
56 private:
57   void createNode(const MachineInstr &);
58 };
59
60 class MachineBasicBlock : public ilist_node<MachineBasicBlock> {
61   typedef ilist<MachineInstr> Instructions;
62   Instructions Insts;
63   const BasicBlock *BB;
64   int Number;
65   MachineFunction *xParent;
66   
67   /// Predecessors/Successors - Keep track of the predecessor / successor
68   /// basicblocks.
69   std::vector<MachineBasicBlock *> Predecessors;
70   std::vector<MachineBasicBlock *> Successors;
71
72   /// LiveIns - Keep track of the physical registers that are livein of
73   /// the basicblock.
74   std::vector<unsigned> LiveIns;
75
76   /// Alignment - Alignment of the basic block. Zero if the basic block does
77   /// not need to be aligned.
78   unsigned Alignment;
79   
80   /// IsLandingPad - Indicate that this basic block is entered via an
81   /// exception handler.
82   bool IsLandingPad;
83
84   /// AddressTaken - Indicate that this basic block is potentially the
85   /// target of an indirect branch.
86   bool AddressTaken;
87
88   // Intrusive list support
89   MachineBasicBlock() {}
90
91   explicit MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb);
92
93   ~MachineBasicBlock();
94
95   // MachineBasicBlocks are allocated and owned by MachineFunction.
96   friend class MachineFunction;
97
98 public:
99   /// getBasicBlock - Return the LLVM basic block that this instance
100   /// corresponded to originally. Note that this may be NULL if this instance
101   /// does not correspond directly to an LLVM basic block.
102   ///
103   const BasicBlock *getBasicBlock() const { return BB; }
104
105   /// getName - Return the name of the corresponding LLVM basic block, or
106   /// "(null)".
107   StringRef getName() const;
108
109   /// hasAddressTaken - Test whether this block is potentially the target
110   /// of an indirect branch.
111   bool hasAddressTaken() const { return AddressTaken; }
112
113   /// setHasAddressTaken - Set this block to reflect that it potentially
114   /// is the target of an indirect branch.
115   void setHasAddressTaken() { AddressTaken = true; }
116
117   /// getParent - Return the MachineFunction containing this basic block.
118   ///
119   const MachineFunction *getParent() const { return xParent; }
120   MachineFunction *getParent() { return xParent; }
121
122   typedef Instructions::iterator                              iterator;
123   typedef Instructions::const_iterator                  const_iterator;
124   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
125   typedef std::reverse_iterator<iterator>             reverse_iterator;
126
127   unsigned size() const { return (unsigned)Insts.size(); }
128   bool empty() const { return Insts.empty(); }
129
130   MachineInstr& front() { return Insts.front(); }
131   MachineInstr& back()  { return Insts.back(); }
132   const MachineInstr& front() const { return Insts.front(); }
133   const MachineInstr& back()  const { return Insts.back(); }
134
135   iterator                begin()       { return Insts.begin();  }
136   const_iterator          begin() const { return Insts.begin();  }
137   iterator                  end()       { return Insts.end();    }
138   const_iterator            end() const { return Insts.end();    }
139   reverse_iterator       rbegin()       { return Insts.rbegin(); }
140   const_reverse_iterator rbegin() const { return Insts.rbegin(); }
141   reverse_iterator       rend  ()       { return Insts.rend();   }
142   const_reverse_iterator rend  () const { return Insts.rend();   }
143
144   // Machine-CFG iterators
145   typedef std::vector<MachineBasicBlock *>::iterator       pred_iterator;
146   typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
147   typedef std::vector<MachineBasicBlock *>::iterator       succ_iterator;
148   typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
149   typedef std::vector<MachineBasicBlock *>::reverse_iterator
150                                                          pred_reverse_iterator;
151   typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
152                                                    const_pred_reverse_iterator;
153   typedef std::vector<MachineBasicBlock *>::reverse_iterator
154                                                          succ_reverse_iterator;
155   typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
156                                                    const_succ_reverse_iterator;
157
158   pred_iterator        pred_begin()       { return Predecessors.begin(); }
159   const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
160   pred_iterator        pred_end()         { return Predecessors.end();   }
161   const_pred_iterator  pred_end()   const { return Predecessors.end();   }
162   pred_reverse_iterator        pred_rbegin()
163                                           { return Predecessors.rbegin();}
164   const_pred_reverse_iterator  pred_rbegin() const
165                                           { return Predecessors.rbegin();}
166   pred_reverse_iterator        pred_rend()
167                                           { return Predecessors.rend();  }
168   const_pred_reverse_iterator  pred_rend()   const
169                                           { return Predecessors.rend();  }
170   unsigned             pred_size()  const {
171     return (unsigned)Predecessors.size();
172   }
173   bool                 pred_empty() const { return Predecessors.empty(); }
174   succ_iterator        succ_begin()       { return Successors.begin();   }
175   const_succ_iterator  succ_begin() const { return Successors.begin();   }
176   succ_iterator        succ_end()         { return Successors.end();     }
177   const_succ_iterator  succ_end()   const { return Successors.end();     }
178   succ_reverse_iterator        succ_rbegin()
179                                           { return Successors.rbegin();  }
180   const_succ_reverse_iterator  succ_rbegin() const
181                                           { return Successors.rbegin();  }
182   succ_reverse_iterator        succ_rend()
183                                           { return Successors.rend();    }
184   const_succ_reverse_iterator  succ_rend()   const
185                                           { return Successors.rend();    }
186   unsigned             succ_size()  const {
187     return (unsigned)Successors.size();
188   }
189   bool                 succ_empty() const { return Successors.empty();   }
190
191   // LiveIn management methods.
192
193   /// addLiveIn - Add the specified register as a live in.  Note that it
194   /// is an error to add the same register to the same set more than once.
195   void addLiveIn(unsigned Reg)  { LiveIns.push_back(Reg); }
196
197   /// removeLiveIn - Remove the specified register from the live in set.
198   ///
199   void removeLiveIn(unsigned Reg);
200
201   /// isLiveIn - Return true if the specified register is in the live in set.
202   ///
203   bool isLiveIn(unsigned Reg) const;
204
205   // Iteration support for live in sets.  These sets are kept in sorted
206   // order by their register number.
207   typedef std::vector<unsigned>::const_iterator livein_iterator;
208   livein_iterator livein_begin() const { return LiveIns.begin(); }
209   livein_iterator livein_end()   const { return LiveIns.end(); }
210   bool            livein_empty() const { return LiveIns.empty(); }
211
212   /// getAlignment - Return alignment of the basic block.
213   ///
214   unsigned getAlignment() const { return Alignment; }
215
216   /// setAlignment - Set alignment of the basic block.
217   ///
218   void setAlignment(unsigned Align) { Alignment = Align; }
219
220   /// isLandingPad - Returns true if the block is a landing pad. That is
221   /// this basic block is entered via an exception handler.
222   bool isLandingPad() const { return IsLandingPad; }
223
224   /// setIsLandingPad - Indicates the block is a landing pad.  That is
225   /// this basic block is entered via an exception handler.
226   void setIsLandingPad() { IsLandingPad = true; }
227
228   /// getLandingPadSuccessor - If this block has a successor that is a landing
229   /// pad, return it. Otherwise return NULL.
230   const MachineBasicBlock *getLandingPadSuccessor() const;
231
232   // Code Layout methods.
233   
234   /// moveBefore/moveAfter - move 'this' block before or after the specified
235   /// block.  This only moves the block, it does not modify the CFG or adjust
236   /// potential fall-throughs at the end of the block.
237   void moveBefore(MachineBasicBlock *NewAfter);
238   void moveAfter(MachineBasicBlock *NewBefore);
239
240   /// updateTerminator - Update the terminator instructions in block to account
241   /// for changes to the layout. If the block previously used a fallthrough,
242   /// it may now need a branch, and if it previously used branching it may now
243   /// be able to use a fallthrough.
244   void updateTerminator();
245
246   // Machine-CFG mutators
247   
248   /// addSuccessor - Add succ as a successor of this MachineBasicBlock.
249   /// The Predecessors list of succ is automatically updated.
250   ///
251   void addSuccessor(MachineBasicBlock *succ);
252
253   /// removeSuccessor - Remove successor from the successors list of this
254   /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
255   ///
256   void removeSuccessor(MachineBasicBlock *succ);
257
258   /// removeSuccessor - Remove specified successor from the successors list of
259   /// this MachineBasicBlock. The Predecessors list of succ is automatically
260   /// updated.  Return the iterator to the element after the one removed.
261   ///
262   succ_iterator removeSuccessor(succ_iterator I);
263   
264   /// transferSuccessors - Transfers all the successors from MBB to this
265   /// machine basic block (i.e., copies all the successors fromMBB and
266   /// remove all the successors from fromMBB).
267   void transferSuccessors(MachineBasicBlock *fromMBB);
268
269   /// transferSuccessorsAndUpdatePHIs - Transfers all the successors, as
270   /// in transferSuccessors, and update PHI operands in the successor blocks
271   /// which refer to fromMBB to refer to this.
272   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
273   
274   /// isSuccessor - Return true if the specified MBB is a successor of this
275   /// block.
276   bool isSuccessor(const MachineBasicBlock *MBB) const;
277
278   /// isLayoutSuccessor - Return true if the specified MBB will be emitted
279   /// immediately after this block, such that if this block exits by
280   /// falling through, control will transfer to the specified MBB. Note
281   /// that MBB need not be a successor at all, for example if this block
282   /// ends with an unconditional branch to some other block.
283   bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
284
285   /// canFallThrough - Return true if the block can implicitly transfer
286   /// control to the block after it by falling off the end of it.  This should
287   /// return false if it can reach the block after it, but it uses an explicit
288   /// branch to do so (e.g., a table jump).  True is a conservative answer.
289   bool canFallThrough();
290
291   /// Returns a pointer to the first instructon in this block that is not a 
292   /// PHINode instruction. When adding instruction to the beginning of the
293   /// basic block, they should be added before the returned value, not before
294   /// the first instruction, which might be PHI.
295   /// Returns end() is there's no non-PHI instruction.
296   iterator getFirstNonPHI();
297
298   /// SkipPHIsAndLabels - Return the first instruction in MBB after I that is
299   /// not a PHI or a label. This is the correct point to insert copies at the
300   /// beginning of a basic block.
301   iterator SkipPHIsAndLabels(iterator I);
302
303   /// getFirstTerminator - returns an iterator to the first terminator
304   /// instruction of this basic block. If a terminator does not exist,
305   /// it returns end()
306   iterator getFirstTerminator();
307
308   const_iterator getFirstTerminator() const {
309     return const_cast<MachineBasicBlock*>(this)->getFirstTerminator();
310   }
311
312   /// getLastNonDebugInstr - returns an iterator to the last non-debug
313   /// instruction in the basic block, or end()
314   iterator getLastNonDebugInstr();
315
316   const_iterator getLastNonDebugInstr() const {
317     return const_cast<MachineBasicBlock*>(this)->getLastNonDebugInstr();
318   }
319
320   /// SplitCriticalEdge - Split the critical edge from this block to the
321   /// given successor block, and return the newly created block, or null
322   /// if splitting is not possible.
323   ///
324   /// This function updates LiveVariables, MachineDominatorTree, and
325   /// MachineLoopInfo, as applicable.
326   MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
327
328   void pop_front() { Insts.pop_front(); }
329   void pop_back() { Insts.pop_back(); }
330   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
331   template<typename IT>
332   void insert(iterator I, IT S, IT E) { Insts.insert(I, S, E); }
333   iterator insert(iterator I, MachineInstr *M) { return Insts.insert(I, M); }
334   iterator insertAfter(iterator I, MachineInstr *M) { 
335     return Insts.insertAfter(I, M); 
336   }
337
338   // erase - Remove the specified element or range from the instruction list.
339   // These functions delete any instructions removed.
340   //
341   iterator erase(iterator I)             { return Insts.erase(I); }
342   iterator erase(iterator I, iterator E) { return Insts.erase(I, E); }
343   MachineInstr *remove(MachineInstr *I)  { return Insts.remove(I); }
344   void clear()                           { Insts.clear(); }
345
346   /// splice - Take an instruction from MBB 'Other' at the position From,
347   /// and insert it into this MBB right before 'where'.
348   void splice(iterator where, MachineBasicBlock *Other, iterator From) {
349     Insts.splice(where, Other->Insts, From);
350   }
351
352   /// splice - Take a block of instructions from MBB 'Other' in the range [From,
353   /// To), and insert them into this MBB right before 'where'.
354   void splice(iterator where, MachineBasicBlock *Other, iterator From,
355               iterator To) {
356     Insts.splice(where, Other->Insts, From, To);
357   }
358
359   /// removeFromParent - This method unlinks 'this' from the containing
360   /// function, and returns it, but does not delete it.
361   MachineBasicBlock *removeFromParent();
362   
363   /// eraseFromParent - This method unlinks 'this' from the containing
364   /// function and deletes it.
365   void eraseFromParent();
366
367   /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
368   /// 'Old', change the code and CFG so that it branches to 'New' instead.
369   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
370
371   /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
372   /// the CFG to be inserted.  If we have proven that MBB can only branch to
373   /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
374   /// DestB can be null. Besides DestA and DestB, retain other edges leading
375   /// to LandingPads (currently there can be only one; we don't check or require
376   /// that here). Note it is possible that DestA and/or DestB are LandingPads.
377   bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
378                             MachineBasicBlock *DestB,
379                             bool isCond);
380
381   /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
382   /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
383   DebugLoc findDebugLoc(MachineBasicBlock::iterator &MBBI);
384
385   // Debugging methods.
386   void dump() const;
387   void print(raw_ostream &OS, SlotIndexes* = 0) const;
388
389   /// getNumber - MachineBasicBlocks are uniquely numbered at the function
390   /// level, unless they're not in a MachineFunction yet, in which case this
391   /// will return -1.
392   ///
393   int getNumber() const { return Number; }
394   void setNumber(int N) { Number = N; }
395
396   /// getSymbol - Return the MCSymbol for this basic block.
397   ///
398   MCSymbol *getSymbol() const;
399   
400 private:   // Methods used to maintain doubly linked list of blocks...
401   friend struct ilist_traits<MachineBasicBlock>;
402
403   // Machine-CFG mutators
404
405   /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
406   /// Don't do this unless you know what you're doing, because it doesn't
407   /// update pred's successors list. Use pred->addSuccessor instead.
408   ///
409   void addPredecessor(MachineBasicBlock *pred);
410
411   /// removePredecessor - Remove pred as a predecessor of this
412   /// MachineBasicBlock. Don't do this unless you know what you're
413   /// doing, because it doesn't update pred's successors list. Use
414   /// pred->removeSuccessor instead.
415   ///
416   void removePredecessor(MachineBasicBlock *pred);
417 };
418
419 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
420
421 void WriteAsOperand(raw_ostream &, const MachineBasicBlock*, bool t);
422
423 // This is useful when building IndexedMaps keyed on basic block pointers.
424 struct MBB2NumberFunctor :
425   public std::unary_function<const MachineBasicBlock*, unsigned> {
426   unsigned operator()(const MachineBasicBlock *MBB) const {
427     return MBB->getNumber();
428   }
429 };
430
431 //===--------------------------------------------------------------------===//
432 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
433 //===--------------------------------------------------------------------===//
434
435 // Provide specializations of GraphTraits to be able to treat a
436 // MachineFunction as a graph of MachineBasicBlocks...
437 //
438
439 template <> struct GraphTraits<MachineBasicBlock *> {
440   typedef MachineBasicBlock NodeType;
441   typedef MachineBasicBlock::succ_iterator ChildIteratorType;
442
443   static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
444   static inline ChildIteratorType child_begin(NodeType *N) {
445     return N->succ_begin();
446   }
447   static inline ChildIteratorType child_end(NodeType *N) {
448     return N->succ_end();
449   }
450 };
451
452 template <> struct GraphTraits<const MachineBasicBlock *> {
453   typedef const MachineBasicBlock NodeType;
454   typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
455
456   static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
457   static inline ChildIteratorType child_begin(NodeType *N) {
458     return N->succ_begin();
459   }
460   static inline ChildIteratorType child_end(NodeType *N) {
461     return N->succ_end();
462   }
463 };
464
465 // Provide specializations of GraphTraits to be able to treat a
466 // MachineFunction as a graph of MachineBasicBlocks... and to walk it
467 // in inverse order.  Inverse order for a function is considered
468 // to be when traversing the predecessor edges of a MBB
469 // instead of the successor edges.
470 //
471 template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
472   typedef MachineBasicBlock NodeType;
473   typedef MachineBasicBlock::pred_iterator ChildIteratorType;
474   static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
475     return G.Graph;
476   }
477   static inline ChildIteratorType child_begin(NodeType *N) {
478     return N->pred_begin();
479   }
480   static inline ChildIteratorType child_end(NodeType *N) {
481     return N->pred_end();
482   }
483 };
484
485 template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
486   typedef const MachineBasicBlock NodeType;
487   typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
488   static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
489     return G.Graph;
490   }
491   static inline ChildIteratorType child_begin(NodeType *N) {
492     return N->pred_begin();
493   }
494   static inline ChildIteratorType child_end(NodeType *N) {
495     return N->pred_end();
496   }
497 };
498
499 } // End llvm namespace
500
501 #endif