Temporarily revert r90502. It was causing the llvm-gcc bootstrap on PPC to fail.
[oota-llvm.git] / include / llvm / CodeGen / LiveIntervalAnalysis.h
1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- 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 the LiveInterval analysis pass.  Given some numbering of
11 // each the machine instructions (in this implemention depth-first order) an
12 // interval [i, j) is said to be a live interval for register v if there is no
13 // instruction with number j' > j such that v is live at j' and there is no
14 // instruction with number i' < i such that v is live at i'. In this
15 // implementation intervals can have holes, i.e. an interval might look like
16 // [1,20), [50,65), [1000,1001).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
22
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/SlotIndexes.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/Allocator.h"
32 #include <cmath>
33 #include <iterator>
34
35 namespace llvm {
36
37   class AliasAnalysis;
38   class LiveVariables;
39   class MachineLoopInfo;
40   class TargetRegisterInfo;
41   class MachineRegisterInfo;
42   class TargetInstrInfo;
43   class TargetRegisterClass;
44   class VirtRegMap;
45   
46   class LiveIntervals : public MachineFunctionPass {
47     MachineFunction* mf_;
48     MachineRegisterInfo* mri_;
49     const TargetMachine* tm_;
50     const TargetRegisterInfo* tri_;
51     const TargetInstrInfo* tii_;
52     AliasAnalysis *aa_;
53     LiveVariables* lv_;
54     SlotIndexes* indexes_;
55
56     /// Special pool allocator for VNInfo's (LiveInterval val#).
57     ///
58     BumpPtrAllocator VNInfoAllocator;
59
60     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61     Reg2IntervalMap r2iMap_;
62
63     /// allocatableRegs_ - A bit vector of allocatable registers.
64     BitVector allocatableRegs_;
65
66     /// CloneMIs - A list of clones as result of re-materialization.
67     std::vector<MachineInstr*> CloneMIs;
68
69   public:
70     static char ID; // Pass identification, replacement for typeid
71     LiveIntervals() : MachineFunctionPass(&ID) {}
72
73     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
74       return (isDef + isUse) * powf(10.0F, (float)loopDepth);
75     }
76
77     typedef Reg2IntervalMap::iterator iterator;
78     typedef Reg2IntervalMap::const_iterator const_iterator;
79     const_iterator begin() const { return r2iMap_.begin(); }
80     const_iterator end() const { return r2iMap_.end(); }
81     iterator begin() { return r2iMap_.begin(); }
82     iterator end() { return r2iMap_.end(); }
83     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
84
85     LiveInterval &getInterval(unsigned reg) {
86       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
87       assert(I != r2iMap_.end() && "Interval does not exist for register");
88       return *I->second;
89     }
90
91     const LiveInterval &getInterval(unsigned reg) const {
92       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
93       assert(I != r2iMap_.end() && "Interval does not exist for register");
94       return *I->second;
95     }
96
97     bool hasInterval(unsigned reg) const {
98       return r2iMap_.count(reg);
99     }
100
101     /// getScaledIntervalSize - get the size of an interval in "units,"
102     /// where every function is composed of one thousand units.  This
103     /// measure scales properly with empty index slots in the function.
104     double getScaledIntervalSize(LiveInterval& I) {
105       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
106     }
107     
108     /// getApproximateInstructionCount - computes an estimate of the number
109     /// of instructions in a given LiveInterval.
110     unsigned getApproximateInstructionCount(LiveInterval& I) {
111       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
112       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
113     }
114
115     /// conflictsWithPhysRegDef - Returns true if the specified register
116     /// is defined during the duration of the specified interval.
117     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
118                                  unsigned reg);
119
120     /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
121     /// it can check use as well.
122     bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
123                                  bool CheckUse,
124                                  SmallPtrSet<MachineInstr*,32> &JoinedCopies);
125
126     // Interval creation
127     LiveInterval &getOrCreateInterval(unsigned reg) {
128       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
129       if (I == r2iMap_.end())
130         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
131       return *I->second;
132     }
133
134     /// dupInterval - Duplicate a live interval. The caller is responsible for
135     /// managing the allocated memory.
136     LiveInterval *dupInterval(LiveInterval *li);
137     
138     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
139     /// adds a live range from that instruction to the end of its MBB.
140     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
141                                        MachineInstr* startInst);
142
143     // Interval removal
144
145     void removeInterval(unsigned Reg) {
146       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
147       delete I->second;
148       r2iMap_.erase(I);
149     }
150
151     SlotIndex getZeroIndex() const {
152       return indexes_->getZeroIndex();
153     }
154
155     SlotIndex getInvalidIndex() const {
156       return indexes_->getInvalidIndex();
157     }
158
159     /// isNotInMIMap - returns true if the specified machine instr has been
160     /// removed or was never entered in the map.
161     bool isNotInMIMap(const MachineInstr* Instr) const {
162       return !indexes_->hasIndex(Instr);
163     }
164
165     /// Returns the base index of the given instruction.
166     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
167       return indexes_->getInstructionIndex(instr);
168     }
169     
170     /// Returns the instruction associated with the given index.
171     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
172       return indexes_->getInstructionFromIndex(index);
173     }
174
175     /// Return the first index in the given basic block.
176     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
177       return indexes_->getMBBStartIdx(mbb);
178     } 
179
180     /// Return the last index in the given basic block.
181     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
182       return indexes_->getMBBEndIdx(mbb);
183     } 
184
185     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
186       return indexes_->getMBBFromIndex(index);
187     }
188
189     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
190       return indexes_->insertMachineInstrInMaps(MI);
191     }
192
193     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
194       indexes_->removeMachineInstrFromMaps(MI);
195     }
196
197     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
198       indexes_->replaceMachineInstrInMaps(MI, NewMI);
199     }
200
201     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
202                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
203       return indexes_->findLiveInMBBs(Start, End, MBBs);
204     }
205
206     void renumber() {
207       indexes_->renumberIndexes();
208     }
209
210     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
211
212     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
213     /// copy field and returns the source register that defines it.
214     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
215
216     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
217     virtual void releaseMemory();
218
219     /// runOnMachineFunction - pass entry point
220     virtual bool runOnMachineFunction(MachineFunction&);
221
222     /// print - Implement the dump method.
223     virtual void print(raw_ostream &O, const Module* = 0) const;
224
225     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
226     /// the given interval. FIXME: It also returns the weight of the spill slot
227     /// (if any is created) by reference. This is temporary.
228     std::vector<LiveInterval*>
229     addIntervalsForSpills(const LiveInterval& i,
230                           SmallVectorImpl<LiveInterval*> &SpillIs,
231                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
232     
233     /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
234     /// defs / uses without remat or splitting.
235     std::vector<LiveInterval*>
236     addIntervalsForSpillsFast(const LiveInterval &li,
237                               const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
238
239     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
240     /// around all defs and uses of the specified interval. Return true if it
241     /// was able to cut its interval.
242     bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
243                                        unsigned PhysReg, VirtRegMap &vrm);
244
245     /// isReMaterializable - Returns true if every definition of MI of every
246     /// val# of the specified interval is re-materializable. Also returns true
247     /// by reference if all of the defs are load instructions.
248     bool isReMaterializable(const LiveInterval &li,
249                             SmallVectorImpl<LiveInterval*> &SpillIs,
250                             bool &isLoad);
251
252     /// isReMaterializable - Returns true if the definition MI of the specified
253     /// val# of the specified interval is re-materializable.
254     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
255                             MachineInstr *MI);
256
257     /// getRepresentativeReg - Find the largest super register of the specified
258     /// physical register.
259     unsigned getRepresentativeReg(unsigned Reg) const;
260
261     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
262     /// specified interval that conflicts with the specified physical register.
263     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
264                                         unsigned PhysReg) const;
265
266     /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
267     /// marker to implicit_def defs and their uses.
268     void processImplicitDefs();
269
270     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
271     /// within a single basic block.
272     bool intervalIsInOneMBB(const LiveInterval &li) const;
273
274   private:      
275     /// computeIntervals - Compute live intervals.
276     void computeIntervals();
277
278     /// handleRegisterDef - update intervals for a register def
279     /// (calls handlePhysicalRegisterDef and
280     /// handleVirtualRegisterDef)
281     void handleRegisterDef(MachineBasicBlock *MBB,
282                            MachineBasicBlock::iterator MI,
283                            SlotIndex MIIdx,
284                            MachineOperand& MO, unsigned MOIdx);
285
286     /// handleVirtualRegisterDef - update intervals for a virtual
287     /// register def
288     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
289                                   MachineBasicBlock::iterator MI,
290                                   SlotIndex MIIdx, MachineOperand& MO,
291                                   unsigned MOIdx,
292                                   LiveInterval& interval);
293
294     /// handlePhysicalRegisterDef - update intervals for a physical register
295     /// def.
296     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
297                                    MachineBasicBlock::iterator mi,
298                                    SlotIndex MIIdx, MachineOperand& MO,
299                                    LiveInterval &interval,
300                                    MachineInstr *CopyMI);
301
302     /// handleLiveInRegister - Create interval for a livein register.
303     void handleLiveInRegister(MachineBasicBlock* mbb,
304                               SlotIndex MIIdx,
305                               LiveInterval &interval, bool isAlias = false);
306
307     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
308     /// only allow one) virtual register operand, then its uses are implicitly
309     /// using the register. Returns the virtual register.
310     unsigned getReMatImplicitUse(const LiveInterval &li,
311                                  MachineInstr *MI) const;
312
313     /// isValNoAvailableAt - Return true if the val# of the specified interval
314     /// which reaches the given instruction also reaches the specified use
315     /// index.
316     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
317                             SlotIndex UseIdx) const;
318
319     /// isReMaterializable - Returns true if the definition MI of the specified
320     /// val# of the specified interval is re-materializable. Also returns true
321     /// by reference if the def is a load.
322     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
323                             MachineInstr *MI,
324                             SmallVectorImpl<LiveInterval*> &SpillIs,
325                             bool &isLoad);
326
327     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
328     /// slot / to reg or any rematerialized load into ith operand of specified
329     /// MI. If it is successul, MI is updated with the newly created MI and
330     /// returns true.
331     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
332                               MachineInstr *DefMI, SlotIndex InstrIdx,
333                               SmallVector<unsigned, 2> &Ops,
334                               bool isSS, int FrameIndex, unsigned Reg);
335
336     /// canFoldMemoryOperand - Return true if the specified load / store
337     /// folding is possible.
338     bool canFoldMemoryOperand(MachineInstr *MI,
339                               SmallVector<unsigned, 2> &Ops,
340                               bool ReMatLoadSS) const;
341
342     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
343     /// VNInfo that's after the specified index but is within the basic block.
344     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
345                               MachineBasicBlock *MBB,
346                               SlotIndex Idx) const;
347
348     /// hasAllocatableSuperReg - Return true if the specified physical register
349     /// has any super register that's allocatable.
350     bool hasAllocatableSuperReg(unsigned Reg) const;
351
352     /// SRInfo - Spill / restore info.
353     struct SRInfo {
354       SlotIndex index;
355       unsigned vreg;
356       bool canFold;
357       SRInfo(SlotIndex i, unsigned vr, bool f)
358         : index(i), vreg(vr), canFold(f) {}
359     };
360
361     bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
362                           BitVector &RestoreMBBs,
363                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
364     void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
365                           BitVector &RestoreMBBs,
366                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
367
368     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
369     /// spilled and create empty intervals for their uses.
370     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
371                               const TargetRegisterClass* rc,
372                               std::vector<LiveInterval*> &NewLIs);
373
374     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
375     /// interval on to-be re-materialized operands of MI) with new register.
376     void rewriteImplicitOps(const LiveInterval &li,
377                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
378
379     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
380     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
381     /// live range.
382     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
383         bool TrySplit, SlotIndex index, SlotIndex end,
384         MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
385         unsigned Slot, int LdSlot,
386         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
387         VirtRegMap &vrm, const TargetRegisterClass* rc,
388         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
389         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
390         DenseMap<unsigned,unsigned> &MBBVRegsMap,
391         std::vector<LiveInterval*> &NewLIs);
392     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
393         LiveInterval::Ranges::const_iterator &I,
394         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
395         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
396         VirtRegMap &vrm, const TargetRegisterClass* rc,
397         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
398         BitVector &SpillMBBs,
399         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
400         BitVector &RestoreMBBs,
401         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
402         DenseMap<unsigned,unsigned> &MBBVRegsMap,
403         std::vector<LiveInterval*> &NewLIs);
404
405     static LiveInterval* createInterval(unsigned Reg);
406
407     void printInstrs(raw_ostream &O) const;
408     void dumpInstrs() const;
409   };
410 } // End llvm namespace
411
412 #endif