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