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 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/IntervalMap.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/CodeGen/SlotIndexes.h"
24 class ConnectedVNInfoEqClasses;
29 class MachineLoopInfo;
30 class MachineRegisterInfo;
31 class TargetInstrInfo;
32 class TargetRegisterInfo;
37 /// At some point we should just include MachineDominators.h:
38 class MachineDominatorTree;
39 template <class NodeT> class DomTreeNodeBase;
40 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
43 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
47 const MachineFunction &MF;
48 const VirtRegMap &VRM;
49 const LiveIntervals &LIS;
50 const MachineLoopInfo &Loops;
51 const TargetInstrInfo &TII;
53 // Instructions using the the current register.
54 typedef SmallPtrSet<const MachineInstr*, 16> InstrPtrSet;
55 InstrPtrSet UsingInstrs;
57 // Sorted slot indexes of using instructions.
58 SmallVector<SlotIndex, 8> UseSlots;
60 // The number of instructions using CurLI in each basic block.
61 typedef DenseMap<const MachineBasicBlock*, unsigned> BlockCountMap;
62 BlockCountMap UsingBlocks;
64 /// Additional information about basic blocks where the current variable is
65 /// live. Such a block will look like one of these templates:
67 /// 1. | o---x | Internal to block. Variable is only live in this block.
68 /// 2. |---x | Live-in, kill.
69 /// 3. | o---| Def, live-out.
70 /// 4. |---x o---| Live-in, kill, def, live-out.
71 /// 5. |---o---o---| Live-through with uses or defs.
72 /// 6. |-----------| Live-through without uses. Transparent.
75 MachineBasicBlock *MBB;
76 SlotIndex Start; ///< Beginining of block.
77 SlotIndex Stop; ///< End of block.
78 SlotIndex FirstUse; ///< First instr using current reg.
79 SlotIndex LastUse; ///< Last instr using current reg.
80 SlotIndex Kill; ///< Interval end point inside block.
81 SlotIndex Def; ///< Interval start point inside block.
82 /// Last possible point for splitting live ranges.
83 SlotIndex LastSplitPoint;
84 bool Uses; ///< Current reg has uses or defs in block.
85 bool LiveThrough; ///< Live in whole block (Templ 5. or 6. above).
86 bool LiveIn; ///< Current reg is live in.
87 bool LiveOut; ///< Current reg is live out.
89 // Per-interference pattern scratch data.
90 bool OverlapEntry; ///< Interference overlaps entering interval.
91 bool OverlapExit; ///< Interference overlaps exiting interval.
94 /// Basic blocks where var is live. This array is parallel to
96 SmallVector<BlockInfo, 8> LiveBlocks;
99 // Current live interval.
100 const LiveInterval *CurLI;
102 // Sumarize statistics by counting instructions using CurLI.
105 /// calcLiveBlockInfo - Compute per-block information about CurLI.
106 bool calcLiveBlockInfo();
108 /// canAnalyzeBranch - Return true if MBB ends in a branch that can be
110 bool canAnalyzeBranch(const MachineBasicBlock *MBB);
113 SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
114 const MachineLoopInfo &mli);
116 /// analyze - set CurLI to the specified interval, and analyze how it may be
118 void analyze(const LiveInterval *li);
120 /// clear - clear all data structures so SplitAnalysis is ready to analyze a
124 /// getParent - Return the last analyzed interval.
125 const LiveInterval &getParent() const { return *CurLI; }
127 /// hasUses - Return true if MBB has any uses of CurLI.
128 bool hasUses(const MachineBasicBlock *MBB) const {
129 return UsingBlocks.lookup(MBB);
132 /// isOriginalEndpoint - Return true if the original live range was killed or
133 /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
134 /// and 'use' for an early-clobber def.
135 /// This can be used to recognize code inserted by earlier live range
137 bool isOriginalEndpoint(SlotIndex Idx) const;
139 typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
141 // Print a set of blocks with use counts.
142 void print(const BlockPtrSet&, raw_ostream&) const;
144 /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
145 /// having CurLI split to a new live interval. Return true if Blocks can be
146 /// passed to SplitEditor::splitSingleBlocks.
147 bool getMultiUseBlocks(BlockPtrSet &Blocks);
151 /// SplitEditor - Edit machine code and LiveIntervals for live range
154 /// - Create a SplitEditor from a SplitAnalysis.
155 /// - Start a new live interval with openIntv.
156 /// - Mark the places where the new interval is entered using enterIntv*
157 /// - Mark the ranges where the new interval is used with useIntv*
158 /// - Mark the places where the interval is exited with exitIntv*.
159 /// - Finish the current interval with closeIntv and repeat from 2.
160 /// - Rewrite instructions with finish().
166 MachineRegisterInfo &MRI;
167 MachineDominatorTree &MDT;
168 const TargetInstrInfo &TII;
169 const TargetRegisterInfo &TRI;
171 /// Edit - The current parent register and new intervals created.
174 /// Index into Edit of the currently open interval.
175 /// The index 0 is used for the complement, so the first interval started by
176 /// openIntv will be 1.
179 typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
181 /// Allocator for the interval map. This will eventually be shared with
182 /// SlotIndexes and LiveIntervals.
183 RegAssignMap::Allocator Allocator;
185 /// RegAssign - Map of the assigned register indexes.
186 /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
188 RegAssignMap RegAssign;
190 typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
192 /// Values - keep track of the mapping from parent values to values in the new
193 /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
195 /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
196 /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
197 /// Each value is represented by a minimal live range at its def.
198 /// 3. A non-null VNInfo - the value is mapped to a single new value.
199 /// The new value has no live ranges anywhere.
202 typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
203 typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
205 // LiveOutCache - Map each basic block where a new register is live out to the
206 // live-out value and its defining block.
207 // One of these conditions shall be true:
209 // 1. !LiveOutCache.count(MBB)
210 // 2. LiveOutCache[MBB].second.getNode() == MBB
211 // 3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
213 // This is only a cache, the values can be computed as:
215 // VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
216 // Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
218 // The cache is also used as a visited set by extendRange(). It can be shared
219 // by all the new registers because at most one is live out of each block.
220 LiveOutMap LiveOutCache;
222 // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
223 // entry in LiveOutCache.
224 BitVector LiveOutSeen;
226 /// defValue - define a value in RegIdx from ParentVNI at Idx.
227 /// Idx does not have to be ParentVNI->def, but it must be contained within
228 /// ParentVNI's live range in ParentLI. The new value is added to the value
230 /// Return the new LI value.
231 VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
233 /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
234 /// of the number of defs.
235 void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
237 /// defFromParent - Define Reg from ParentVNI at UseIdx using either
238 /// rematerialization or a COPY from parent. Return the new value.
239 VNInfo *defFromParent(unsigned RegIdx,
242 MachineBasicBlock &MBB,
243 MachineBasicBlock::iterator I);
245 /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
246 /// Insert PHIDefs as needed to preserve SSA form.
247 void extendRange(unsigned RegIdx, SlotIndex Idx);
249 /// updateSSA - Insert PHIDefs as necessary and update LiveOutCache such that
250 /// Edit.get(RegIdx) is live-in to all the blocks in LiveIn.
251 /// Return the value that is eventually live-in to IdxMBB.
252 VNInfo *updateSSA(unsigned RegIdx,
253 SmallVectorImpl<MachineDomTreeNode*> &LiveIn,
255 const MachineBasicBlock *IdxMBB);
257 /// transferSimpleValues - Transfer simply defined values to the new ranges.
258 /// Return true if any complex ranges were skipped.
259 bool transferSimpleValues();
261 /// extendPHIKillRanges - Extend the ranges of all values killed by original
263 void extendPHIKillRanges();
265 /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
266 void rewriteAssigned(bool ExtendRanges);
268 /// rewriteComponents - Rewrite all uses of Intv[0] according to the eq
269 /// classes in ConEQ.
270 /// This must be done when Intvs[0] is styill live at all uses, before calling
271 /// ConEq.Distribute().
272 void rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs,
273 const ConnectedVNInfoEqClasses &ConEq);
275 /// deleteRematVictims - Delete defs that are dead after rematerializing.
276 void deleteRematVictims();
279 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
280 /// Newly created intervals will be appended to newIntervals.
281 SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
282 MachineDominatorTree&);
284 /// reset - Prepare for a new split.
285 void reset(LiveRangeEdit&);
287 /// Create a new virtual register and live interval.
290 /// enterIntvBefore - Enter the open interval before the instruction at Idx.
291 /// If the parent interval is not live before Idx, a COPY is not inserted.
292 /// Return the beginning of the new live range.
293 SlotIndex enterIntvBefore(SlotIndex Idx);
295 /// enterIntvAtEnd - Enter the open interval at the end of MBB.
296 /// Use the open interval from he inserted copy to the MBB end.
297 /// Return the beginning of the new live range.
298 SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
300 /// useIntv - indicate that all instructions in MBB should use OpenLI.
301 void useIntv(const MachineBasicBlock &MBB);
303 /// useIntv - indicate that all instructions in range should use OpenLI.
304 void useIntv(SlotIndex Start, SlotIndex End);
306 /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
307 /// Return the end of the live range.
308 SlotIndex leaveIntvAfter(SlotIndex Idx);
310 /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
311 /// Return the end of the live range.
312 SlotIndex leaveIntvBefore(SlotIndex Idx);
314 /// leaveIntvAtTop - Leave the interval at the top of MBB.
315 /// Add liveness from the MBB top to the copy.
316 /// Return the end of the live range.
317 SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
319 /// overlapIntv - Indicate that all instructions in range should use the open
320 /// interval, but also let the complement interval be live.
322 /// This doubles the register pressure, but is sometimes required to deal with
323 /// register uses after the last valid split point.
325 /// The Start index should be a return value from a leaveIntv* call, and End
326 /// should be in the same basic block. The parent interval must have the same
327 /// value across the range.
329 void overlapIntv(SlotIndex Start, SlotIndex End);
331 /// closeIntv - Indicate that we are done editing the currently open
332 /// LiveInterval, and ranges can be trimmed.
335 /// finish - after all the new live ranges have been created, compute the
336 /// remaining live range, and rewrite instructions to use the new registers.
339 /// dump - print the current interval maping to dbgs().
342 // ===--- High level methods ---===
344 /// splitSingleBlocks - Split CurLI into a separate live interval inside each
345 /// basic block in Blocks.
346 void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);