LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
LiveIntervalAnalysis.h
Go to the documentation of this file.
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/ADT/IndexedMap.h"
24 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
31 #include <cmath>
32 #include <iterator>
33 
34 namespace llvm {
35 
36  class AliasAnalysis;
37  class BitVector;
38  class BlockFrequency;
39  class LiveRangeCalc;
40  class LiveVariables;
41  class MachineDominatorTree;
42  class MachineLoopInfo;
43  class TargetRegisterInfo;
44  class MachineRegisterInfo;
45  class TargetInstrInfo;
46  class TargetRegisterClass;
47  class VirtRegMap;
48 
50  MachineFunction* MF;
52  const TargetMachine* TM;
53  const TargetRegisterInfo* TRI;
54  const TargetInstrInfo* TII;
55  AliasAnalysis *AA;
56  SlotIndexes* Indexes;
57  MachineDominatorTree *DomTree;
58  LiveRangeCalc *LRCalc;
59 
60  /// Special pool allocator for VNInfo's (LiveInterval val#).
61  ///
62  VNInfo::Allocator VNInfoAllocator;
63 
64  /// Live interval pointers for all the virtual registers.
66 
67  /// RegMaskSlots - Sorted list of instructions with register mask operands.
68  /// Always use the 'r' slot, RegMasks are normal clobbers, not early
69  /// clobbers.
70  SmallVector<SlotIndex, 8> RegMaskSlots;
71 
72  /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
73  /// pointer to the corresponding register mask. This pointer can be
74  /// recomputed as:
75  ///
76  /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
77  /// unsigned OpNum = findRegMaskOperand(MI);
78  /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
79  ///
80  /// This is kept in a separate vector partly because some standard
81  /// libraries don't support lower_bound() with mixed objects, partly to
82  /// improve locality when searching in RegMaskSlots.
83  /// Also see the comment in LiveInterval::find().
85 
86  /// For each basic block number, keep (begin, size) pairs indexing into the
87  /// RegMaskSlots and RegMaskBits arrays.
88  /// Note that basic block numbers may not be layout contiguous, that's why
89  /// we can't just keep track of the first register mask in each basic
90  /// block.
92 
93  /// Keeps a live range set for each register unit to track fixed physreg
94  /// interference.
95  SmallVector<LiveRange*, 0> RegUnitRanges;
96 
97  public:
98  static char ID; // Pass identification, replacement for typeid
99  LiveIntervals();
100  virtual ~LiveIntervals();
101 
102  // Calculate the spill weight to assign to a single instruction.
103  static float getSpillWeight(bool isDef, bool isUse, BlockFrequency freq);
104 
106  if (hasInterval(Reg))
107  return *VirtRegIntervals[Reg];
108  else
110  }
111 
112  const LiveInterval &getInterval(unsigned Reg) const {
113  return const_cast<LiveIntervals*>(this)->getInterval(Reg);
114  }
115 
116  bool hasInterval(unsigned Reg) const {
117  return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
118  }
119 
120  // Interval creation.
122  assert(!hasInterval(Reg) && "Interval already exists!");
123  VirtRegIntervals.grow(Reg);
124  VirtRegIntervals[Reg] = createInterval(Reg);
125  return *VirtRegIntervals[Reg];
126  }
127 
130  computeVirtRegInterval(LI);
131  return LI;
132  }
133 
134  // Interval removal.
135  void removeInterval(unsigned Reg) {
136  delete VirtRegIntervals[Reg];
137  VirtRegIntervals[Reg] = 0;
138  }
139 
140  /// Given a register and an instruction, adds a live segment from that
141  /// instruction to the end of its MBB.
143  MachineInstr* startInst);
144 
145  /// shrinkToUses - After removing some uses of a register, shrink its live
146  /// range to just the remaining uses. This method does not compute reaching
147  /// defs for new uses, and it doesn't remove dead defs.
148  /// Dead PHIDef values are marked as unused.
149  /// New dead machine instructions are added to the dead vector.
150  /// Return true if the interval may have been separated into multiple
151  /// connected components.
152  bool shrinkToUses(LiveInterval *li,
154 
155  /// extendToIndices - Extend the live range of LI to reach all points in
156  /// Indices. The points in the Indices array must be jointly dominated by
157  /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
158  ///
159  /// If a SlotIndex in Indices is the end index of a basic block, LI will be
160  /// extended to be live out of the basic block.
161  ///
162  /// See also LiveRangeCalc::extend().
163  void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices);
164 
165  /// pruneValue - If an LI value is live at Kill, prune its live range by
166  /// removing any liveness reachable from Kill. Add live range end points to
167  /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
168  /// value's live range.
169  ///
170  /// Calling pruneValue() and extendToIndices() can be used to reconstruct
171  /// SSA form after adding defs to a virtual register.
173  SmallVectorImpl<SlotIndex> *EndPoints);
174 
176  return Indexes;
177  }
178 
180  return AA;
181  }
182 
183  /// isNotInMIMap - returns true if the specified machine instr has been
184  /// removed or was never entered in the map.
185  bool isNotInMIMap(const MachineInstr* Instr) const {
186  return !Indexes->hasIndex(Instr);
187  }
188 
189  /// Returns the base index of the given instruction.
191  return Indexes->getInstructionIndex(instr);
192  }
193 
194  /// Returns the instruction associated with the given index.
196  return Indexes->getInstructionFromIndex(index);
197  }
198 
199  /// Return the first index in the given basic block.
201  return Indexes->getMBBStartIdx(mbb);
202  }
203 
204  /// Return the last index in the given basic block.
206  return Indexes->getMBBEndIdx(mbb);
207  }
208 
209  bool isLiveInToMBB(const LiveRange &LR,
210  const MachineBasicBlock *mbb) const {
211  return LR.liveAt(getMBBStartIdx(mbb));
212  }
213 
214  bool isLiveOutOfMBB(const LiveRange &LR,
215  const MachineBasicBlock *mbb) const {
216  return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
217  }
218 
220  return Indexes->getMBBFromIndex(index);
221  }
222 
224  Indexes->insertMBBInMaps(MBB);
225  assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
226  "Blocks must be added in order.");
227  RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
228  }
229 
231  return Indexes->insertMachineInstrInMaps(MI);
232  }
233 
236  for (MachineBasicBlock::iterator I = B; I != E; ++I)
237  Indexes->insertMachineInstrInMaps(I);
238  }
239 
241  Indexes->removeMachineInstrFromMaps(MI);
242  }
243 
245  Indexes->replaceMachineInstrInMaps(MI, NewMI);
246  }
247 
250  return Indexes->findLiveInMBBs(Start, End, MBBs);
251  }
252 
253  VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
254 
255  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
256  virtual void releaseMemory();
257 
258  /// runOnMachineFunction - pass entry point
259  virtual bool runOnMachineFunction(MachineFunction&);
260 
261  /// print - Implement the dump method.
262  virtual void print(raw_ostream &O, const Module* = 0) const;
263 
264  /// intervalIsInOneMBB - If LI is confined to a single basic block, return
265  /// a pointer to that block. If LI is live in to or out of any block,
266  /// return NULL.
268 
269  /// Returns true if VNI is killed by any PHI-def values in LI.
270  /// This may conservatively return true to avoid expensive computations.
271  bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
272 
273  /// addKillFlags - Add kill flags to any instruction that kills a virtual
274  /// register.
275  void addKillFlags(const VirtRegMap*);
276 
277  /// handleMove - call this method to notify LiveIntervals that
278  /// instruction 'mi' has been moved within a basic block. This will update
279  /// the live intervals for all operands of mi. Moves between basic blocks
280  /// are not supported.
281  ///
282  /// \param UpdateFlags Update live intervals for nonallocatable physregs.
283  void handleMove(MachineInstr* MI, bool UpdateFlags = false);
284 
285  /// moveIntoBundle - Update intervals for operands of MI so that they
286  /// begin/end on the SlotIndex for BundleStart.
287  ///
288  /// \param UpdateFlags Update live intervals for nonallocatable physregs.
289  ///
290  /// Requires MI and BundleStart to have SlotIndexes, and assumes
291  /// existing liveness is accurate. BundleStart should be the first
292  /// instruction in the Bundle.
293  void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
294  bool UpdateFlags = false);
295 
296  /// repairIntervalsInRange - Update live intervals for instructions in a
297  /// range of iterators. It is intended for use after target hooks that may
298  /// insert or remove instructions, and is only efficient for a small number
299  /// of instructions.
300  ///
301  /// OrigRegs is a vector of registers that were originally used by the
302  /// instructions in the range between the two iterators.
303  ///
304  /// Currently, the only only changes that are supported are simple removal
305  /// and addition of uses.
309  ArrayRef<unsigned> OrigRegs);
310 
311  // Register mask functions.
312  //
313  // Machine instructions may use a register mask operand to indicate that a
314  // large number of registers are clobbered by the instruction. This is
315  // typically used for calls.
316  //
317  // For compile time performance reasons, these clobbers are not recorded in
318  // the live intervals for individual physical registers. Instead,
319  // LiveIntervalAnalysis maintains a sorted list of instructions with
320  // register mask operands.
321 
322  /// getRegMaskSlots - Returns a sorted array of slot indices of all
323  /// instructions with register mask operands.
324  ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
325 
326  /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
327  /// instructions with register mask operands in the basic block numbered
328  /// MBBNum.
330  std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
331  return getRegMaskSlots().slice(P.first, P.second);
332  }
333 
334  /// getRegMaskBits() - Returns an array of register mask pointers
335  /// corresponding to getRegMaskSlots().
336  ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
337 
338  /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
339  /// to getRegMaskSlotsInBlock(MBBNum).
341  std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
342  return getRegMaskBits().slice(P.first, P.second);
343  }
344 
345  /// checkRegMaskInterference - Test if LI is live across any register mask
346  /// instructions, and compute a bit mask of physical registers that are not
347  /// clobbered by any of them.
348  ///
349  /// Returns false if LI doesn't cross any register mask instructions. In
350  /// that case, the bit vector is not filled in.
352  BitVector &UsableRegs);
353 
354  // Register unit functions.
355  //
356  // Fixed interference occurs when MachineInstrs use physregs directly
357  // instead of virtual registers. This typically happens when passing
358  // arguments to a function call, or when instructions require operands in
359  // fixed registers.
360  //
361  // Each physreg has one or more register units, see MCRegisterInfo. We
362  // track liveness per register unit to handle aliasing registers more
363  // efficiently.
364 
365  /// getRegUnit - Return the live range for Unit.
366  /// It will be computed if it doesn't exist.
367  LiveRange &getRegUnit(unsigned Unit) {
368  LiveRange *LR = RegUnitRanges[Unit];
369  if (!LR) {
370  // Compute missing ranges on demand.
371  RegUnitRanges[Unit] = LR = new LiveRange();
372  computeRegUnitRange(*LR, Unit);
373  }
374  return *LR;
375  }
376 
377  /// getCachedRegUnit - Return the live range for Unit if it has already
378  /// been computed, or NULL if it hasn't been computed yet.
379  LiveRange *getCachedRegUnit(unsigned Unit) {
380  return RegUnitRanges[Unit];
381  }
382 
383  const LiveRange *getCachedRegUnit(unsigned Unit) const {
384  return RegUnitRanges[Unit];
385  }
386 
387  private:
388  /// Compute live intervals for all virtual registers.
389  void computeVirtRegs();
390 
391  /// Compute RegMaskSlots and RegMaskBits.
392  void computeRegMasks();
393 
394  static LiveInterval* createInterval(unsigned Reg);
395 
396  void printInstrs(raw_ostream &O) const;
397  void dumpInstrs() const;
398 
399  void computeLiveInRegUnits();
400  void computeRegUnitRange(LiveRange&, unsigned Unit);
401  void computeVirtRegInterval(LiveInterval&);
402 
403  class HMEditor;
404  };
405 } // End llvm namespace
406 
407 #endif
static float getSpillWeight(bool isDef, bool isUse, BlockFrequency freq)
void push_back(const T &Elt)
Definition: SmallVector.h:236
ArrayRef< SlotIndex > getRegMaskSlots() const
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
SlotIndex getInstructionIndex(const MachineInstr *instr) const
Returns the base index of the given instruction.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
bool isLiveOutOfMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
virtual bool runOnMachineFunction(MachineFunction &)
runOnMachineFunction - pass entry point
bool checkRegMaskInterference(LiveInterval &LI, BitVector &UsableRegs)
void pruneValue(LiveInterval *LI, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
bool isNotInMIMap(const MachineInstr *Instr) const
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
ArrayRef< SlotIndex > getRegMaskSlotsInBlock(unsigned MBBNum) const
ArrayRef< const uint32_t * > getRegMaskBits() const
VNInfo::Allocator & getVNInfoAllocator()
bool findLiveInMBBs(SlotIndex Start, SlotIndex End, SmallVectorImpl< MachineBasicBlock * > &MBBs) const
void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E)
void insertMBBInMaps(MachineBasicBlock *MBB)
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=0)
LiveRange * getCachedRegUnit(unsigned Unit)
bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
bundle_iterator< MachineInstr, instr_iterator > iterator
#define P(N)
void RemoveMachineInstrFromMaps(MachineInstr *MI)
SlotIndexes * getSlotIndexes() const
void insertMBBInMaps(MachineBasicBlock *mbb)
Add the given MachineBasicBlock into the maps.
Definition: SlotIndexes.h:639
bool findLiveInMBBs(SlotIndex start, SlotIndex end, SmallVectorImpl< MachineBasicBlock * > &mbbs) const
Definition: SlotIndexes.h:522
void removeInterval(unsigned Reg)
const LiveRange * getCachedRegUnit(unsigned Unit) const
virtual void getAnalysisUsage(AnalysisUsage &AU) const
block freq
LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg, MachineInstr *startInst)
void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< unsigned > OrigRegs)
void handleMove(MachineInstr *MI, bool UpdateFlags=false)
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:330
SlotIndex getInstructionIndex(const MachineInstr *MI) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:414
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Definition: SlotIndexes.h:423
virtual void print(raw_ostream &O, const Module *=0) const
print - Implement the dump method.
ArrayRef< const uint32_t * > getRegMaskBitsInBlock(unsigned MBBNum) const
bool hasIndex(const MachineInstr *instr) const
Definition: SlotIndexes.h:409
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
Definition: SlotIndexes.h:506
LiveInterval & getInterval(unsigned Reg)
SlotIndex InsertMachineInstrInMaps(MachineInstr *MI)
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:496
LiveInterval & createEmptyInterval(unsigned Reg)
void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI)
void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI)
Definition: SlotIndexes.h:625
void addKillFlags(const VirtRegMap *)
void handleMoveIntoBundle(MachineInstr *MI, MachineInstr *BundleStart, bool UpdateFlags=false)
#define I(x, y, z)
Definition: MD5.cpp:54
void removeMachineInstrFromMaps(MachineInstr *mi)
Remove the given machine instruction from the mapping.
Definition: SlotIndexes.h:610
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:486
bool hasInterval(unsigned Reg) const
AliasAnalysis * getAliasAnalysis() const
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
const LiveInterval & getInterval(unsigned Reg) const
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:92
SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late=false)
Definition: SlotIndexes.h:569
void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices)
LiveRange & getRegUnit(unsigned Unit)
LiveInterval & createAndComputeVirtRegInterval(unsigned Reg)