Add an allnodes_size method.
[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/MachineFunctionPass.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
30 #include <cmath>
31 #include <map>
32
33 namespace llvm {
34
35   class LiveVariables;
36   class MachineLoopInfo;
37   class TargetRegisterInfo;
38   class MachineRegisterInfo;
39   class TargetInstrInfo;
40   class TargetRegisterClass;
41   class VirtRegMap;
42   typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
43
44   inline bool operator<(unsigned V, const IdxMBBPair &IM) {
45     return V < IM.first;
46   }
47
48   inline bool operator<(const IdxMBBPair &IM, unsigned V) {
49     return IM.first < V;
50   }
51
52   struct Idx2MBBCompare {
53     bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
54       return LHS.first < RHS.first;
55     }
56   };
57
58   class LiveIntervals : public MachineFunctionPass {
59     MachineFunction* mf_;
60     MachineRegisterInfo* mri_;
61     const TargetMachine* tm_;
62     const TargetRegisterInfo* tri_;
63     const TargetInstrInfo* tii_;
64     LiveVariables* lv_;
65
66     /// Special pool allocator for VNInfo's (LiveInterval val#).
67     ///
68     BumpPtrAllocator VNInfoAllocator;
69
70     /// MBB2IdxMap - The indexes of the first and last instructions in the
71     /// specified basic block.
72     std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
73
74     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
75     /// and MBB id.
76     std::vector<IdxMBBPair> Idx2MBBMap;
77
78     typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
79     Mi2IndexMap mi2iMap_;
80
81     typedef std::vector<MachineInstr*> Index2MiMap;
82     Index2MiMap i2miMap_;
83
84     typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
85     Reg2IntervalMap r2iMap_;
86
87     BitVector allocatableRegs_;
88
89     std::vector<MachineInstr*> ClonedMIs;
90
91   public:
92     static char ID; // Pass identification, replacement for typeid
93     LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
94
95     struct InstrSlots {
96       enum {
97         LOAD  = 0,
98         USE   = 1,
99         DEF   = 2,
100         STORE = 3,
101         NUM   = 4
102       };
103     };
104
105     static unsigned getBaseIndex(unsigned index) {
106       return index - (index % InstrSlots::NUM);
107     }
108     static unsigned getBoundaryIndex(unsigned index) {
109       return getBaseIndex(index + InstrSlots::NUM - 1);
110     }
111     static unsigned getLoadIndex(unsigned index) {
112       return getBaseIndex(index) + InstrSlots::LOAD;
113     }
114     static unsigned getUseIndex(unsigned index) {
115       return getBaseIndex(index) + InstrSlots::USE;
116     }
117     static unsigned getDefIndex(unsigned index) {
118       return getBaseIndex(index) + InstrSlots::DEF;
119     }
120     static unsigned getStoreIndex(unsigned index) {
121       return getBaseIndex(index) + InstrSlots::STORE;
122     }
123
124     static float getSpillWeight(bool isDef, bool isUse, bool isMem,
125                                 unsigned loopDepth) {
126       float Weight = isDef;
127       if (isUse)
128         Weight += isMem ? 1.2f : 1.0f;
129       return Weight * powf(10.0F, (float)loopDepth);
130     }
131
132     typedef Reg2IntervalMap::iterator iterator;
133     typedef Reg2IntervalMap::const_iterator const_iterator;
134     const_iterator begin() const { return r2iMap_.begin(); }
135     const_iterator end() const { return r2iMap_.end(); }
136     iterator begin() { return r2iMap_.begin(); }
137     iterator end() { return r2iMap_.end(); }
138     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
139
140     LiveInterval &getInterval(unsigned reg) {
141       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
142       assert(I != r2iMap_.end() && "Interval does not exist for register");
143       return I->second;
144     }
145
146     const LiveInterval &getInterval(unsigned reg) const {
147       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
148       assert(I != r2iMap_.end() && "Interval does not exist for register");
149       return I->second;
150     }
151
152     bool hasInterval(unsigned reg) const {
153       return r2iMap_.count(reg);
154     }
155
156     /// getMBBStartIdx - Return the base index of the first instruction in the
157     /// specified MachineBasicBlock.
158     unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
159       return getMBBStartIdx(MBB->getNumber());
160     }
161     unsigned getMBBStartIdx(unsigned MBBNo) const {
162       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
163       return MBB2IdxMap[MBBNo].first;
164     }
165
166     /// getMBBEndIdx - Return the store index of the last instruction in the
167     /// specified MachineBasicBlock.
168     unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
169       return getMBBEndIdx(MBB->getNumber());
170     }
171     unsigned getMBBEndIdx(unsigned MBBNo) const {
172       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
173       return MBB2IdxMap[MBBNo].second;
174     }
175
176     /// getMBBFromIndex - given an index in any instruction of an
177     /// MBB return a pointer the MBB
178     MachineBasicBlock* getMBBFromIndex(unsigned index) const {
179       std::vector<IdxMBBPair>::const_iterator I =
180         std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
181       // Take the pair containing the index
182       std::vector<IdxMBBPair>::const_iterator J =
183         ((I != Idx2MBBMap.end() && I->first > index) ||
184          (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
185
186       assert(J != Idx2MBBMap.end() && J->first < index+1 &&
187              index <= getMBBEndIdx(J->second) &&
188              "index does not correspond to an MBB");
189       return J->second;
190     }
191
192     /// getInstructionIndex - returns the base index of instr
193     unsigned getInstructionIndex(MachineInstr* instr) const {
194       Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
195       assert(it != mi2iMap_.end() && "Invalid instruction!");
196       return it->second;
197     }
198
199     /// getInstructionFromIndex - given an index in any slot of an
200     /// instruction return a pointer the instruction
201     MachineInstr* getInstructionFromIndex(unsigned index) const {
202       index /= InstrSlots::NUM; // convert index to vector index
203       assert(index < i2miMap_.size() &&
204              "index does not correspond to an instruction");
205       return i2miMap_[index];
206     }
207
208     /// conflictsWithPhysRegDef - Returns true if the specified register
209     /// is defined during the duration of the specified interval.
210     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
211                                  unsigned reg);
212
213     /// findLiveInMBBs - Given a live range, if the value of the range
214     /// is live in any MBB returns true as well as the list of basic blocks
215     /// where the value is live in.
216     bool findLiveInMBBs(const LiveRange &LR,
217                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
218
219     // Interval creation
220
221     LiveInterval &getOrCreateInterval(unsigned reg) {
222       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
223       if (I == r2iMap_.end())
224         I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
225       return I->second;
226     }
227     
228     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
229     /// adds a live range from that instruction to the end of its MBB.
230     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
231                                         MachineInstr* startInst);
232
233     // Interval removal
234
235     void removeInterval(unsigned Reg) {
236       r2iMap_.erase(Reg);
237     }
238
239     /// isRemoved - returns true if the specified machine instr has been
240     /// removed.
241     bool isRemoved(MachineInstr* instr) const {
242       return !mi2iMap_.count(instr);
243     }
244
245     /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
246     /// deleted.
247     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
248       // remove index -> MachineInstr and
249       // MachineInstr -> index mappings
250       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
251       if (mi2i != mi2iMap_.end()) {
252         i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
253         mi2iMap_.erase(mi2i);
254       }
255     }
256
257     /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
258     /// maps used by register allocator.
259     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
260       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
261       if (mi2i == mi2iMap_.end())
262         return;
263       i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
264       Mi2IndexMap::iterator it = mi2iMap_.find(MI);
265       assert(it != mi2iMap_.end() && "Invalid instruction!");
266       unsigned Index = it->second;
267       mi2iMap_.erase(it);
268       mi2iMap_[NewMI] = Index;
269     }
270
271     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
272
273     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
274     /// copy field and returns the source register that defines it.
275     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
276
277     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
278     virtual void releaseMemory();
279
280     /// runOnMachineFunction - pass entry point
281     virtual bool runOnMachineFunction(MachineFunction&);
282
283     /// print - Implement the dump method.
284     virtual void print(std::ostream &O, const Module* = 0) const;
285     void print(std::ostream *O, const Module* M = 0) const {
286       if (O) print(*O, M);
287     }
288
289     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
290     /// the given interval. FIXME: It also returns the weight of the spill slot
291     /// (if any is created) by reference. This is temporary.
292     std::vector<LiveInterval*>
293     addIntervalsForSpills(const LiveInterval& i,
294                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
295                           float &SSWeight);
296
297     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
298     /// around all defs and uses of the specified interval.
299     void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
300                                        unsigned PhysReg, VirtRegMap &vrm);
301
302     /// isReMaterializable - Returns true if every definition of MI of every
303     /// val# of the specified interval is re-materializable. Also returns true
304     /// by reference if all of the defs are load instructions.
305     bool isReMaterializable(const LiveInterval &li, bool &isLoad);
306
307     /// getRepresentativeReg - Find the largest super register of the specified
308     /// physical register.
309     unsigned getRepresentativeReg(unsigned Reg) const;
310
311     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
312     /// specified interval that conflicts with the specified physical register.
313     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
314                                         unsigned PhysReg) const;
315
316     /// computeNumbering - Compute the index numbering.
317     void computeNumbering();
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, unsigned MIIdx,
328                            unsigned reg);
329
330     /// handleVirtualRegisterDef - update intervals for a virtual
331     /// register def
332     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
333                                   MachineBasicBlock::iterator MI,
334                                   unsigned MIIdx,
335                                   LiveInterval& interval);
336
337     /// handlePhysicalRegisterDef - update intervals for a physical register
338     /// def.
339     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
340                                    MachineBasicBlock::iterator mi,
341                                    unsigned MIIdx,
342                                    LiveInterval &interval,
343                                    MachineInstr *CopyMI);
344
345     /// handleLiveInRegister - Create interval for a livein register.
346     void handleLiveInRegister(MachineBasicBlock* mbb,
347                               unsigned MIIdx,
348                               LiveInterval &interval, bool isAlias = false);
349
350     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
351     /// only allow one) virtual register operand, then its uses are implicitly
352     /// using the register. Returns the virtual register.
353     unsigned getReMatImplicitUse(const LiveInterval &li,
354                                  MachineInstr *MI) const;
355
356     /// isValNoAvailableAt - Return true if the val# of the specified interval
357     /// which reaches the given instruction also reaches the specified use
358     /// index.
359     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
360                             unsigned UseIdx) const;
361
362     /// isReMaterializable - Returns true if the definition MI of the specified
363     /// val# of the specified interval is re-materializable. Also returns true
364     /// by reference if the def is a load.
365     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
366                             MachineInstr *MI, bool &isLoad);
367
368     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
369     /// slot / to reg or any rematerialized load into ith operand of specified
370     /// MI. If it is successul, MI is updated with the newly created MI and
371     /// returns true.
372     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
373                               MachineInstr *DefMI, unsigned InstrIdx,
374                               SmallVector<unsigned, 2> &Ops,
375                               bool isSS, int Slot, unsigned Reg);
376
377     /// canFoldMemoryOperand - Return true if the specified load / store
378     /// folding is possible.
379     bool canFoldMemoryOperand(MachineInstr *MI,
380                               SmallVector<unsigned, 2> &Ops,
381                               bool ReMatLoadSS) const;
382
383     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
384     /// VNInfo that's after the specified index but is within the basic block.
385     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
386                               MachineBasicBlock *MBB, unsigned Idx) const;
387
388     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
389     /// within a single basic block.
390     bool intervalIsInOneMBB(const LiveInterval &li) const;
391
392     /// hasAllocatableSuperReg - Return true if the specified physical register
393     /// has any super register that's allocatable.
394     bool hasAllocatableSuperReg(unsigned Reg) const;
395
396     /// SRInfo - Spill / restore info.
397     struct SRInfo {
398       int index;
399       unsigned vreg;
400       bool canFold;
401       SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
402     };
403
404     bool alsoFoldARestore(int Id, int index, unsigned vr,
405                           BitVector &RestoreMBBs,
406                           std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
407     void eraseRestoreInfo(int Id, int index, unsigned vr,
408                           BitVector &RestoreMBBs,
409                           std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
410
411     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
412     /// spilled and create empty intervals for their uses.
413     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
414                               const TargetRegisterClass* rc,
415                               std::vector<LiveInterval*> &NewLIs);
416
417     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
418     /// interval on to-be re-materialized operands of MI) with new register.
419     void rewriteImplicitOps(const LiveInterval &li,
420                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
421
422     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
423     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
424     /// live range.
425     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
426         bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
427         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
428         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
429         VirtRegMap &vrm, const TargetRegisterClass* rc,
430         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
431         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
432         std::map<unsigned,unsigned> &MBBVRegsMap,
433         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
434     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
435         LiveInterval::Ranges::const_iterator &I,
436         MachineInstr *OrigDefMI, MachineInstr *DefMI, 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         BitVector &SpillMBBs,
441         std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
442         BitVector &RestoreMBBs,
443         std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
444         std::map<unsigned,unsigned> &MBBVRegsMap,
445         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
446
447     static LiveInterval createInterval(unsigned Reg);
448
449     void printRegName(unsigned reg) const;
450   };
451
452 } // End llvm namespace
453
454 #endif