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