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/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"
35 class MachineLoopInfo;
36 class TargetRegisterInfo;
37 class MachineRegisterInfo;
38 class TargetInstrInfo;
39 class TargetRegisterClass;
41 typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
43 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
47 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
51 struct Idx2MBBCompare {
52 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
53 return LHS.first < RHS.first;
57 class LiveIntervals : public MachineFunctionPass {
59 MachineRegisterInfo* mri_;
60 const TargetMachine* tm_;
61 const TargetRegisterInfo* tri_;
62 const TargetInstrInfo* tii_;
65 /// Special pool allocator for VNInfo's (LiveInterval val#).
67 BumpPtrAllocator VNInfoAllocator;
69 /// MBB2IdxMap - The indexes of the first and last instructions in the
70 /// specified basic block.
71 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
73 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
75 std::vector<IdxMBBPair> Idx2MBBMap;
77 typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
80 typedef std::vector<MachineInstr*> Index2MiMap;
83 typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
84 Reg2IntervalMap r2iMap_;
86 BitVector allocatableRegs_;
88 std::vector<MachineInstr*> ClonedMIs;
91 static char ID; // Pass identification, replacement for typeid
92 LiveIntervals() : MachineFunctionPass((intptr_t)&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 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 /// getMBBFromIndex - given an index in any instruction of an
172 /// MBB return a pointer the MBB
173 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
174 std::vector<IdxMBBPair>::const_iterator I =
175 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
176 // Take the pair containing the index
177 std::vector<IdxMBBPair>::const_iterator J =
178 ((I != Idx2MBBMap.end() && I->first > index) ||
179 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
181 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
182 index <= getMBBEndIdx(J->second) &&
183 "index does not correspond to an MBB");
187 /// getInstructionIndex - returns the base index of instr
188 unsigned getInstructionIndex(MachineInstr* instr) const {
189 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
190 assert(it != mi2iMap_.end() && "Invalid instruction!");
194 /// getInstructionFromIndex - given an index in any slot of an
195 /// instruction return a pointer the instruction
196 MachineInstr* getInstructionFromIndex(unsigned index) const {
197 index /= InstrSlots::NUM; // convert index to vector index
198 assert(index < i2miMap_.size() &&
199 "index does not correspond to an instruction");
200 return i2miMap_[index];
203 /// conflictsWithPhysRegDef - Returns true if the specified register
204 /// is defined during the duration of the specified interval.
205 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
208 /// findLiveInMBBs - Given a live range, if the value of the range
209 /// is live in any MBB returns true as well as the list of basic blocks
210 /// where the value is live in.
211 bool findLiveInMBBs(const LiveRange &LR,
212 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
216 LiveInterval &getOrCreateInterval(unsigned reg) {
217 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
218 if (I == r2iMap_.end())
219 I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
225 void removeInterval(unsigned Reg) {
229 /// isRemoved - returns true if the specified machine instr has been
231 bool isRemoved(MachineInstr* instr) const {
232 return !mi2iMap_.count(instr);
235 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
237 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
238 // remove index -> MachineInstr and
239 // MachineInstr -> index mappings
240 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
241 if (mi2i != mi2iMap_.end()) {
242 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
243 mi2iMap_.erase(mi2i);
247 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
248 /// maps used by register allocator.
249 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
250 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
251 if (mi2i == mi2iMap_.end())
253 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
254 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
255 assert(it != mi2iMap_.end() && "Invalid instruction!");
256 unsigned Index = it->second;
258 mi2iMap_[NewMI] = Index;
261 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
263 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
264 /// copy field and returns the source register that defines it.
265 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
267 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
268 virtual void releaseMemory();
270 /// runOnMachineFunction - pass entry point
271 virtual bool runOnMachineFunction(MachineFunction&);
273 /// print - Implement the dump method.
274 virtual void print(std::ostream &O, const Module* = 0) const;
275 void print(std::ostream *O, const Module* M = 0) const {
279 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
280 /// the given interval.
281 std::vector<LiveInterval*>
282 addIntervalsForSpills(const LiveInterval& i,
283 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
285 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
286 /// around all defs and uses of the specified interval.
287 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
288 unsigned PhysReg, VirtRegMap &vrm);
290 /// isReMaterializable - Returns true if every definition of MI of every
291 /// val# of the specified interval is re-materializable. Also returns true
292 /// by reference if all of the defs are load instructions.
293 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
295 /// getRepresentativeReg - Find the largest super register of the specified
296 /// physical register.
297 unsigned getRepresentativeReg(unsigned Reg) const;
299 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
300 /// specified interval that conflicts with the specified physical register.
301 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
302 unsigned PhysReg) const;
305 /// computeIntervals - Compute live intervals.
306 void computeIntervals();
308 /// handleRegisterDef - update intervals for a register def
309 /// (calls handlePhysicalRegisterDef and
310 /// handleVirtualRegisterDef)
311 void handleRegisterDef(MachineBasicBlock *MBB,
312 MachineBasicBlock::iterator MI, unsigned MIIdx,
315 /// handleVirtualRegisterDef - update intervals for a virtual
317 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
318 MachineBasicBlock::iterator MI,
320 LiveInterval& interval);
322 /// handlePhysicalRegisterDef - update intervals for a physical register
324 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
325 MachineBasicBlock::iterator mi,
327 LiveInterval &interval,
328 MachineInstr *CopyMI);
330 /// handleLiveInRegister - Create interval for a livein register.
331 void handleLiveInRegister(MachineBasicBlock* mbb,
333 LiveInterval &interval, bool isAlias = false);
335 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
336 /// only allow one) virtual register operand, then its uses are implicitly
337 /// using the register. Returns the virtual register.
338 unsigned getReMatImplicitUse(const LiveInterval &li,
339 MachineInstr *MI) const;
341 /// isValNoAvailableAt - Return true if the val# of the specified interval
342 /// which reaches the given instruction also reaches the specified use
344 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
345 unsigned UseIdx) const;
347 /// isReMaterializable - Returns true if the definition MI of the specified
348 /// val# of the specified interval is re-materializable. Also returns true
349 /// by reference if the def is a load.
350 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
351 MachineInstr *MI, bool &isLoad);
353 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
354 /// slot / to reg or any rematerialized load into ith operand of specified
355 /// MI. If it is successul, MI is updated with the newly created MI and
357 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
358 MachineInstr *DefMI, unsigned InstrIdx,
359 SmallVector<unsigned, 2> &Ops,
360 bool isSS, int Slot, unsigned Reg);
362 /// canFoldMemoryOperand - Return true if the specified load / store
363 /// folding is possible.
364 bool canFoldMemoryOperand(MachineInstr *MI,
365 SmallVector<unsigned, 2> &Ops,
366 bool ReMatLoadSS) const;
368 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
369 /// VNInfo that's after the specified index but is within the basic block.
370 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
371 MachineBasicBlock *MBB, unsigned Idx) const;
373 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
374 /// within a single basic block.
375 bool intervalIsInOneMBB(const LiveInterval &li) const;
377 /// hasAllocatableSuperReg - Return true if the specified physical register
378 /// has any super register that's allocatable.
379 bool hasAllocatableSuperReg(unsigned Reg) const;
381 /// SRInfo - Spill / restore info.
386 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
389 bool alsoFoldARestore(int Id, int index, unsigned vr,
390 BitVector &RestoreMBBs,
391 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
392 void eraseRestoreInfo(int Id, int index, unsigned vr,
393 BitVector &RestoreMBBs,
394 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
396 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
397 /// interval on to-be re-materialized operands of MI) with new register.
398 void rewriteImplicitOps(const LiveInterval &li,
399 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
401 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
402 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
404 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
405 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
406 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
407 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
408 VirtRegMap &vrm, const TargetRegisterClass* rc,
409 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
410 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
411 std::map<unsigned,unsigned> &MBBVRegsMap,
412 std::vector<LiveInterval*> &NewLIs);
413 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
414 LiveInterval::Ranges::const_iterator &I,
415 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
416 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
417 VirtRegMap &vrm, const TargetRegisterClass* rc,
418 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
419 BitVector &SpillMBBs,
420 std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
421 BitVector &RestoreMBBs,
422 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
423 std::map<unsigned,unsigned> &MBBVRegsMap,
424 std::vector<LiveInterval*> &NewLIs);
426 static LiveInterval createInterval(unsigned Reg);
428 void printRegName(unsigned reg) const;
431 } // End llvm namespace