Add LiveIntervals::getLastSplitPoint().
[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     VNInfo::Allocator 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       initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
73     }
74
75     // Calculate the spill weight to assign to a single instruction.
76     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
77
78     // After summing the spill weights of all defs and uses, the final weight
79     // should be normalized, dividing the weight of the interval by its size.
80     // This encourages spilling of intervals that are large and have few uses,
81     // and discourages spilling of small intervals with many uses.
82     void normalizeSpillWeight(LiveInterval &li) {
83       li.weight /= getApproximateInstructionCount(li) + 25;
84     }
85
86     typedef Reg2IntervalMap::iterator iterator;
87     typedef Reg2IntervalMap::const_iterator const_iterator;
88     const_iterator begin() const { return r2iMap_.begin(); }
89     const_iterator end() const { return r2iMap_.end(); }
90     iterator begin() { return r2iMap_.begin(); }
91     iterator end() { return r2iMap_.end(); }
92     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
93
94     LiveInterval &getInterval(unsigned reg) {
95       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
96       assert(I != r2iMap_.end() && "Interval does not exist for register");
97       return *I->second;
98     }
99
100     const LiveInterval &getInterval(unsigned reg) const {
101       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
102       assert(I != r2iMap_.end() && "Interval does not exist for register");
103       return *I->second;
104     }
105
106     bool hasInterval(unsigned reg) const {
107       return r2iMap_.count(reg);
108     }
109
110     /// isAllocatable - is the physical register reg allocatable in the current
111     /// function?
112     bool isAllocatable(unsigned reg) const {
113       return allocatableRegs_.test(reg);
114     }
115
116     /// getScaledIntervalSize - get the size of an interval in "units,"
117     /// where every function is composed of one thousand units.  This
118     /// measure scales properly with empty index slots in the function.
119     double getScaledIntervalSize(LiveInterval& I) {
120       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
121     }
122
123     /// getFuncInstructionCount - Return the number of instructions in the
124     /// current function.
125     unsigned getFuncInstructionCount() {
126       return indexes_->getFunctionSize();
127     }
128
129     /// getApproximateInstructionCount - computes an estimate of the number
130     /// of instructions in a given LiveInterval.
131     unsigned getApproximateInstructionCount(LiveInterval& I) {
132       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
133       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
134     }
135
136     /// conflictsWithPhysReg - Returns true if the specified register is used or
137     /// defined during the duration of the specified interval. Copies to and
138     /// from li.reg are allowed. This method is only able to analyze simple
139     /// ranges that stay within a single basic block. Anything else is
140     /// considered a conflict.
141     bool conflictsWithPhysReg(const LiveInterval &li, VirtRegMap &vrm,
142                               unsigned reg);
143
144     /// conflictsWithAliasRef - Similar to conflictsWithPhysRegRef except
145     /// it checks for alias uses and defs.
146     bool conflictsWithAliasRef(LiveInterval &li, unsigned Reg,
147                                    SmallPtrSet<MachineInstr*,32> &JoinedCopies);
148
149     // Interval creation
150     LiveInterval &getOrCreateInterval(unsigned reg) {
151       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
152       if (I == r2iMap_.end())
153         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
154       return *I->second;
155     }
156
157     /// dupInterval - Duplicate a live interval. The caller is responsible for
158     /// managing the allocated memory.
159     LiveInterval *dupInterval(LiveInterval *li);
160
161     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
162     /// adds a live range from that instruction to the end of its MBB.
163     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
164                                        MachineInstr* startInst);
165
166     // Interval removal
167
168     void removeInterval(unsigned Reg) {
169       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
170       delete I->second;
171       r2iMap_.erase(I);
172     }
173
174     SlotIndexes *getSlotIndexes() const {
175       return indexes_;
176     }
177
178     SlotIndex getZeroIndex() const {
179       return indexes_->getZeroIndex();
180     }
181
182     SlotIndex getInvalidIndex() const {
183       return indexes_->getInvalidIndex();
184     }
185
186     /// isNotInMIMap - returns true if the specified machine instr has been
187     /// removed or was never entered in the map.
188     bool isNotInMIMap(const MachineInstr* Instr) const {
189       return !indexes_->hasIndex(Instr);
190     }
191
192     /// Returns the base index of the given instruction.
193     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
194       return indexes_->getInstructionIndex(instr);
195     }
196
197     /// Returns the instruction associated with the given index.
198     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
199       return indexes_->getInstructionFromIndex(index);
200     }
201
202     /// Return the first index in the given basic block.
203     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
204       return indexes_->getMBBStartIdx(mbb);
205     }
206
207     /// Return the last index in the given basic block.
208     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
209       return indexes_->getMBBEndIdx(mbb);
210     }
211
212     bool isLiveInToMBB(const LiveInterval &li,
213                        const MachineBasicBlock *mbb) const {
214       return li.liveAt(getMBBStartIdx(mbb));
215     }
216
217     LiveRange* findEnteringRange(LiveInterval &li,
218                                  const MachineBasicBlock *mbb) {
219       return li.getLiveRangeContaining(getMBBStartIdx(mbb));
220     }
221
222     bool isLiveOutOfMBB(const LiveInterval &li,
223                         const MachineBasicBlock *mbb) const {
224       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
225     }
226
227     LiveRange* findExitingRange(LiveInterval &li,
228                                 const MachineBasicBlock *mbb) {
229       return li.getLiveRangeContaining(getMBBEndIdx(mbb).getPrevSlot());
230     }
231
232     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
233       return indexes_->getMBBFromIndex(index);
234     }
235
236     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
237       return indexes_->insertMachineInstrInMaps(MI);
238     }
239
240     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
241       indexes_->removeMachineInstrFromMaps(MI);
242     }
243
244     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
245       indexes_->replaceMachineInstrInMaps(MI, NewMI);
246     }
247
248     void InsertMBBInMaps(MachineBasicBlock *MBB) {
249       indexes_->insertMBBInMaps(MBB);
250     }
251
252     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
253                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
254       return indexes_->findLiveInMBBs(Start, End, MBBs);
255     }
256
257     void renumber() {
258       indexes_->renumberIndexes();
259     }
260
261     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
262
263     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
264     virtual void releaseMemory();
265
266     /// runOnMachineFunction - pass entry point
267     virtual bool runOnMachineFunction(MachineFunction&);
268
269     /// print - Implement the dump method.
270     virtual void print(raw_ostream &O, const Module* = 0) const;
271
272     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
273     /// the given interval. FIXME: It also returns the weight of the spill slot
274     /// (if any is created) by reference. This is temporary.
275     std::vector<LiveInterval*>
276     addIntervalsForSpills(const LiveInterval& i,
277                           const SmallVectorImpl<LiveInterval*> &SpillIs,
278                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
279
280     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
281     /// around all defs and uses of the specified interval. Return true if it
282     /// was able to cut its interval.
283     bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
284                                        unsigned PhysReg, VirtRegMap &vrm);
285
286     /// isReMaterializable - Returns true if every definition of MI of every
287     /// val# of the specified interval is re-materializable. Also returns true
288     /// by reference if all of the defs are load instructions.
289     bool isReMaterializable(const LiveInterval &li,
290                             const SmallVectorImpl<LiveInterval*> &SpillIs,
291                             bool &isLoad);
292
293     /// isReMaterializable - Returns true if the definition MI of the specified
294     /// val# of the specified interval is re-materializable.
295     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
296                             MachineInstr *MI);
297
298     /// getRepresentativeReg - Find the largest super register of the specified
299     /// physical register.
300     unsigned getRepresentativeReg(unsigned Reg) const;
301
302     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
303     /// specified interval that conflicts with the specified physical register.
304     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
305                                         unsigned PhysReg) const;
306
307     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
308     /// within a single basic block.
309     bool intervalIsInOneMBB(const LiveInterval &li) const;
310
311     /// getLastSplitPoint - Return the last possible insertion point in mbb for
312     /// spilling and splitting code. This is the first terminator, or the call
313     /// instruction if li is live into a landing pad successor.
314     MachineBasicBlock::iterator getLastSplitPoint(const LiveInterval &li,
315                                                   MachineBasicBlock *mbb);
316
317   private:
318     /// computeIntervals - Compute live intervals.
319     void computeIntervals();
320
321     /// handleRegisterDef - update intervals for a register def
322     /// (calls handlePhysicalRegisterDef and
323     /// handleVirtualRegisterDef)
324     void handleRegisterDef(MachineBasicBlock *MBB,
325                            MachineBasicBlock::iterator MI,
326                            SlotIndex MIIdx,
327                            MachineOperand& MO, unsigned MOIdx);
328
329     /// isPartialRedef - Return true if the specified def at the specific index
330     /// is partially re-defining the specified live interval. A common case of
331     /// this is a definition of the sub-register.
332     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
333                         LiveInterval &interval);
334
335     /// handleVirtualRegisterDef - update intervals for a virtual
336     /// register def
337     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
338                                   MachineBasicBlock::iterator MI,
339                                   SlotIndex MIIdx, MachineOperand& MO,
340                                   unsigned MOIdx,
341                                   LiveInterval& interval);
342
343     /// handlePhysicalRegisterDef - update intervals for a physical register
344     /// def.
345     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
346                                    MachineBasicBlock::iterator mi,
347                                    SlotIndex MIIdx, MachineOperand& MO,
348                                    LiveInterval &interval,
349                                    MachineInstr *CopyMI);
350
351     /// handleLiveInRegister - Create interval for a livein register.
352     void handleLiveInRegister(MachineBasicBlock* mbb,
353                               SlotIndex MIIdx,
354                               LiveInterval &interval, bool isAlias = false);
355
356     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
357     /// only allow one) virtual register operand, then its uses are implicitly
358     /// using the register. Returns the virtual register.
359     unsigned getReMatImplicitUse(const LiveInterval &li,
360                                  MachineInstr *MI) const;
361
362     /// isValNoAvailableAt - Return true if the val# of the specified interval
363     /// which reaches the given instruction also reaches the specified use
364     /// index.
365     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
366                             SlotIndex UseIdx) const;
367
368     /// isReMaterializable - Returns true if the definition MI of the specified
369     /// val# of the specified interval is re-materializable. Also returns true
370     /// by reference if the def is a load.
371     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
372                             MachineInstr *MI,
373                             const SmallVectorImpl<LiveInterval*> &SpillIs,
374                             bool &isLoad);
375
376     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
377     /// slot / to reg or any rematerialized load into ith operand of specified
378     /// MI. If it is successul, MI is updated with the newly created MI and
379     /// returns true.
380     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
381                               MachineInstr *DefMI, SlotIndex InstrIdx,
382                               SmallVector<unsigned, 2> &Ops,
383                               bool isSS, int FrameIndex, unsigned Reg);
384
385     /// canFoldMemoryOperand - Return true if the specified load / store
386     /// folding is possible.
387     bool canFoldMemoryOperand(MachineInstr *MI,
388                               SmallVector<unsigned, 2> &Ops,
389                               bool ReMatLoadSS) const;
390
391     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
392     /// VNInfo that's after the specified index but is within the basic block.
393     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
394                               MachineBasicBlock *MBB,
395                               SlotIndex Idx) const;
396
397     /// hasAllocatableSuperReg - Return true if the specified physical register
398     /// has any super register that's allocatable.
399     bool hasAllocatableSuperReg(unsigned Reg) const;
400
401     /// SRInfo - Spill / restore info.
402     struct SRInfo {
403       SlotIndex index;
404       unsigned vreg;
405       bool canFold;
406       SRInfo(SlotIndex i, unsigned vr, bool f)
407         : index(i), vreg(vr), canFold(f) {}
408     };
409
410     bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
411                           BitVector &RestoreMBBs,
412                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
413     void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
414                           BitVector &RestoreMBBs,
415                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
416
417     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
418     /// spilled and create empty intervals for their uses.
419     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
420                               const TargetRegisterClass* rc,
421                               std::vector<LiveInterval*> &NewLIs);
422
423     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
424     /// interval on to-be re-materialized operands of MI) with new register.
425     void rewriteImplicitOps(const LiveInterval &li,
426                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
427
428     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
429     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
430     /// live range.
431     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
432         bool TrySplit, SlotIndex index, SlotIndex end,
433         MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
434         unsigned Slot, int LdSlot,
435         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
436         VirtRegMap &vrm, const TargetRegisterClass* rc,
437         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
438         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
439         DenseMap<unsigned,unsigned> &MBBVRegsMap,
440         std::vector<LiveInterval*> &NewLIs);
441     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
442         LiveInterval::Ranges::const_iterator &I,
443         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
444         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
445         VirtRegMap &vrm, const TargetRegisterClass* rc,
446         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
447         BitVector &SpillMBBs,
448         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
449         BitVector &RestoreMBBs,
450         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
451         DenseMap<unsigned,unsigned> &MBBVRegsMap,
452         std::vector<LiveInterval*> &NewLIs);
453
454     // Normalize the spill weight of all the intervals in NewLIs.
455     void normalizeSpillWeights(std::vector<LiveInterval*> &NewLIs);
456
457     static LiveInterval* createInterval(unsigned Reg);
458
459     void printInstrs(raw_ostream &O) const;
460     void dumpInstrs() const;
461   };
462 } // End llvm namespace
463
464 #endif