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