1 //===-------- SplitKit.h - Toolkit for splitting live ranges ----*- 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 contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SPLITKIT_H
16 #define LLVM_CODEGEN_SPLITKIT_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IndexedMap.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
28 class ConnectedVNInfoEqClasses;
33 class MachineLoopInfo;
34 class MachineRegisterInfo;
35 class TargetInstrInfo;
36 class TargetRegisterInfo;
41 /// At some point we should just include MachineDominators.h:
42 class MachineDominatorTree;
43 template <class NodeT> class DomTreeNodeBase;
44 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
47 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
51 const MachineFunction &MF;
52 const VirtRegMap &VRM;
53 const LiveIntervals &LIS;
54 const MachineLoopInfo &Loops;
55 const TargetInstrInfo &TII;
57 // Sorted slot indexes of using instructions.
58 SmallVector<SlotIndex, 8> UseSlots;
60 /// Additional information about basic blocks where the current variable is
61 /// live. Such a block will look like one of these templates:
63 /// 1. | o---x | Internal to block. Variable is only live in this block.
64 /// 2. |---x | Live-in, kill.
65 /// 3. | o---| Def, live-out.
66 /// 4. |---x o---| Live-in, kill, def, live-out.
67 /// 5. |---o---o---| Live-through with uses or defs.
68 /// 6. |-----------| Live-through without uses. Transparent.
71 MachineBasicBlock *MBB;
72 SlotIndex FirstUse; ///< First instr using current reg.
73 SlotIndex LastUse; ///< Last instr using current reg.
74 SlotIndex Kill; ///< Interval end point inside block.
75 SlotIndex Def; ///< Interval start point inside block.
76 bool LiveThrough; ///< Live in whole block (Templ 5. or 6. above).
77 bool LiveIn; ///< Current reg is live in.
78 bool LiveOut; ///< Current reg is live out.
82 // Current live interval.
83 const LiveInterval *CurLI;
85 /// LastSplitPoint - Last legal split point in each basic block in the current
86 /// function. The first entry is the first terminator, the second entry is the
87 /// last valid split point for a variable that is live in to a landing pad
89 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
91 /// UseBlocks - Blocks where CurLI has uses.
92 SmallVector<BlockInfo, 8> UseBlocks;
94 /// ThroughBlocks - Block numbers where CurLI is live through without uses.
95 BitVector ThroughBlocks;
97 /// NumThroughBlocks - Number of live-through blocks.
98 unsigned NumThroughBlocks;
100 SlotIndex computeLastSplitPoint(unsigned Num);
102 // Sumarize statistics by counting instructions using CurLI.
105 /// calcLiveBlockInfo - Compute per-block information about CurLI.
106 bool calcLiveBlockInfo();
109 SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
110 const MachineLoopInfo &mli);
112 /// analyze - set CurLI to the specified interval, and analyze how it may be
114 void analyze(const LiveInterval *li);
116 /// clear - clear all data structures so SplitAnalysis is ready to analyze a
120 /// getParent - Return the last analyzed interval.
121 const LiveInterval &getParent() const { return *CurLI; }
123 /// getLastSplitPoint - Return that base index of the last valid split point
124 /// in the basic block numbered Num.
125 SlotIndex getLastSplitPoint(unsigned Num) {
126 // Inline the common simple case.
127 if (LastSplitPoint[Num].first.isValid() &&
128 !LastSplitPoint[Num].second.isValid())
129 return LastSplitPoint[Num].first;
130 return computeLastSplitPoint(Num);
133 /// isOriginalEndpoint - Return true if the original live range was killed or
134 /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
135 /// and 'use' for an early-clobber def.
136 /// This can be used to recognize code inserted by earlier live range
138 bool isOriginalEndpoint(SlotIndex Idx) const;
140 /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
141 /// where CurLI has uses.
142 ArrayRef<BlockInfo> getUseBlocks() { return UseBlocks; }
144 /// getNumThroughBlocks - Return the number of through blocks.
145 unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
147 /// isThroughBlock - Return true if CurLI is live through MBB without uses.
148 bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
150 /// getThroughBlocks - Return the set of through blocks.
151 const BitVector &getThroughBlocks() const { return ThroughBlocks; }
153 /// countLiveBlocks - Return the number of blocks where li is live.
154 /// This is guaranteed to return the same number as getNumThroughBlocks() +
155 /// getUseBlocks().size() after calling analyze(li).
156 unsigned countLiveBlocks(const LiveInterval *li) const;
158 typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
160 /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
161 /// having CurLI split to a new live interval. Return true if Blocks can be
162 /// passed to SplitEditor::splitSingleBlocks.
163 bool getMultiUseBlocks(BlockPtrSet &Blocks);
167 /// SplitEditor - Edit machine code and LiveIntervals for live range
170 /// - Create a SplitEditor from a SplitAnalysis.
171 /// - Start a new live interval with openIntv.
172 /// - Mark the places where the new interval is entered using enterIntv*
173 /// - Mark the ranges where the new interval is used with useIntv*
174 /// - Mark the places where the interval is exited with exitIntv*.
175 /// - Finish the current interval with closeIntv and repeat from 2.
176 /// - Rewrite instructions with finish().
182 MachineRegisterInfo &MRI;
183 MachineDominatorTree &MDT;
184 const TargetInstrInfo &TII;
185 const TargetRegisterInfo &TRI;
187 /// Edit - The current parent register and new intervals created.
190 /// Index into Edit of the currently open interval.
191 /// The index 0 is used for the complement, so the first interval started by
192 /// openIntv will be 1.
195 typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
197 /// Allocator for the interval map. This will eventually be shared with
198 /// SlotIndexes and LiveIntervals.
199 RegAssignMap::Allocator Allocator;
201 /// RegAssign - Map of the assigned register indexes.
202 /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
204 RegAssignMap RegAssign;
206 typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
208 /// Values - keep track of the mapping from parent values to values in the new
209 /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
211 /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
212 /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
213 /// Each value is represented by a minimal live range at its def.
214 /// 3. A non-null VNInfo - the value is mapped to a single new value.
215 /// The new value has no live ranges anywhere.
218 typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
219 typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
221 // LiveOutCache - Map each basic block where a new register is live out to the
222 // live-out value and its defining block.
223 // One of these conditions shall be true:
225 // 1. !LiveOutCache.count(MBB)
226 // 2. LiveOutCache[MBB].second.getNode() == MBB
227 // 3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
229 // This is only a cache, the values can be computed as:
231 // VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
232 // Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
234 // The cache is also used as a visited set by extendRange(). It can be shared
235 // by all the new registers because at most one is live out of each block.
236 LiveOutMap LiveOutCache;
238 // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
239 // entry in LiveOutCache.
240 BitVector LiveOutSeen;
242 /// LiveInBlock - Info for updateSSA() about a block where a register is
244 /// The updateSSA caller provides DomNode and Kill inside MBB, updateSSA()
245 /// adds the computed live-in value.
247 // Dominator tree node for the block.
248 // Cleared by updateSSA when the final value has been determined.
249 MachineDomTreeNode *DomNode;
251 // Live-in value filled in by updateSSA once it is known.
254 // Position in block where the live-in range ends, or SlotIndex() if the
255 // range passes through the block.
258 LiveInBlock(MachineDomTreeNode *node) : DomNode(node), Value(0) {}
261 /// LiveInBlocks - List of live-in blocks used by findReachingDefs() and
262 /// updateSSA(). This list is usually empty, it exists here to avoid frequent
264 SmallVector<LiveInBlock, 16> LiveInBlocks;
266 /// defValue - define a value in RegIdx from ParentVNI at Idx.
267 /// Idx does not have to be ParentVNI->def, but it must be contained within
268 /// ParentVNI's live range in ParentLI. The new value is added to the value
270 /// Return the new LI value.
271 VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
273 /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
274 /// of the number of defs.
275 void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
277 /// defFromParent - Define Reg from ParentVNI at UseIdx using either
278 /// rematerialization or a COPY from parent. Return the new value.
279 VNInfo *defFromParent(unsigned RegIdx,
282 MachineBasicBlock &MBB,
283 MachineBasicBlock::iterator I);
285 /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
286 /// Insert PHIDefs as needed to preserve SSA form.
287 void extendRange(unsigned RegIdx, SlotIndex Idx);
289 /// findReachingDefs - Starting from MBB, add blocks to LiveInBlocks until all
290 /// reaching defs for LI are found.
291 /// @param LI Live interval whose value is needed.
292 /// @param MBB Block where LI should be live-in.
293 /// @param Kill Kill point in MBB.
294 /// @return Unique value seen, or NULL.
295 VNInfo *findReachingDefs(LiveInterval *LI, MachineBasicBlock *MBB,
298 /// updateSSA - Compute and insert PHIDefs such that all blocks in
299 // LiveInBlocks get a known live-in value. Add live ranges to the blocks.
302 /// transferValues - Transfer values to the new ranges.
303 /// Return true if any ranges were skipped.
304 bool transferValues();
306 /// extendPHIKillRanges - Extend the ranges of all values killed by original
308 void extendPHIKillRanges();
310 /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
311 void rewriteAssigned(bool ExtendRanges);
313 /// deleteRematVictims - Delete defs that are dead after rematerializing.
314 void deleteRematVictims();
317 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
318 /// Newly created intervals will be appended to newIntervals.
319 SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
320 MachineDominatorTree&);
322 /// reset - Prepare for a new split.
323 void reset(LiveRangeEdit&);
325 /// Create a new virtual register and live interval.
326 /// Return the interval index, starting from 1. Interval index 0 is the
327 /// implicit complement interval.
330 /// currentIntv - Return the current interval index.
331 unsigned currentIntv() const { return OpenIdx; }
333 /// selectIntv - Select a previously opened interval index.
334 void selectIntv(unsigned Idx);
336 /// enterIntvBefore - Enter the open interval before the instruction at Idx.
337 /// If the parent interval is not live before Idx, a COPY is not inserted.
338 /// Return the beginning of the new live range.
339 SlotIndex enterIntvBefore(SlotIndex Idx);
341 /// enterIntvAtEnd - Enter the open interval at the end of MBB.
342 /// Use the open interval from he inserted copy to the MBB end.
343 /// Return the beginning of the new live range.
344 SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
346 /// useIntv - indicate that all instructions in MBB should use OpenLI.
347 void useIntv(const MachineBasicBlock &MBB);
349 /// useIntv - indicate that all instructions in range should use OpenLI.
350 void useIntv(SlotIndex Start, SlotIndex End);
352 /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
353 /// Return the end of the live range.
354 SlotIndex leaveIntvAfter(SlotIndex Idx);
356 /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
357 /// Return the end of the live range.
358 SlotIndex leaveIntvBefore(SlotIndex Idx);
360 /// leaveIntvAtTop - Leave the interval at the top of MBB.
361 /// Add liveness from the MBB top to the copy.
362 /// Return the end of the live range.
363 SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
365 /// overlapIntv - Indicate that all instructions in range should use the open
366 /// interval, but also let the complement interval be live.
368 /// This doubles the register pressure, but is sometimes required to deal with
369 /// register uses after the last valid split point.
371 /// The Start index should be a return value from a leaveIntv* call, and End
372 /// should be in the same basic block. The parent interval must have the same
373 /// value across the range.
375 void overlapIntv(SlotIndex Start, SlotIndex End);
377 /// finish - after all the new live ranges have been created, compute the
378 /// remaining live range, and rewrite instructions to use the new registers.
379 /// @param LRMap When not null, this vector will map each live range in Edit
380 /// back to the indices returned by openIntv.
381 /// There may be extra indices created by dead code elimination.
382 void finish(SmallVectorImpl<unsigned> *LRMap = 0);
384 /// dump - print the current interval maping to dbgs().
387 // ===--- High level methods ---===
389 /// splitSingleBlock - Split CurLI into a separate live interval around the
390 /// uses in a single block. This is intended to be used as part of a larger
391 /// split, and doesn't call finish().
392 void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
394 /// splitSingleBlocks - Split CurLI into a separate live interval inside each
395 /// basic block in Blocks.
396 void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);