Re-apply 55467 with fix. If copy is being replaced by remat'ed def, transfer the...
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.h
1 //===-- SimpleRegisterCoalescing.h - Register Coalescing --------*- 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 // This file implements a simple register copy coalescing phase.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H
15 #define LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H
16
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/LiveInterval.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/RegisterCoalescer.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/IndexedMap.h"
23 #include <queue>
24
25 namespace llvm {
26   class SimpleRegisterCoalescing;
27   class LiveVariables;
28   class TargetRegisterInfo;
29   class TargetInstrInfo;
30   class VirtRegMap;
31   class MachineLoopInfo;
32
33   /// CopyRec - Representation for copy instructions in coalescer queue.
34   ///
35   struct CopyRec {
36     MachineInstr *MI;
37     unsigned LoopDepth;
38     bool isBackEdge;
39     CopyRec(MachineInstr *mi, unsigned depth, bool be)
40       : MI(mi), LoopDepth(depth), isBackEdge(be) {};
41   };
42
43   template<class SF> class JoinPriorityQueue;
44
45   /// CopyRecSort - Sorting function for coalescer queue.
46   ///
47   struct CopyRecSort : public std::binary_function<CopyRec,CopyRec,bool> {
48     JoinPriorityQueue<CopyRecSort> *JPQ;
49     explicit CopyRecSort(JoinPriorityQueue<CopyRecSort> *jpq) : JPQ(jpq) {}
50     CopyRecSort(const CopyRecSort &RHS) : JPQ(RHS.JPQ) {}
51     bool operator()(CopyRec left, CopyRec right) const;
52   };
53
54   /// JoinQueue - A priority queue of copy instructions the coalescer is
55   /// going to process.
56   template<class SF>
57   class JoinPriorityQueue {
58     SimpleRegisterCoalescing *Rc;
59     std::priority_queue<CopyRec, std::vector<CopyRec>, SF> Queue;
60
61   public:
62     explicit JoinPriorityQueue(SimpleRegisterCoalescing *rc)
63       : Rc(rc), Queue(SF(this)) {}
64
65     bool empty() const { return Queue.empty(); }
66     void push(CopyRec R) { Queue.push(R); }
67     CopyRec pop() {
68       if (empty()) return CopyRec(0, 0, false);
69       CopyRec R = Queue.top();
70       Queue.pop();
71       return R;
72     }
73
74     // Callbacks to SimpleRegisterCoalescing.
75     unsigned getRepIntervalSize(unsigned Reg);
76   };
77
78   class SimpleRegisterCoalescing : public MachineFunctionPass,
79                                    public RegisterCoalescer {
80     MachineFunction* mf_;
81     MachineRegisterInfo* mri_;
82     const TargetMachine* tm_;
83     const TargetRegisterInfo* tri_;
84     const TargetInstrInfo* tii_;
85     LiveIntervals *li_;
86     const MachineLoopInfo* loopInfo;
87     
88     BitVector allocatableRegs_;
89     DenseMap<const TargetRegisterClass*, BitVector> allocatableRCRegs_;
90
91     /// JoinQueue - A priority queue of copy instructions the coalescer is
92     /// going to process.
93     JoinPriorityQueue<CopyRecSort> *JoinQueue;
94
95     /// JoinedCopies - Keep track of copies eliminated due to coalescing.
96     ///
97     SmallPtrSet<MachineInstr*, 32> JoinedCopies;
98
99     /// ReMatCopies - Keep track of copies eliminated due to remat.
100     ///
101     SmallPtrSet<MachineInstr*, 32> ReMatCopies;
102
103   public:
104     static char ID; // Pass identifcation, replacement for typeid
105     SimpleRegisterCoalescing() : MachineFunctionPass((intptr_t)&ID) {}
106
107     struct InstrSlots {
108       enum {
109         LOAD  = 0,
110         USE   = 1,
111         DEF   = 2,
112         STORE = 3,
113         NUM   = 4
114       };
115     };
116     
117     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
118     virtual void releaseMemory();
119
120     /// runOnMachineFunction - pass entry point
121     virtual bool runOnMachineFunction(MachineFunction&);
122
123     bool coalesceFunction(MachineFunction &mf, RegallocQuery &) {
124       // This runs as an independent pass, so don't do anything.
125       return false;
126     };
127
128     /// getRepIntervalSize - Called from join priority queue sorting function.
129     /// It returns the size of the interval that represent the given register.
130     unsigned getRepIntervalSize(unsigned Reg) {
131       if (!li_->hasInterval(Reg))
132         return 0;
133       return li_->getApproximateInstructionCount(li_->getInterval(Reg)) *
134              LiveIntervals::InstrSlots::NUM;
135     }
136
137     /// print - Implement the dump method.
138     virtual void print(std::ostream &O, const Module* = 0) const;
139     void print(std::ostream *O, const Module* M = 0) const {
140       if (O) print(*O, M);
141     }
142
143   private:
144     /// joinIntervals - join compatible live intervals
145     void joinIntervals();
146
147     /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
148     /// copies that cannot yet be coalesced into the "TryAgain" list.
149     void CopyCoalesceInMBB(MachineBasicBlock *MBB,
150                            std::vector<CopyRec> &TryAgain);
151
152     /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
153     /// which are the src/dst of the copy instruction CopyMI.  This returns true
154     /// if the copy was successfully coalesced away. If it is not currently
155     /// possible to coalesce this interval, but it may be possible if other
156     /// things get coalesced, then it returns true by reference in 'Again'.
157     bool JoinCopy(CopyRec &TheCopy, bool &Again);
158     
159     /// JoinIntervals - Attempt to join these two intervals.  On failure, this
160     /// returns false.  Otherwise, if one of the intervals being joined is a
161     /// physreg, this method always canonicalizes DestInt to be it.  The output
162     /// "SrcInt" will not have been modified, so we can use this information
163     /// below to update aliases.
164     bool JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, bool &Swapped);
165     
166     /// SimpleJoin - Attempt to join the specified interval into this one. The
167     /// caller of this method must guarantee that the RHS only contains a single
168     /// value number and that the RHS is not defined by a copy from this
169     /// interval.  This returns false if the intervals are not joinable, or it
170     /// joins them and returns true.
171     bool SimpleJoin(LiveInterval &LHS, LiveInterval &RHS);
172     
173     /// Return true if the two specified registers belong to different register
174     /// classes.  The registers may be either phys or virt regs. In the
175     /// case where both registers are virtual registers, it would also returns
176     /// true by reference the RegB register class in SubRC if it is a subset of
177     /// RegA's register class.
178     bool differingRegisterClasses(unsigned RegA, unsigned RegB,
179                                   const TargetRegisterClass *&SubRC) const;
180
181
182     /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
183     /// the source value number is defined by a copy from the destination reg
184     /// see if we can merge these two destination reg valno# into a single
185     /// value number, eliminating a copy.
186     bool AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
187                               MachineInstr *CopyMI);
188
189     /// HasOtherReachingDefs - Return true if there are definitions of IntB
190     /// other than BValNo val# that can reach uses of AValno val# of IntA.
191     bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
192                               VNInfo *AValNo, VNInfo *BValNo);
193
194     /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
195     /// If the source value number is defined by a commutable instruction and
196     /// its other operand is coalesced to the copy dest register, see if we
197     /// can transform the copy into a noop by commuting the definition.
198     bool RemoveCopyByCommutingDef(LiveInterval &IntA, LiveInterval &IntB,
199                                   MachineInstr *CopyMI);
200
201     bool ReMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
202                                  MachineInstr *CopyMI);
203
204     /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
205     /// turn the copy into an implicit def.
206     bool TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
207                             MachineBasicBlock *MBB,
208                             unsigned DstReg, unsigned SrcReg);
209
210     /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
211     /// from an implicit def to another register can be coalesced away.
212     bool CanCoalesceWithImpDef(MachineInstr *CopyMI,
213                                LiveInterval &li, LiveInterval &ImpLi) const;
214
215     /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
216     /// def and it is being removed. Turn all copies from this value# into
217     /// identity copies so they will be removed.
218     void RemoveCopiesFromValNo(LiveInterval &li, VNInfo *VNI);
219
220     /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
221     /// a subset of the register class of SrcReg, return true if it's profitable
222     /// to coalesce the two registers.
223     bool isProfitableToCoalesceToSubRC(unsigned SrcReg, unsigned DstReg,
224                                        MachineBasicBlock *MBB);
225
226     /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
227     /// the specified live interval is defined by a copy from the specified
228     /// register.
229     bool RangeIsDefinedByCopyFromReg(LiveInterval &li, LiveRange *LR,
230                                      unsigned Reg);
231
232     /// isBackEdgeCopy - Return true if CopyMI is a back edge copy.
233     ///
234     bool isBackEdgeCopy(MachineInstr *CopyMI, unsigned DstReg) const;
235
236     /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
237     /// update the subregister number if it is not zero. If DstReg is a
238     /// physical register and the existing subregister number of the def / use
239     /// being updated is not zero, make sure to set it to the correct physical
240     /// subregister.
241     void UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
242
243     /// RemoveDeadImpDef - Remove implicit_def instructions which are
244     /// "re-defining" registers due to insert_subreg coalescing. e.g.
245     void RemoveDeadImpDef(unsigned Reg, LiveInterval &LI);
246
247     /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
248     /// due to live range lengthening as the result of coalescing.
249     void RemoveUnnecessaryKills(unsigned Reg, LiveInterval &LI);
250
251     /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
252     /// Return true if live interval is removed.
253     bool ShortenDeadCopyLiveRange(LiveInterval &li, MachineInstr *CopyMI);
254
255     /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
256     /// extended by a dead copy. Mark the last use (if any) of the val# as kill
257     /// as ends the live range there. If there isn't another use, then this
258     /// live range is dead. Return true if live interval is removed.
259     bool ShortenDeadCopySrcLiveRange(LiveInterval &li, MachineInstr *CopyMI);
260
261     /// lastRegisterUse - Returns the last use of the specific register between
262     /// cycles Start and End or NULL if there are no uses.
263     MachineOperand *lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
264                                     unsigned &LastUseIdx) const;
265
266     void printRegName(unsigned reg) const;
267   };
268
269 } // End llvm namespace
270
271 #endif