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