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