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