Changes for MachineBasicBlock to use SortedVector for LiveIns.
[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/ADT/SortedVector.h"
18 #include "llvm/ADT/GraphTraits.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Support/DataTypes.h"
21 #include <functional>
22
23 namespace llvm {
24
25 class Pass;
26 class BasicBlock;
27 class MachineFunction;
28 class MCSymbol;
29 class SlotIndexes;
30 class StringRef;
31 class raw_ostream;
32 class MachineBranchProbabilityInfo;
33
34 template <>
35 struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
36 private:
37   mutable ilist_half_node<MachineInstr> Sentinel;
38
39   // this is only set by the MachineBasicBlock owning the LiveList
40   friend class MachineBasicBlock;
41   MachineBasicBlock* Parent;
42
43 public:
44   MachineInstr *createSentinel() const {
45     return static_cast<MachineInstr*>(&Sentinel);
46   }
47   void destroySentinel(MachineInstr *) const {}
48
49   MachineInstr *provideInitialHead() const { return createSentinel(); }
50   MachineInstr *ensureHead(MachineInstr*) const { return createSentinel(); }
51   static void noteHead(MachineInstr*, MachineInstr*) {}
52
53   void addNodeToList(MachineInstr* N);
54   void removeNodeFromList(MachineInstr* N);
55   void transferNodesFromList(ilist_traits &SrcTraits,
56                              ilist_iterator<MachineInstr> first,
57                              ilist_iterator<MachineInstr> last);
58   void deleteNode(MachineInstr *N);
59 private:
60   void createNode(const MachineInstr &);
61 };
62
63 class MachineBasicBlock : public ilist_node<MachineBasicBlock> {
64   typedef ilist<MachineInstr> Instructions;
65   Instructions Insts;
66   const BasicBlock *BB;
67   int Number;
68   MachineFunction *xParent;
69
70   /// Predecessors/Successors - Keep track of the predecessor / successor
71   /// basicblocks.
72   std::vector<MachineBasicBlock *> Predecessors;
73   std::vector<MachineBasicBlock *> Successors;
74
75   /// Weights - Keep track of the weights to the successors. This vector
76   /// has the same order as Successors, or it is empty if we don't use it
77   /// (disable optimization).
78   std::vector<uint32_t> Weights;
79   typedef std::vector<uint32_t>::iterator weight_iterator;
80   typedef std::vector<uint32_t>::const_iterator const_weight_iterator;
81
82   /// LiveIns - Keep track of the physical registers that are livein of
83   /// the basicblock.
84   mutable SortedVector<unsigned> LiveIns;
85
86   /// Alignment - Alignment of the basic block. Zero if the basic block does
87   /// not need to be aligned.
88   /// The alignment is specified as log2(bytes).
89   unsigned Alignment;
90
91   /// IsLandingPad - Indicate that this basic block is entered via an
92   /// exception handler.
93   bool IsLandingPad;
94
95   /// AddressTaken - Indicate that this basic block is potentially the
96   /// target of an indirect branch.
97   bool AddressTaken;
98
99   /// \brief since getSymbol is a relatively heavy-weight operation, the symbol
100   /// is only computed once and is cached.
101   mutable MCSymbol *CachedMCSymbol;
102
103   // Intrusive list support
104   MachineBasicBlock() {}
105
106   explicit MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb);
107
108   ~MachineBasicBlock();
109
110   // MachineBasicBlocks are allocated and owned by MachineFunction.
111   friend class MachineFunction;
112
113 public:
114   /// getBasicBlock - Return the LLVM basic block that this instance
115   /// corresponded to originally. Note that this may be NULL if this instance
116   /// does not correspond directly to an LLVM basic block.
117   ///
118   const BasicBlock *getBasicBlock() const { return BB; }
119
120   /// getName - Return the name of the corresponding LLVM basic block, or
121   /// "(null)".
122   StringRef getName() const;
123
124   /// getFullName - Return a formatted string to identify this block and its
125   /// parent function.
126   std::string getFullName() const;
127
128   /// hasAddressTaken - Test whether this block is potentially the target
129   /// of an indirect branch.
130   bool hasAddressTaken() const { return AddressTaken; }
131
132   /// setHasAddressTaken - Set this block to reflect that it potentially
133   /// is the target of an indirect branch.
134   void setHasAddressTaken() { AddressTaken = true; }
135
136   /// getParent - Return the MachineFunction containing this basic block.
137   ///
138   const MachineFunction *getParent() const { return xParent; }
139   MachineFunction *getParent() { return xParent; }
140
141
142   /// bundle_iterator - MachineBasicBlock iterator that automatically skips over
143   /// MIs that are inside bundles (i.e. walk top level MIs only).
144   template<typename Ty, typename IterTy>
145   class bundle_iterator
146     : public std::iterator<std::bidirectional_iterator_tag, Ty, ptrdiff_t> {
147     IterTy MII;
148
149   public:
150     bundle_iterator(IterTy mii) : MII(mii) {}
151
152     bundle_iterator(Ty &mi) : MII(mi) {
153       assert(!mi.isBundledWithPred() &&
154              "It's not legal to initialize bundle_iterator with a bundled MI");
155     }
156     bundle_iterator(Ty *mi) : MII(mi) {
157       assert((!mi || !mi->isBundledWithPred()) &&
158              "It's not legal to initialize bundle_iterator with a bundled MI");
159     }
160     // Template allows conversion from const to nonconst.
161     template<class OtherTy, class OtherIterTy>
162     bundle_iterator(const bundle_iterator<OtherTy, OtherIterTy> &I)
163       : MII(I.getInstrIterator()) {}
164     bundle_iterator() : MII(nullptr) {}
165
166     Ty &operator*() const { return *MII; }
167     Ty *operator->() const { return &operator*(); }
168
169     operator Ty*() const { return MII; }
170
171     bool operator==(const bundle_iterator &x) const {
172       return MII == x.MII;
173     }
174     bool operator!=(const bundle_iterator &x) const {
175       return !operator==(x);
176     }
177
178     // Increment and decrement operators...
179     bundle_iterator &operator--() {      // predecrement - Back up
180       do --MII;
181       while (MII->isBundledWithPred());
182       return *this;
183     }
184     bundle_iterator &operator++() {      // preincrement - Advance
185       while (MII->isBundledWithSucc())
186         ++MII;
187       ++MII;
188       return *this;
189     }
190     bundle_iterator operator--(int) {    // postdecrement operators...
191       bundle_iterator tmp = *this;
192       --*this;
193       return tmp;
194     }
195     bundle_iterator operator++(int) {    // postincrement operators...
196       bundle_iterator tmp = *this;
197       ++*this;
198       return tmp;
199     }
200
201     IterTy getInstrIterator() const {
202       return MII;
203     }
204   };
205
206   typedef Instructions::iterator                                 instr_iterator;
207   typedef Instructions::const_iterator                     const_instr_iterator;
208   typedef std::reverse_iterator<instr_iterator>          reverse_instr_iterator;
209   typedef
210   std::reverse_iterator<const_instr_iterator>      const_reverse_instr_iterator;
211
212   typedef
213   bundle_iterator<MachineInstr,instr_iterator>                         iterator;
214   typedef
215   bundle_iterator<const MachineInstr,const_instr_iterator>       const_iterator;
216   typedef std::reverse_iterator<const_iterator>          const_reverse_iterator;
217   typedef std::reverse_iterator<iterator>                      reverse_iterator;
218
219
220   unsigned size() const { return (unsigned)Insts.size(); }
221   bool empty() const { return Insts.empty(); }
222
223   MachineInstr       &instr_front()       { return Insts.front(); }
224   MachineInstr       &instr_back()        { return Insts.back();  }
225   const MachineInstr &instr_front() const { return Insts.front(); }
226   const MachineInstr &instr_back()  const { return Insts.back();  }
227
228   MachineInstr       &front()             { return Insts.front(); }
229   MachineInstr       &back()              { return *--end();      }
230   const MachineInstr &front()       const { return Insts.front(); }
231   const MachineInstr &back()        const { return *--end();      }
232
233   instr_iterator                instr_begin()       { return Insts.begin();  }
234   const_instr_iterator          instr_begin() const { return Insts.begin();  }
235   instr_iterator                  instr_end()       { return Insts.end();    }
236   const_instr_iterator            instr_end() const { return Insts.end();    }
237   reverse_instr_iterator       instr_rbegin()       { return Insts.rbegin(); }
238   const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
239   reverse_instr_iterator       instr_rend  ()       { return Insts.rend();   }
240   const_reverse_instr_iterator instr_rend  () const { return Insts.rend();   }
241
242   iterator                begin()       { return instr_begin();  }
243   const_iterator          begin() const { return instr_begin();  }
244   iterator                end  ()       { return instr_end();    }
245   const_iterator          end  () const { return instr_end();    }
246   reverse_iterator       rbegin()       { return instr_rbegin(); }
247   const_reverse_iterator rbegin() const { return instr_rbegin(); }
248   reverse_iterator       rend  ()       { return instr_rend();   }
249   const_reverse_iterator rend  () const { return instr_rend();   }
250
251   inline iterator_range<iterator> terminators() {
252     return iterator_range<iterator>(getFirstTerminator(), end());
253   }
254   inline iterator_range<const_iterator> terminators() const {
255     return iterator_range<const_iterator>(getFirstTerminator(), end());
256   }
257
258   // Machine-CFG iterators
259   typedef std::vector<MachineBasicBlock *>::iterator       pred_iterator;
260   typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
261   typedef std::vector<MachineBasicBlock *>::iterator       succ_iterator;
262   typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
263   typedef std::vector<MachineBasicBlock *>::reverse_iterator
264                                                          pred_reverse_iterator;
265   typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
266                                                    const_pred_reverse_iterator;
267   typedef std::vector<MachineBasicBlock *>::reverse_iterator
268                                                          succ_reverse_iterator;
269   typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
270                                                    const_succ_reverse_iterator;
271   pred_iterator        pred_begin()       { return Predecessors.begin(); }
272   const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
273   pred_iterator        pred_end()         { return Predecessors.end();   }
274   const_pred_iterator  pred_end()   const { return Predecessors.end();   }
275   pred_reverse_iterator        pred_rbegin()
276                                           { return Predecessors.rbegin();}
277   const_pred_reverse_iterator  pred_rbegin() const
278                                           { return Predecessors.rbegin();}
279   pred_reverse_iterator        pred_rend()
280                                           { return Predecessors.rend();  }
281   const_pred_reverse_iterator  pred_rend()   const
282                                           { return Predecessors.rend();  }
283   unsigned             pred_size()  const {
284     return (unsigned)Predecessors.size();
285   }
286   bool                 pred_empty() const { return Predecessors.empty(); }
287   succ_iterator        succ_begin()       { return Successors.begin();   }
288   const_succ_iterator  succ_begin() const { return Successors.begin();   }
289   succ_iterator        succ_end()         { return Successors.end();     }
290   const_succ_iterator  succ_end()   const { return Successors.end();     }
291   succ_reverse_iterator        succ_rbegin()
292                                           { return Successors.rbegin();  }
293   const_succ_reverse_iterator  succ_rbegin() const
294                                           { return Successors.rbegin();  }
295   succ_reverse_iterator        succ_rend()
296                                           { return Successors.rend();    }
297   const_succ_reverse_iterator  succ_rend()   const
298                                           { return Successors.rend();    }
299   unsigned             succ_size()  const {
300     return (unsigned)Successors.size();
301   }
302   bool                 succ_empty() const { return Successors.empty();   }
303
304   inline iterator_range<pred_iterator> predecessors() {
305     return iterator_range<pred_iterator>(pred_begin(), pred_end());
306   }
307   inline iterator_range<const_pred_iterator> predecessors() const {
308     return iterator_range<const_pred_iterator>(pred_begin(), pred_end());
309   }
310   inline iterator_range<succ_iterator> successors() {
311     return iterator_range<succ_iterator>(succ_begin(), succ_end());
312   }
313   inline iterator_range<const_succ_iterator> successors() const {
314     return iterator_range<const_succ_iterator>(succ_begin(), succ_end());
315   }
316
317   // LiveIn management methods.
318
319   /// Adds the specified register as a live in. Note that it is an error to add
320   /// the same register to the same set more than once unless the intention is
321   /// to call sortUniqueLiveIns after all registers are added.
322   void addLiveIn(unsigned Reg) { LiveIns.insert(Reg); }
323
324   /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
325   /// this than repeatedly calling isLiveIn before calling addLiveIn for every
326   /// LiveIn insertion.
327   void sortUniqueLiveIns() { LiveIns.sortUnique(); }
328
329   /// Add PhysReg as live in to this block, and ensure that there is a copy of
330   /// PhysReg to a virtual register of class RC. Return the virtual register
331   /// that is a copy of the live in PhysReg.
332   unsigned addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC);
333
334   /// removeLiveIn - Remove the specified register from the live in set.
335   ///
336   void removeLiveIn(unsigned Reg);
337
338   /// isLiveIn - Return true if the specified register is in the live in set.
339   ///
340   bool isLiveIn(unsigned Reg) const { return LiveIns.has(Reg); }
341
342   // Iteration support for live in sets.  These sets are kept in sorted
343   // order by their register number.
344   typedef std::vector<unsigned>::const_iterator livein_iterator;
345   bool            livein_empty() const { return LiveIns.empty(); }
346   livein_iterator livein_begin() const {
347     LiveIns.sortUnique();
348     return LiveIns.begin();
349   }
350   livein_iterator livein_end() const {
351     LiveIns.sortUnique();
352     return LiveIns.end();
353   }
354
355   /// getAlignment - Return alignment of the basic block.
356   /// The alignment is specified as log2(bytes).
357   ///
358   unsigned getAlignment() const { return Alignment; }
359
360   /// setAlignment - Set alignment of the basic block.
361   /// The alignment is specified as log2(bytes).
362   ///
363   void setAlignment(unsigned Align) { Alignment = Align; }
364
365   /// isLandingPad - Returns true if the block is a landing pad. That is
366   /// this basic block is entered via an exception handler.
367   bool isLandingPad() const { return IsLandingPad; }
368
369   /// setIsLandingPad - Indicates the block is a landing pad.  That is
370   /// this basic block is entered via an exception handler.
371   void setIsLandingPad(bool V = true) { IsLandingPad = V; }
372
373   /// getLandingPadSuccessor - If this block has a successor that is a landing
374   /// pad, return it. Otherwise return NULL.
375   const MachineBasicBlock *getLandingPadSuccessor() const;
376
377   // Code Layout methods.
378
379   /// moveBefore/moveAfter - move 'this' block before or after the specified
380   /// block.  This only moves the block, it does not modify the CFG or adjust
381   /// potential fall-throughs at the end of the block.
382   void moveBefore(MachineBasicBlock *NewAfter);
383   void moveAfter(MachineBasicBlock *NewBefore);
384
385   /// updateTerminator - Update the terminator instructions in block to account
386   /// for changes to the layout. If the block previously used a fallthrough,
387   /// it may now need a branch, and if it previously used branching it may now
388   /// be able to use a fallthrough.
389   void updateTerminator();
390
391   // Machine-CFG mutators
392
393   /// addSuccessor - Add succ as a successor of this MachineBasicBlock.
394   /// The Predecessors list of succ is automatically updated. WEIGHT
395   /// parameter is stored in Weights list and it may be used by
396   /// MachineBranchProbabilityInfo analysis to calculate branch probability.
397   ///
398   /// Note that duplicate Machine CFG edges are not allowed.
399   ///
400   void addSuccessor(MachineBasicBlock *succ, uint32_t weight = 0);
401
402   /// Set successor weight of a given iterator.
403   void setSuccWeight(succ_iterator I, uint32_t weight);
404
405   /// removeSuccessor - Remove successor from the successors list of this
406   /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
407   ///
408   void removeSuccessor(MachineBasicBlock *succ);
409
410   /// removeSuccessor - Remove specified successor from the successors list of
411   /// this MachineBasicBlock. The Predecessors list of succ is automatically
412   /// updated.  Return the iterator to the element after the one removed.
413   ///
414   succ_iterator removeSuccessor(succ_iterator I);
415
416   /// replaceSuccessor - Replace successor OLD with NEW and update weight info.
417   ///
418   void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
419
420
421   /// transferSuccessors - Transfers all the successors from MBB to this
422   /// machine basic block (i.e., copies all the successors fromMBB and
423   /// remove all the successors from fromMBB).
424   void transferSuccessors(MachineBasicBlock *fromMBB);
425
426   /// transferSuccessorsAndUpdatePHIs - Transfers all the successors, as
427   /// in transferSuccessors, and update PHI operands in the successor blocks
428   /// which refer to fromMBB to refer to this.
429   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
430
431   /// isPredecessor - Return true if the specified MBB is a predecessor of this
432   /// block.
433   bool isPredecessor(const MachineBasicBlock *MBB) const;
434
435   /// isSuccessor - Return true if the specified MBB is a successor of this
436   /// block.
437   bool isSuccessor(const MachineBasicBlock *MBB) const;
438
439   /// isLayoutSuccessor - Return true if the specified MBB will be emitted
440   /// immediately after this block, such that if this block exits by
441   /// falling through, control will transfer to the specified MBB. Note
442   /// that MBB need not be a successor at all, for example if this block
443   /// ends with an unconditional branch to some other block.
444   bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
445
446   /// canFallThrough - Return true if the block can implicitly transfer
447   /// control to the block after it by falling off the end of it.  This should
448   /// return false if it can reach the block after it, but it uses an explicit
449   /// branch to do so (e.g., a table jump).  True is a conservative answer.
450   bool canFallThrough();
451
452   /// Returns a pointer to the first instruction in this block that is not a
453   /// PHINode instruction. When adding instructions to the beginning of the
454   /// basic block, they should be added before the returned value, not before
455   /// the first instruction, which might be PHI.
456   /// Returns end() is there's no non-PHI instruction.
457   iterator getFirstNonPHI();
458
459   /// SkipPHIsAndLabels - Return the first instruction in MBB after I that is
460   /// not a PHI or a label. This is the correct point to insert copies at the
461   /// beginning of a basic block.
462   iterator SkipPHIsAndLabels(iterator I);
463
464   /// getFirstTerminator - returns an iterator to the first terminator
465   /// instruction of this basic block. If a terminator does not exist,
466   /// it returns end()
467   iterator getFirstTerminator();
468   const_iterator getFirstTerminator() const {
469     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
470   }
471
472   /// getFirstInstrTerminator - Same getFirstTerminator but it ignores bundles
473   /// and return an instr_iterator instead.
474   instr_iterator getFirstInstrTerminator();
475
476   /// getFirstNonDebugInstr - returns an iterator to the first non-debug
477   /// instruction in the basic block, or end()
478   iterator getFirstNonDebugInstr();
479   const_iterator getFirstNonDebugInstr() const {
480     return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
481   }
482
483   /// getLastNonDebugInstr - returns an iterator to the last non-debug
484   /// instruction in the basic block, or end()
485   iterator getLastNonDebugInstr();
486   const_iterator getLastNonDebugInstr() const {
487     return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
488   }
489
490   /// SplitCriticalEdge - Split the critical edge from this block to the
491   /// given successor block, and return the newly created block, or null
492   /// if splitting is not possible.
493   ///
494   /// This function updates LiveVariables, MachineDominatorTree, and
495   /// MachineLoopInfo, as applicable.
496   MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
497
498   void pop_front() { Insts.pop_front(); }
499   void pop_back() { Insts.pop_back(); }
500   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
501
502   /// Insert MI into the instruction list before I, possibly inside a bundle.
503   ///
504   /// If the insertion point is inside a bundle, MI will be added to the bundle,
505   /// otherwise MI will not be added to any bundle. That means this function
506   /// alone can't be used to prepend or append instructions to bundles. See
507   /// MIBundleBuilder::insert() for a more reliable way of doing that.
508   instr_iterator insert(instr_iterator I, MachineInstr *M);
509
510   /// Insert a range of instructions into the instruction list before I.
511   template<typename IT>
512   void insert(iterator I, IT S, IT E) {
513     assert((I == end() || I->getParent() == this) &&
514            "iterator points outside of basic block");
515     Insts.insert(I.getInstrIterator(), S, E);
516   }
517
518   /// Insert MI into the instruction list before I.
519   iterator insert(iterator I, MachineInstr *MI) {
520     assert((I == end() || I->getParent() == this) &&
521            "iterator points outside of basic block");
522     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
523            "Cannot insert instruction with bundle flags");
524     return Insts.insert(I.getInstrIterator(), MI);
525   }
526
527   /// Insert MI into the instruction list after I.
528   iterator insertAfter(iterator I, MachineInstr *MI) {
529     assert((I == end() || I->getParent() == this) &&
530            "iterator points outside of basic block");
531     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
532            "Cannot insert instruction with bundle flags");
533     return Insts.insertAfter(I.getInstrIterator(), MI);
534   }
535
536   /// Remove an instruction from the instruction list and delete it.
537   ///
538   /// If the instruction is part of a bundle, the other instructions in the
539   /// bundle will still be bundled after removing the single instruction.
540   instr_iterator erase(instr_iterator I);
541
542   /// Remove an instruction from the instruction list and delete it.
543   ///
544   /// If the instruction is part of a bundle, the other instructions in the
545   /// bundle will still be bundled after removing the single instruction.
546   instr_iterator erase_instr(MachineInstr *I) {
547     return erase(instr_iterator(I));
548   }
549
550   /// Remove a range of instructions from the instruction list and delete them.
551   iterator erase(iterator I, iterator E) {
552     return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
553   }
554
555   /// Remove an instruction or bundle from the instruction list and delete it.
556   ///
557   /// If I points to a bundle of instructions, they are all erased.
558   iterator erase(iterator I) {
559     return erase(I, std::next(I));
560   }
561
562   /// Remove an instruction from the instruction list and delete it.
563   ///
564   /// If I is the head of a bundle of instructions, the whole bundle will be
565   /// erased.
566   iterator erase(MachineInstr *I) {
567     return erase(iterator(I));
568   }
569
570   /// Remove the unbundled instruction from the instruction list without
571   /// deleting it.
572   ///
573   /// This function can not be used to remove bundled instructions, use
574   /// remove_instr to remove individual instructions from a bundle.
575   MachineInstr *remove(MachineInstr *I) {
576     assert(!I->isBundled() && "Cannot remove bundled instructions");
577     return Insts.remove(I);
578   }
579
580   /// Remove the possibly bundled instruction from the instruction list
581   /// without deleting it.
582   ///
583   /// If the instruction is part of a bundle, the other instructions in the
584   /// bundle will still be bundled after removing the single instruction.
585   MachineInstr *remove_instr(MachineInstr *I);
586
587   void clear() {
588     Insts.clear();
589   }
590
591   /// Take an instruction from MBB 'Other' at the position From, and insert it
592   /// into this MBB right before 'Where'.
593   ///
594   /// If From points to a bundle of instructions, the whole bundle is moved.
595   void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
596     // The range splice() doesn't allow noop moves, but this one does.
597     if (Where != From)
598       splice(Where, Other, From, std::next(From));
599   }
600
601   /// Take a block of instructions from MBB 'Other' in the range [From, To),
602   /// and insert them into this MBB right before 'Where'.
603   ///
604   /// The instruction at 'Where' must not be included in the range of
605   /// instructions to move.
606   void splice(iterator Where, MachineBasicBlock *Other,
607               iterator From, iterator To) {
608     Insts.splice(Where.getInstrIterator(), Other->Insts,
609                  From.getInstrIterator(), To.getInstrIterator());
610   }
611
612   /// removeFromParent - This method unlinks 'this' from the containing
613   /// function, and returns it, but does not delete it.
614   MachineBasicBlock *removeFromParent();
615
616   /// eraseFromParent - This method unlinks 'this' from the containing
617   /// function and deletes it.
618   void eraseFromParent();
619
620   /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
621   /// 'Old', change the code and CFG so that it branches to 'New' instead.
622   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
623
624   /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
625   /// the CFG to be inserted.  If we have proven that MBB can only branch to
626   /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
627   /// DestB can be null. Besides DestA and DestB, retain other edges leading
628   /// to LandingPads (currently there can be only one; we don't check or require
629   /// that here). Note it is possible that DestA and/or DestB are LandingPads.
630   bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
631                             MachineBasicBlock *DestB,
632                             bool isCond);
633
634   /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
635   /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
636   DebugLoc findDebugLoc(instr_iterator MBBI);
637   DebugLoc findDebugLoc(iterator MBBI) {
638     return findDebugLoc(MBBI.getInstrIterator());
639   }
640
641   /// Possible outcome of a register liveness query to computeRegisterLiveness()
642   enum LivenessQueryResult {
643     LQR_Live,            ///< Register is known to be live.
644     LQR_OverlappingLive, ///< Register itself is not live, but some overlapping
645                          ///< register is.
646     LQR_Dead,            ///< Register is known to be dead.
647     LQR_Unknown          ///< Register liveness not decidable from local
648                          ///< neighborhood.
649   };
650
651   /// Return whether (physical) register \p Reg has been <def>ined and not
652   /// <kill>ed as of just before \p Before.
653   ///
654   /// Search is localised to a neighborhood of \p Neighborhood instructions
655   /// before (searching for defs or kills) and \p Neighborhood instructions
656   /// after (searching just for defs) \p Before.
657   ///
658   /// \p Reg must be a physical register.
659   LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
660                                               unsigned Reg,
661                                               const_iterator Before,
662                                               unsigned Neighborhood=10) const;
663
664   // Debugging methods.
665   void dump() const;
666   void print(raw_ostream &OS, SlotIndexes* = nullptr) const;
667   void print(raw_ostream &OS, ModuleSlotTracker &MST,
668              SlotIndexes * = nullptr) const;
669
670   // Printing method used by LoopInfo.
671   void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
672
673   /// getNumber - MachineBasicBlocks are uniquely numbered at the function
674   /// level, unless they're not in a MachineFunction yet, in which case this
675   /// will return -1.
676   ///
677   int getNumber() const { return Number; }
678   void setNumber(int N) { Number = N; }
679
680   /// getSymbol - Return the MCSymbol for this basic block.
681   ///
682   MCSymbol *getSymbol() const;
683
684
685 private:
686   /// getWeightIterator - Return weight iterator corresponding to the I
687   /// successor iterator.
688   weight_iterator getWeightIterator(succ_iterator I);
689   const_weight_iterator getWeightIterator(const_succ_iterator I) const;
690
691   friend class MachineBranchProbabilityInfo;
692
693   /// getSuccWeight - Return weight of the edge from this block to MBB. This
694   /// method should NOT be called directly, but by using getEdgeWeight method
695   /// from MachineBranchProbabilityInfo class.
696   uint32_t getSuccWeight(const_succ_iterator Succ) const;
697
698
699   // Methods used to maintain doubly linked list of blocks...
700   friend struct ilist_traits<MachineBasicBlock>;
701
702   // Machine-CFG mutators
703
704   /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
705   /// Don't do this unless you know what you're doing, because it doesn't
706   /// update pred's successors list. Use pred->addSuccessor instead.
707   ///
708   void addPredecessor(MachineBasicBlock *pred);
709
710   /// removePredecessor - Remove pred as a predecessor of this
711   /// MachineBasicBlock. Don't do this unless you know what you're
712   /// doing, because it doesn't update pred's successors list. Use
713   /// pred->removeSuccessor instead.
714   ///
715   void removePredecessor(MachineBasicBlock *pred);
716 };
717
718 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
719
720 // This is useful when building IndexedMaps keyed on basic block pointers.
721 struct MBB2NumberFunctor :
722   public std::unary_function<const MachineBasicBlock*, unsigned> {
723   unsigned operator()(const MachineBasicBlock *MBB) const {
724     return MBB->getNumber();
725   }
726 };
727
728 //===--------------------------------------------------------------------===//
729 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
730 //===--------------------------------------------------------------------===//
731
732 // Provide specializations of GraphTraits to be able to treat a
733 // MachineFunction as a graph of MachineBasicBlocks...
734 //
735
736 template <> struct GraphTraits<MachineBasicBlock *> {
737   typedef MachineBasicBlock NodeType;
738   typedef MachineBasicBlock::succ_iterator ChildIteratorType;
739
740   static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
741   static inline ChildIteratorType child_begin(NodeType *N) {
742     return N->succ_begin();
743   }
744   static inline ChildIteratorType child_end(NodeType *N) {
745     return N->succ_end();
746   }
747 };
748
749 template <> struct GraphTraits<const MachineBasicBlock *> {
750   typedef const MachineBasicBlock NodeType;
751   typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
752
753   static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
754   static inline ChildIteratorType child_begin(NodeType *N) {
755     return N->succ_begin();
756   }
757   static inline ChildIteratorType child_end(NodeType *N) {
758     return N->succ_end();
759   }
760 };
761
762 // Provide specializations of GraphTraits to be able to treat a
763 // MachineFunction as a graph of MachineBasicBlocks... and to walk it
764 // in inverse order.  Inverse order for a function is considered
765 // to be when traversing the predecessor edges of a MBB
766 // instead of the successor edges.
767 //
768 template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
769   typedef MachineBasicBlock NodeType;
770   typedef MachineBasicBlock::pred_iterator ChildIteratorType;
771   static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
772     return G.Graph;
773   }
774   static inline ChildIteratorType child_begin(NodeType *N) {
775     return N->pred_begin();
776   }
777   static inline ChildIteratorType child_end(NodeType *N) {
778     return N->pred_end();
779   }
780 };
781
782 template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
783   typedef const MachineBasicBlock NodeType;
784   typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
785   static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
786     return G.Graph;
787   }
788   static inline ChildIteratorType child_begin(NodeType *N) {
789     return N->pred_begin();
790   }
791   static inline ChildIteratorType child_end(NodeType *N) {
792     return N->pred_end();
793   }
794 };
795
796
797
798 /// MachineInstrSpan provides an interface to get an iteration range
799 /// containing the instruction it was initialized with, along with all
800 /// those instructions inserted prior to or following that instruction
801 /// at some point after the MachineInstrSpan is constructed.
802 class MachineInstrSpan {
803   MachineBasicBlock &MBB;
804   MachineBasicBlock::iterator I, B, E;
805 public:
806   MachineInstrSpan(MachineBasicBlock::iterator I)
807     : MBB(*I->getParent()),
808       I(I),
809       B(I == MBB.begin() ? MBB.end() : std::prev(I)),
810       E(std::next(I)) {}
811
812   MachineBasicBlock::iterator begin() {
813     return B == MBB.end() ? MBB.begin() : std::next(B);
814   }
815   MachineBasicBlock::iterator end() { return E; }
816   bool empty() { return begin() == end(); }
817
818   MachineBasicBlock::iterator getInitial() { return I; }
819 };
820
821 } // End llvm namespace
822
823 #endif