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