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