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