Collect and coalesce DBG_VALUE instructions before emitting the function.
[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   /// getLastNonDebugInstr - returns an iterator to the last non-debug
309   /// instruction in the basic block, or end()
310   iterator getLastNonDebugInstr();
311
312   const_iterator getLastNonDebugInstr() const {
313     return const_cast<MachineBasicBlock*>(this)->getLastNonDebugInstr();
314   }
315
316   /// SplitCriticalEdge - Split the critical edge from this block to the
317   /// given successor block, and return the newly created block, or null
318   /// if splitting is not possible.
319   ///
320   /// This function updates LiveVariables, MachineDominatorTree, and
321   /// MachineLoopInfo, as applicable.
322   MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
323
324   void pop_front() { Insts.pop_front(); }
325   void pop_back() { Insts.pop_back(); }
326   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
327   template<typename IT>
328   void insert(iterator I, IT S, IT E) { Insts.insert(I, S, E); }
329   iterator insert(iterator I, MachineInstr *M) { return Insts.insert(I, M); }
330   iterator insertAfter(iterator I, MachineInstr *M) { 
331     return Insts.insertAfter(I, M); 
332   }
333
334   // erase - Remove the specified element or range from the instruction list.
335   // These functions delete any instructions removed.
336   //
337   iterator erase(iterator I)             { return Insts.erase(I); }
338   iterator erase(iterator I, iterator E) { return Insts.erase(I, E); }
339   MachineInstr *remove(MachineInstr *I)  { return Insts.remove(I); }
340   void clear()                           { Insts.clear(); }
341
342   /// splice - Take an instruction from MBB 'Other' at the position From,
343   /// and insert it into this MBB right before 'where'.
344   void splice(iterator where, MachineBasicBlock *Other, iterator From) {
345     Insts.splice(where, Other->Insts, From);
346   }
347
348   /// splice - Take a block of instructions from MBB 'Other' in the range [From,
349   /// To), and insert them into this MBB right before 'where'.
350   void splice(iterator where, MachineBasicBlock *Other, iterator From,
351               iterator To) {
352     Insts.splice(where, Other->Insts, From, To);
353   }
354
355   /// removeFromParent - This method unlinks 'this' from the containing
356   /// function, and returns it, but does not delete it.
357   MachineBasicBlock *removeFromParent();
358   
359   /// eraseFromParent - This method unlinks 'this' from the containing
360   /// function and deletes it.
361   void eraseFromParent();
362
363   /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
364   /// 'Old', change the code and CFG so that it branches to 'New' instead.
365   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
366
367   /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
368   /// the CFG to be inserted.  If we have proven that MBB can only branch to
369   /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
370   /// DestB can be null. Besides DestA and DestB, retain other edges leading
371   /// to LandingPads (currently there can be only one; we don't check or require
372   /// that here). Note it is possible that DestA and/or DestB are LandingPads.
373   bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
374                             MachineBasicBlock *DestB,
375                             bool isCond);
376
377   /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
378   /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
379   DebugLoc findDebugLoc(MachineBasicBlock::iterator &MBBI);
380
381   // Debugging methods.
382   void dump() const;
383   void print(raw_ostream &OS, SlotIndexes* = 0) const;
384
385   /// getNumber - MachineBasicBlocks are uniquely numbered at the function
386   /// level, unless they're not in a MachineFunction yet, in which case this
387   /// will return -1.
388   ///
389   int getNumber() const { return Number; }
390   void setNumber(int N) { Number = N; }
391
392   /// getSymbol - Return the MCSymbol for this basic block.
393   ///
394   MCSymbol *getSymbol() const;
395   
396 private:   // Methods used to maintain doubly linked list of blocks...
397   friend struct ilist_traits<MachineBasicBlock>;
398
399   // Machine-CFG mutators
400
401   /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
402   /// Don't do this unless you know what you're doing, because it doesn't
403   /// update pred's successors list. Use pred->addSuccessor instead.
404   ///
405   void addPredecessor(MachineBasicBlock *pred);
406
407   /// removePredecessor - Remove pred as a predecessor of this
408   /// MachineBasicBlock. Don't do this unless you know what you're
409   /// doing, because it doesn't update pred's successors list. Use
410   /// pred->removeSuccessor instead.
411   ///
412   void removePredecessor(MachineBasicBlock *pred);
413 };
414
415 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
416
417 void WriteAsOperand(raw_ostream &, const MachineBasicBlock*, bool t);
418
419 // This is useful when building IndexedMaps keyed on basic block pointers.
420 struct MBB2NumberFunctor :
421   public std::unary_function<const MachineBasicBlock*, unsigned> {
422   unsigned operator()(const MachineBasicBlock *MBB) const {
423     return MBB->getNumber();
424   }
425 };
426
427 //===--------------------------------------------------------------------===//
428 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
429 //===--------------------------------------------------------------------===//
430
431 // Provide specializations of GraphTraits to be able to treat a
432 // MachineFunction as a graph of MachineBasicBlocks...
433 //
434
435 template <> struct GraphTraits<MachineBasicBlock *> {
436   typedef MachineBasicBlock NodeType;
437   typedef MachineBasicBlock::succ_iterator ChildIteratorType;
438
439   static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
440   static inline ChildIteratorType child_begin(NodeType *N) {
441     return N->succ_begin();
442   }
443   static inline ChildIteratorType child_end(NodeType *N) {
444     return N->succ_end();
445   }
446 };
447
448 template <> struct GraphTraits<const MachineBasicBlock *> {
449   typedef const MachineBasicBlock NodeType;
450   typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
451
452   static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
453   static inline ChildIteratorType child_begin(NodeType *N) {
454     return N->succ_begin();
455   }
456   static inline ChildIteratorType child_end(NodeType *N) {
457     return N->succ_end();
458   }
459 };
460
461 // Provide specializations of GraphTraits to be able to treat a
462 // MachineFunction as a graph of MachineBasicBlocks... and to walk it
463 // in inverse order.  Inverse order for a function is considered
464 // to be when traversing the predecessor edges of a MBB
465 // instead of the successor edges.
466 //
467 template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
468   typedef MachineBasicBlock NodeType;
469   typedef MachineBasicBlock::pred_iterator ChildIteratorType;
470   static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
471     return G.Graph;
472   }
473   static inline ChildIteratorType child_begin(NodeType *N) {
474     return N->pred_begin();
475   }
476   static inline ChildIteratorType child_end(NodeType *N) {
477     return N->pred_end();
478   }
479 };
480
481 template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
482   typedef const MachineBasicBlock NodeType;
483   typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
484   static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
485     return G.Graph;
486   }
487   static inline ChildIteratorType child_begin(NodeType *N) {
488     return N->pred_begin();
489   }
490   static inline ChildIteratorType child_end(NodeType *N) {
491     return N->pred_end();
492   }
493 };
494
495 } // End llvm namespace
496
497 #endif