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