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