1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Support/Allocator.h"
37 class MachineLoopInfo;
38 class TargetRegisterInfo;
39 class MachineRegisterInfo;
40 class TargetInstrInfo;
41 class TargetRegisterClass;
43 typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
45 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
49 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
53 struct Idx2MBBCompare {
54 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
55 return LHS.first < RHS.first;
59 class LiveIntervals : public MachineFunctionPass {
61 MachineRegisterInfo* mri_;
62 const TargetMachine* tm_;
63 const TargetRegisterInfo* tri_;
64 const TargetInstrInfo* tii_;
68 /// Special pool allocator for VNInfo's (LiveInterval val#).
70 BumpPtrAllocator VNInfoAllocator;
72 /// MBB2IdxMap - The indexes of the first and last instructions in the
73 /// specified basic block.
74 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
76 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
78 std::vector<IdxMBBPair> Idx2MBBMap;
80 /// FunctionSize - The number of instructions present in the function
81 uint64_t FunctionSize;
83 typedef DenseMap<const MachineInstr*, unsigned> Mi2IndexMap;
86 typedef std::vector<MachineInstr*> Index2MiMap;
89 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
90 Reg2IntervalMap r2iMap_;
92 DenseMap<MachineBasicBlock*, unsigned> terminatorGaps;
94 BitVector allocatableRegs_;
96 std::vector<MachineInstr*> ClonedMIs;
98 typedef LiveInterval::InstrSlots InstrSlots;
101 static char ID; // Pass identification, replacement for typeid
102 LiveIntervals() : MachineFunctionPass(&ID) {}
104 static unsigned getBaseIndex(unsigned index) {
105 return index - (index % InstrSlots::NUM);
107 static unsigned getBoundaryIndex(unsigned index) {
108 return getBaseIndex(index + InstrSlots::NUM - 1);
110 static unsigned getLoadIndex(unsigned index) {
111 return getBaseIndex(index) + InstrSlots::LOAD;
113 static unsigned getUseIndex(unsigned index) {
114 return getBaseIndex(index) + InstrSlots::USE;
116 static unsigned getDefIndex(unsigned index) {
117 return getBaseIndex(index) + InstrSlots::DEF;
119 static unsigned getStoreIndex(unsigned index) {
120 return getBaseIndex(index) + InstrSlots::STORE;
123 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
124 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
127 typedef Reg2IntervalMap::iterator iterator;
128 typedef Reg2IntervalMap::const_iterator const_iterator;
129 const_iterator begin() const { return r2iMap_.begin(); }
130 const_iterator end() const { return r2iMap_.end(); }
131 iterator begin() { return r2iMap_.begin(); }
132 iterator end() { return r2iMap_.end(); }
133 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
135 LiveInterval &getInterval(unsigned reg) {
136 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
137 assert(I != r2iMap_.end() && "Interval does not exist for register");
141 const LiveInterval &getInterval(unsigned reg) const {
142 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
143 assert(I != r2iMap_.end() && "Interval does not exist for register");
147 bool hasInterval(unsigned reg) const {
148 return r2iMap_.count(reg);
151 /// getMBBStartIdx - Return the base index of the first instruction in the
152 /// specified MachineBasicBlock.
153 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
154 return getMBBStartIdx(MBB->getNumber());
156 unsigned getMBBStartIdx(unsigned MBBNo) const {
157 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
158 return MBB2IdxMap[MBBNo].first;
161 /// getMBBEndIdx - Return the store index of the last instruction in the
162 /// specified MachineBasicBlock.
163 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
164 return getMBBEndIdx(MBB->getNumber());
166 unsigned getMBBEndIdx(unsigned MBBNo) const {
167 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
168 return MBB2IdxMap[MBBNo].second;
171 /// getScaledIntervalSize - get the size of an interval in "units,"
172 /// where every function is composed of one thousand units. This
173 /// measure scales properly with empty index slots in the function.
174 double getScaledIntervalSize(LiveInterval& I) {
175 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
178 /// getApproximateInstructionCount - computes an estimate of the number
179 /// of instructions in a given LiveInterval.
180 unsigned getApproximateInstructionCount(LiveInterval& I) {
181 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
182 return (unsigned)(IntervalPercentage * FunctionSize);
185 /// getMBBFromIndex - given an index in any instruction of an
186 /// MBB return a pointer the MBB
187 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
188 std::vector<IdxMBBPair>::const_iterator I =
189 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
190 // Take the pair containing the index
191 std::vector<IdxMBBPair>::const_iterator J =
192 ((I != Idx2MBBMap.end() && I->first > index) ||
193 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
195 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
196 index <= getMBBEndIdx(J->second) &&
197 "index does not correspond to an MBB");
201 /// getInstructionIndex - returns the base index of instr
202 unsigned getInstructionIndex(const MachineInstr* instr) const {
203 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
204 assert(it != mi2iMap_.end() && "Invalid instruction!");
208 /// getInstructionFromIndex - given an index in any slot of an
209 /// instruction return a pointer the instruction
210 MachineInstr* getInstructionFromIndex(unsigned index) const {
211 index /= InstrSlots::NUM; // convert index to vector index
212 assert(index < i2miMap_.size() &&
213 "index does not correspond to an instruction");
214 return i2miMap_[index];
217 /// hasGapBeforeInstr - Return true if the previous instruction slot,
218 /// i.e. Index - InstrSlots::NUM, is not occupied.
219 bool hasGapBeforeInstr(unsigned Index) {
220 Index = getBaseIndex(Index - InstrSlots::NUM);
221 return getInstructionFromIndex(Index) == 0;
224 /// hasGapAfterInstr - Return true if the successive instruction slot,
225 /// i.e. Index + InstrSlots::Num, is not occupied.
226 bool hasGapAfterInstr(unsigned Index) {
227 Index = getBaseIndex(Index + InstrSlots::NUM);
228 return getInstructionFromIndex(Index) == 0;
231 /// findGapBeforeInstr - Find an empty instruction slot before the
232 /// specified index. If "Furthest" is true, find one that's furthest
233 /// away from the index (but before any index that's occupied).
234 unsigned findGapBeforeInstr(unsigned Index, bool Furthest = false) {
235 Index = getBaseIndex(Index - InstrSlots::NUM);
236 if (getInstructionFromIndex(Index))
240 unsigned PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
241 while (getInstructionFromIndex(Index)) {
243 PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
248 /// InsertMachineInstrInMaps - Insert the specified machine instruction
249 /// into the instruction index map at the given index.
250 void InsertMachineInstrInMaps(MachineInstr *MI, unsigned Index) {
251 i2miMap_[Index / InstrSlots::NUM] = MI;
252 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
253 assert(it == mi2iMap_.end() && "Already in map!");
254 mi2iMap_[MI] = Index;
257 /// conflictsWithPhysRegDef - Returns true if the specified register
258 /// is defined during the duration of the specified interval.
259 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
262 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
263 /// it can check use as well.
264 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
266 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
268 /// findLiveInMBBs - Given a live range, if the value of the range
269 /// is live in any MBB returns true as well as the list of basic blocks
270 /// in which the value is live.
271 bool findLiveInMBBs(unsigned Start, unsigned End,
272 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
274 /// findReachableMBBs - Return a list MBB that can be reached via any
275 /// branch or fallthroughs. Return true if the list is not empty.
276 bool findReachableMBBs(unsigned Start, unsigned End,
277 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
281 LiveInterval &getOrCreateInterval(unsigned reg) {
282 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
283 if (I == r2iMap_.end())
284 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
288 /// dupInterval - Duplicate a live interval. The caller is responsible for
289 /// managing the allocated memory.
290 LiveInterval *dupInterval(LiveInterval *li);
292 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
293 /// adds a live range from that instruction to the end of its MBB.
294 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
295 MachineInstr* startInst);
299 void removeInterval(unsigned Reg) {
300 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
305 /// isNotInMIMap - returns true if the specified machine instr has been
306 /// removed or was never entered in the map.
307 bool isNotInMIMap(MachineInstr* instr) const {
308 return !mi2iMap_.count(instr);
311 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
313 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
314 // remove index -> MachineInstr and
315 // MachineInstr -> index mappings
316 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
317 if (mi2i != mi2iMap_.end()) {
318 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
319 mi2iMap_.erase(mi2i);
323 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
324 /// maps used by register allocator.
325 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
326 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
327 if (mi2i == mi2iMap_.end())
329 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
330 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
331 assert(it != mi2iMap_.end() && "Invalid instruction!");
332 unsigned Index = it->second;
334 mi2iMap_[NewMI] = Index;
337 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
339 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
340 /// copy field and returns the source register that defines it.
341 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
343 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
344 virtual void releaseMemory();
346 /// runOnMachineFunction - pass entry point
347 virtual bool runOnMachineFunction(MachineFunction&);
349 /// print - Implement the dump method.
350 virtual void print(raw_ostream &O, const Module* = 0) const;
352 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
353 /// the given interval. FIXME: It also returns the weight of the spill slot
354 /// (if any is created) by reference. This is temporary.
355 std::vector<LiveInterval*>
356 addIntervalsForSpills(const LiveInterval& i,
357 SmallVectorImpl<LiveInterval*> &SpillIs,
358 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
360 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
361 /// defs / uses without remat or splitting.
362 std::vector<LiveInterval*>
363 addIntervalsForSpillsFast(const LiveInterval &li,
364 const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
366 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
367 /// around all defs and uses of the specified interval. Return true if it
368 /// was able to cut its interval.
369 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
370 unsigned PhysReg, VirtRegMap &vrm);
372 /// isReMaterializable - Returns true if every definition of MI of every
373 /// val# of the specified interval is re-materializable. Also returns true
374 /// by reference if all of the defs are load instructions.
375 bool isReMaterializable(const LiveInterval &li,
376 SmallVectorImpl<LiveInterval*> &SpillIs,
379 /// isReMaterializable - Returns true if the definition MI of the specified
380 /// val# of the specified interval is re-materializable.
381 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
384 /// getRepresentativeReg - Find the largest super register of the specified
385 /// physical register.
386 unsigned getRepresentativeReg(unsigned Reg) const;
388 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
389 /// specified interval that conflicts with the specified physical register.
390 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
391 unsigned PhysReg) const;
393 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
394 /// marker to implicit_def defs and their uses.
395 void processImplicitDefs();
397 /// computeNumbering - Compute the index numbering.
398 void computeNumbering();
400 /// scaleNumbering - Rescale interval numbers to introduce gaps for new
402 void scaleNumbering(int factor);
404 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
405 /// within a single basic block.
406 bool intervalIsInOneMBB(const LiveInterval &li) const;
409 /// computeIntervals - Compute live intervals.
410 void computeIntervals();
412 /// handleRegisterDef - update intervals for a register def
413 /// (calls handlePhysicalRegisterDef and
414 /// handleVirtualRegisterDef)
415 void handleRegisterDef(MachineBasicBlock *MBB,
416 MachineBasicBlock::iterator MI, unsigned MIIdx,
417 MachineOperand& MO, unsigned MOIdx);
419 /// handleVirtualRegisterDef - update intervals for a virtual
421 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
422 MachineBasicBlock::iterator MI,
423 unsigned MIIdx, MachineOperand& MO,
424 unsigned MOIdx, LiveInterval& interval);
426 /// handlePhysicalRegisterDef - update intervals for a physical register
428 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
429 MachineBasicBlock::iterator mi,
430 unsigned MIIdx, MachineOperand& MO,
431 LiveInterval &interval,
432 MachineInstr *CopyMI);
434 /// handleLiveInRegister - Create interval for a livein register.
435 void handleLiveInRegister(MachineBasicBlock* mbb,
437 LiveInterval &interval, bool isAlias = false);
439 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
440 /// only allow one) virtual register operand, then its uses are implicitly
441 /// using the register. Returns the virtual register.
442 unsigned getReMatImplicitUse(const LiveInterval &li,
443 MachineInstr *MI) const;
445 /// isValNoAvailableAt - Return true if the val# of the specified interval
446 /// which reaches the given instruction also reaches the specified use
448 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
449 unsigned UseIdx) const;
451 /// isReMaterializable - Returns true if the definition MI of the specified
452 /// val# of the specified interval is re-materializable. Also returns true
453 /// by reference if the def is a load.
454 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
456 SmallVectorImpl<LiveInterval*> &SpillIs,
459 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
460 /// slot / to reg or any rematerialized load into ith operand of specified
461 /// MI. If it is successul, MI is updated with the newly created MI and
463 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
464 MachineInstr *DefMI, unsigned InstrIdx,
465 SmallVector<unsigned, 2> &Ops,
466 bool isSS, int Slot, unsigned Reg);
468 /// canFoldMemoryOperand - Return true if the specified load / store
469 /// folding is possible.
470 bool canFoldMemoryOperand(MachineInstr *MI,
471 SmallVector<unsigned, 2> &Ops,
472 bool ReMatLoadSS) const;
474 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
475 /// VNInfo that's after the specified index but is within the basic block.
476 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
477 MachineBasicBlock *MBB, unsigned Idx) const;
479 /// hasAllocatableSuperReg - Return true if the specified physical register
480 /// has any super register that's allocatable.
481 bool hasAllocatableSuperReg(unsigned Reg) const;
483 /// SRInfo - Spill / restore info.
488 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
491 bool alsoFoldARestore(int Id, int index, unsigned vr,
492 BitVector &RestoreMBBs,
493 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
494 void eraseRestoreInfo(int Id, int index, unsigned vr,
495 BitVector &RestoreMBBs,
496 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
498 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
499 /// spilled and create empty intervals for their uses.
500 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
501 const TargetRegisterClass* rc,
502 std::vector<LiveInterval*> &NewLIs);
504 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
505 /// interval on to-be re-materialized operands of MI) with new register.
506 void rewriteImplicitOps(const LiveInterval &li,
507 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
509 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
510 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
512 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
513 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
514 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
515 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
516 VirtRegMap &vrm, const TargetRegisterClass* rc,
517 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
518 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
519 DenseMap<unsigned,unsigned> &MBBVRegsMap,
520 std::vector<LiveInterval*> &NewLIs);
521 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
522 LiveInterval::Ranges::const_iterator &I,
523 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
524 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
525 VirtRegMap &vrm, const TargetRegisterClass* rc,
526 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
527 BitVector &SpillMBBs,
528 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
529 BitVector &RestoreMBBs,
530 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
531 DenseMap<unsigned,unsigned> &MBBVRegsMap,
532 std::vector<LiveInterval*> &NewLIs);
534 static LiveInterval* createInterval(unsigned Reg);
536 void printRegName(unsigned reg) const;
538 } // End llvm namespace