Fix PR3486. Fix a bug in code that manually patch physical register live interval...
[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
32 namespace llvm {
33
34   class AliasAnalysis;
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     AliasAnalysis *aa_;
65     LiveVariables* lv_;
66
67     /// Special pool allocator for VNInfo's (LiveInterval val#).
68     ///
69     BumpPtrAllocator VNInfoAllocator;
70
71     /// MBB2IdxMap - The indexes of the first and last instructions in the
72     /// specified basic block.
73     std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
74
75     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
76     /// and MBB id.
77     std::vector<IdxMBBPair> Idx2MBBMap;
78
79     /// FunctionSize - The number of instructions present in the function
80     uint64_t FunctionSize;
81
82     typedef DenseMap<MachineInstr*, unsigned> Mi2IndexMap;
83     Mi2IndexMap mi2iMap_;
84
85     typedef std::vector<MachineInstr*> Index2MiMap;
86     Index2MiMap i2miMap_;
87
88     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
89     Reg2IntervalMap r2iMap_;
90
91     BitVector allocatableRegs_;
92
93     std::vector<MachineInstr*> ClonedMIs;
94
95   public:
96     static char ID; // Pass identification, replacement for typeid
97     LiveIntervals() : MachineFunctionPass(&ID) {}
98
99     struct InstrSlots {
100       enum {
101         LOAD  = 0,
102         USE   = 1,
103         DEF   = 2,
104         STORE = 3,
105         NUM   = 4
106       };
107     };
108
109     static unsigned getBaseIndex(unsigned index) {
110       return index - (index % InstrSlots::NUM);
111     }
112     static unsigned getBoundaryIndex(unsigned index) {
113       return getBaseIndex(index + InstrSlots::NUM - 1);
114     }
115     static unsigned getLoadIndex(unsigned index) {
116       return getBaseIndex(index) + InstrSlots::LOAD;
117     }
118     static unsigned getUseIndex(unsigned index) {
119       return getBaseIndex(index) + InstrSlots::USE;
120     }
121     static unsigned getDefIndex(unsigned index) {
122       return getBaseIndex(index) + InstrSlots::DEF;
123     }
124     static unsigned getStoreIndex(unsigned index) {
125       return getBaseIndex(index) + InstrSlots::STORE;
126     }
127
128     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
129       return (isDef + isUse) * 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     /// getScaledIntervalSize - get the size of an interval in "units,"
177     /// where every function is composed of one thousand units.  This
178     /// measure scales properly with empty index slots in the function.
179     double getScaledIntervalSize(LiveInterval& I) {
180       return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
181     }
182     
183     /// getApproximateInstructionCount - computes an estimate of the number
184     /// of instructions in a given LiveInterval.
185     unsigned getApproximateInstructionCount(LiveInterval& I) {
186       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
187       return (unsigned)(IntervalPercentage * FunctionSize);
188     }
189
190     /// getMBBFromIndex - given an index in any instruction of an
191     /// MBB return a pointer the MBB
192     MachineBasicBlock* getMBBFromIndex(unsigned index) const {
193       std::vector<IdxMBBPair>::const_iterator I =
194         std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
195       // Take the pair containing the index
196       std::vector<IdxMBBPair>::const_iterator J =
197         ((I != Idx2MBBMap.end() && I->first > index) ||
198          (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
199
200       assert(J != Idx2MBBMap.end() && J->first < index+1 &&
201              index <= getMBBEndIdx(J->second) &&
202              "index does not correspond to an MBB");
203       return J->second;
204     }
205
206     /// getInstructionIndex - returns the base index of instr
207     unsigned getInstructionIndex(MachineInstr* instr) const {
208       Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
209       assert(it != mi2iMap_.end() && "Invalid instruction!");
210       return it->second;
211     }
212
213     /// getInstructionFromIndex - given an index in any slot of an
214     /// instruction return a pointer the instruction
215     MachineInstr* getInstructionFromIndex(unsigned index) const {
216       index /= InstrSlots::NUM; // convert index to vector index
217       assert(index < i2miMap_.size() &&
218              "index does not correspond to an instruction");
219       return i2miMap_[index];
220     }
221
222     /// hasGapBeforeInstr - Return true if the previous instruction slot,
223     /// i.e. Index - InstrSlots::NUM, is not occupied.
224     bool hasGapBeforeInstr(unsigned Index) {
225       Index = getBaseIndex(Index - InstrSlots::NUM);
226       return getInstructionFromIndex(Index) == 0;
227     }
228
229     /// findGapBeforeInstr - Find an empty instruction slot before the
230     /// specified index. If "Furthest" is true, find one that's furthest
231     /// away from the index (but before any index that's occupied).
232     unsigned findGapBeforeInstr(unsigned Index, bool Furthest = false) {
233       Index = getBaseIndex(Index - InstrSlots::NUM);
234       if (getInstructionFromIndex(Index))
235         return 0;  // No gap!
236       if (!Furthest)
237         return Index;
238       unsigned PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
239       while (getInstructionFromIndex(Index)) {
240         Index = PrevIndex;
241         PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
242       }
243       return Index;
244     }
245
246     /// InsertMachineInstrInMaps - Insert the specified machine instruction
247     /// into the instruction index map at the given index.
248     void InsertMachineInstrInMaps(MachineInstr *MI, unsigned Index) {
249       i2miMap_[Index / InstrSlots::NUM] = MI;
250       Mi2IndexMap::iterator it = mi2iMap_.find(MI);
251       assert(it == mi2iMap_.end() && "Already in map!");
252       mi2iMap_[MI] = Index;
253     }
254
255     /// conflictsWithPhysRegDef - Returns true if the specified register
256     /// is defined during the duration of the specified interval.
257     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
258                                  unsigned reg);
259
260     /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
261     /// it can check use as well.
262     bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
263                                  bool CheckUse,
264                                  SmallPtrSet<MachineInstr*,32> &JoinedCopies);
265
266     /// findLiveInMBBs - Given a live range, if the value of the range
267     /// is live in any MBB returns true as well as the list of basic blocks
268     /// in which the value is live.
269     bool findLiveInMBBs(unsigned Start, unsigned End,
270                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
271
272     /// findReachableMBBs - Return a list MBB that can be reached via any
273     /// branch or fallthroughs. Return true if the list is not empty.
274     bool findReachableMBBs(unsigned Start, unsigned End,
275                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
276
277     // Interval creation
278
279     LiveInterval &getOrCreateInterval(unsigned reg) {
280       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
281       if (I == r2iMap_.end())
282         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
283       return *I->second;
284     }
285
286     /// dupInterval - Duplicate a live interval. The caller is responsible for
287     /// managing the allocated memory.
288     LiveInterval *dupInterval(LiveInterval *li);
289     
290     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
291     /// adds a live range from that instruction to the end of its MBB.
292     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
293                                         MachineInstr* startInst);
294
295     // Interval removal
296
297     void removeInterval(unsigned Reg) {
298       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
299       delete I->second;
300       r2iMap_.erase(I);
301     }
302
303     /// isRemoved - returns true if the specified machine instr has been
304     /// removed.
305     bool isRemoved(MachineInstr* instr) const {
306       return !mi2iMap_.count(instr);
307     }
308
309     /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
310     /// deleted.
311     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
312       // remove index -> MachineInstr and
313       // MachineInstr -> index mappings
314       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
315       if (mi2i != mi2iMap_.end()) {
316         i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
317         mi2iMap_.erase(mi2i);
318       }
319     }
320
321     /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
322     /// maps used by register allocator.
323     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
324       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
325       if (mi2i == mi2iMap_.end())
326         return;
327       i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
328       Mi2IndexMap::iterator it = mi2iMap_.find(MI);
329       assert(it != mi2iMap_.end() && "Invalid instruction!");
330       unsigned Index = it->second;
331       mi2iMap_.erase(it);
332       mi2iMap_[NewMI] = Index;
333     }
334
335     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
336
337     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
338     /// copy field and returns the source register that defines it.
339     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
340
341     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
342     virtual void releaseMemory();
343
344     /// runOnMachineFunction - pass entry point
345     virtual bool runOnMachineFunction(MachineFunction&);
346
347     /// print - Implement the dump method.
348     virtual void print(std::ostream &O, const Module* = 0) const;
349     void print(std::ostream *O, const Module* M = 0) const {
350       if (O) print(*O, M);
351     }
352
353     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
354     /// the given interval. FIXME: It also returns the weight of the spill slot
355     /// (if any is created) by reference. This is temporary.
356     std::vector<LiveInterval*>
357     addIntervalsForSpills(const LiveInterval& i,
358                           SmallVectorImpl<LiveInterval*> &SpillIs,
359                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
360                           float &SSWeight);
361     
362     /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
363     /// defs / uses without remat or splitting.
364     std::vector<LiveInterval*>
365     addIntervalsForSpillsFast(const LiveInterval &li,
366                               const MachineLoopInfo *loopInfo,
367                               VirtRegMap &vrm, float& SSWeight);
368
369     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
370     /// around all defs and uses of the specified interval.
371     void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
372                                        unsigned PhysReg, VirtRegMap &vrm);
373
374     /// isReMaterializable - Returns true if every definition of MI of every
375     /// val# of the specified interval is re-materializable. Also returns true
376     /// by reference if all of the defs are load instructions.
377     bool isReMaterializable(const LiveInterval &li,
378                             SmallVectorImpl<LiveInterval*> &SpillIs,
379                             bool &isLoad);
380
381     /// isReMaterializable - Returns true if the definition MI of the specified
382     /// val# of the specified interval is re-materializable.
383     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
384                             MachineInstr *MI);
385
386     /// getRepresentativeReg - Find the largest super register of the specified
387     /// physical register.
388     unsigned getRepresentativeReg(unsigned Reg) const;
389
390     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
391     /// specified interval that conflicts with the specified physical register.
392     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
393                                         unsigned PhysReg) const;
394
395     /// computeNumbering - Compute the index numbering.
396     void computeNumbering();
397
398     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
399     /// within a single basic block.
400     bool intervalIsInOneMBB(const LiveInterval &li) const;
401
402   private:      
403     /// computeIntervals - Compute live intervals.
404     void computeIntervals();
405     
406     /// handleRegisterDef - update intervals for a register def
407     /// (calls handlePhysicalRegisterDef and
408     /// handleVirtualRegisterDef)
409     void handleRegisterDef(MachineBasicBlock *MBB,
410                            MachineBasicBlock::iterator MI, unsigned MIIdx,
411                            MachineOperand& MO, unsigned MOIdx);
412
413     /// handleVirtualRegisterDef - update intervals for a virtual
414     /// register def
415     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
416                                   MachineBasicBlock::iterator MI,
417                                   unsigned MIIdx, MachineOperand& MO,
418                                   unsigned MOIdx, LiveInterval& interval);
419
420     /// handlePhysicalRegisterDef - update intervals for a physical register
421     /// def.
422     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
423                                    MachineBasicBlock::iterator mi,
424                                    unsigned MIIdx, MachineOperand& MO,
425                                    LiveInterval &interval,
426                                    MachineInstr *CopyMI);
427
428     /// handleLiveInRegister - Create interval for a livein register.
429     void handleLiveInRegister(MachineBasicBlock* mbb,
430                               unsigned MIIdx,
431                               LiveInterval &interval, bool isAlias = false);
432
433     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
434     /// only allow one) virtual register operand, then its uses are implicitly
435     /// using the register. Returns the virtual register.
436     unsigned getReMatImplicitUse(const LiveInterval &li,
437                                  MachineInstr *MI) const;
438
439     /// isValNoAvailableAt - Return true if the val# of the specified interval
440     /// which reaches the given instruction also reaches the specified use
441     /// index.
442     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
443                             unsigned UseIdx) const;
444
445     /// isReMaterializable - Returns true if the definition MI of the specified
446     /// val# of the specified interval is re-materializable. Also returns true
447     /// by reference if the def is a load.
448     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
449                             MachineInstr *MI,
450                             SmallVectorImpl<LiveInterval*> &SpillIs,
451                             bool &isLoad);
452
453     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
454     /// slot / to reg or any rematerialized load into ith operand of specified
455     /// MI. If it is successul, MI is updated with the newly created MI and
456     /// returns true.
457     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
458                               MachineInstr *DefMI, unsigned InstrIdx,
459                               SmallVector<unsigned, 2> &Ops,
460                               bool isSS, int Slot, unsigned Reg);
461
462     /// canFoldMemoryOperand - Return true if the specified load / store
463     /// folding is possible.
464     bool canFoldMemoryOperand(MachineInstr *MI,
465                               SmallVector<unsigned, 2> &Ops,
466                               bool ReMatLoadSS) const;
467
468     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
469     /// VNInfo that's after the specified index but is within the basic block.
470     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
471                               MachineBasicBlock *MBB, unsigned Idx) const;
472
473     /// hasAllocatableSuperReg - Return true if the specified physical register
474     /// has any super register that's allocatable.
475     bool hasAllocatableSuperReg(unsigned Reg) const;
476
477     /// SRInfo - Spill / restore info.
478     struct SRInfo {
479       int index;
480       unsigned vreg;
481       bool canFold;
482       SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
483     };
484
485     bool alsoFoldARestore(int Id, int index, unsigned vr,
486                           BitVector &RestoreMBBs,
487                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
488     void eraseRestoreInfo(int Id, int index, unsigned vr,
489                           BitVector &RestoreMBBs,
490                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
491
492     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
493     /// spilled and create empty intervals for their uses.
494     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
495                               const TargetRegisterClass* rc,
496                               std::vector<LiveInterval*> &NewLIs);
497
498     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
499     /// interval on to-be re-materialized operands of MI) with new register.
500     void rewriteImplicitOps(const LiveInterval &li,
501                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
502
503     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
504     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
505     /// live range.
506     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
507         bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
508         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
509         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
510         VirtRegMap &vrm, const TargetRegisterClass* rc,
511         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
512         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
513         DenseMap<unsigned,unsigned> &MBBVRegsMap,
514         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
515     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
516         LiveInterval::Ranges::const_iterator &I,
517         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
518         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
519         VirtRegMap &vrm, const TargetRegisterClass* rc,
520         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
521         BitVector &SpillMBBs,
522         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
523         BitVector &RestoreMBBs,
524         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
525         DenseMap<unsigned,unsigned> &MBBVRegsMap,
526         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
527
528     static LiveInterval* createInterval(unsigned Reg);
529
530     void printRegName(unsigned reg) const;
531   };
532
533 } // End llvm namespace
534
535 #endif