SplitKit.h revision 6796e4fc889d99c4ad97ec5ad86e4c8cf75e52a4
1//===-------- SplitKit.h - Toolkit for splitting live ranges ----*- 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 contains the SplitAnalysis class as well as mutator functions for
11// live range splitting.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_SPLITKIT_H
16#define LLVM_CODEGEN_SPLITKIT_H
17
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"
25
26namespace llvm {
27
28class ConnectedVNInfoEqClasses;
29class LiveInterval;
30class LiveIntervals;
31class LiveRangeEdit;
32class MachineInstr;
33class MachineLoopInfo;
34class MachineRegisterInfo;
35class TargetInstrInfo;
36class TargetRegisterInfo;
37class VirtRegMap;
38class VNInfo;
39class raw_ostream;
40
41/// At some point we should just include MachineDominators.h:
42class MachineDominatorTree;
43template <class NodeT> class DomTreeNodeBase;
44typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
45
46
47/// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
48/// opportunities.
49class SplitAnalysis {
50public:
51  const MachineFunction &MF;
52  const VirtRegMap &VRM;
53  const LiveIntervals &LIS;
54  const MachineLoopInfo &Loops;
55  const TargetInstrInfo &TII;
56
57  // Sorted slot indexes of using instructions.
58  SmallVector<SlotIndex, 8> UseSlots;
59
60  /// Additional information about basic blocks where the current variable is
61  /// live. Such a block will look like one of these templates:
62  ///
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.
69  ///
70  struct BlockInfo {
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.
79  };
80
81private:
82  // Current live interval.
83  const LiveInterval *CurLI;
84
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
88  /// successor.
89  SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
90
91  /// UseBlocks - Blocks where CurLI has uses.
92  SmallVector<BlockInfo, 8> UseBlocks;
93
94  /// ThroughBlocks - Block numbers where CurLI is live through without uses.
95  BitVector ThroughBlocks;
96
97  /// NumThroughBlocks - Number of live-through blocks.
98  unsigned NumThroughBlocks;
99
100  SlotIndex computeLastSplitPoint(unsigned Num);
101
102  // Sumarize statistics by counting instructions using CurLI.
103  void analyzeUses();
104
105  /// calcLiveBlockInfo - Compute per-block information about CurLI.
106  bool calcLiveBlockInfo();
107
108public:
109  SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
110                const MachineLoopInfo &mli);
111
112  /// analyze - set CurLI to the specified interval, and analyze how it may be
113  /// split.
114  void analyze(const LiveInterval *li);
115
116  /// clear - clear all data structures so SplitAnalysis is ready to analyze a
117  /// new interval.
118  void clear();
119
120  /// getParent - Return the last analyzed interval.
121  const LiveInterval &getParent() const { return *CurLI; }
122
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);
131  }
132
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
137  /// splitting.
138  bool isOriginalEndpoint(SlotIndex Idx) const;
139
140  /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
141  /// where CurLI has uses.
142  ArrayRef<BlockInfo> getUseBlocks() { return UseBlocks; }
143
144  /// getNumThroughBlocks - Return the number of through blocks.
145  unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
146
147  /// isThroughBlock - Return true if CurLI is live through MBB without uses.
148  bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
149
150  /// getThroughBlocks - Return the set of through blocks.
151  const BitVector &getThroughBlocks() const { return ThroughBlocks; }
152
153  typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
154
155  /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
156  /// having CurLI split to a new live interval. Return true if Blocks can be
157  /// passed to SplitEditor::splitSingleBlocks.
158  bool getMultiUseBlocks(BlockPtrSet &Blocks);
159};
160
161
162/// SplitEditor - Edit machine code and LiveIntervals for live range
163/// splitting.
164///
165/// - Create a SplitEditor from a SplitAnalysis.
166/// - Start a new live interval with openIntv.
167/// - Mark the places where the new interval is entered using enterIntv*
168/// - Mark the ranges where the new interval is used with useIntv*
169/// - Mark the places where the interval is exited with exitIntv*.
170/// - Finish the current interval with closeIntv and repeat from 2.
171/// - Rewrite instructions with finish().
172///
173class SplitEditor {
174  SplitAnalysis &SA;
175  LiveIntervals &LIS;
176  VirtRegMap &VRM;
177  MachineRegisterInfo &MRI;
178  MachineDominatorTree &MDT;
179  const TargetInstrInfo &TII;
180  const TargetRegisterInfo &TRI;
181
182  /// Edit - The current parent register and new intervals created.
183  LiveRangeEdit *Edit;
184
185  /// Index into Edit of the currently open interval.
186  /// The index 0 is used for the complement, so the first interval started by
187  /// openIntv will be 1.
188  unsigned OpenIdx;
189
190  typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
191
192  /// Allocator for the interval map. This will eventually be shared with
193  /// SlotIndexes and LiveIntervals.
194  RegAssignMap::Allocator Allocator;
195
196  /// RegAssign - Map of the assigned register indexes.
197  /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
198  /// Idx.
199  RegAssignMap RegAssign;
200
201  typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
202
203  /// Values - keep track of the mapping from parent values to values in the new
204  /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
205  ///
206  /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
207  /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
208  ///    Each value is represented by a minimal live range at its def.
209  /// 3. A non-null VNInfo - the value is mapped to a single new value.
210  ///    The new value has no live ranges anywhere.
211  ValueMap Values;
212
213  typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
214  typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
215
216  // LiveOutCache - Map each basic block where a new register is live out to the
217  // live-out value and its defining block.
218  // One of these conditions shall be true:
219  //
220  //  1. !LiveOutCache.count(MBB)
221  //  2. LiveOutCache[MBB].second.getNode() == MBB
222  //  3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
223  //
224  // This is only a cache, the values can be computed as:
225  //
226  //  VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
227  //  Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
228  //
229  // The cache is also used as a visited set by extendRange(). It can be shared
230  // by all the new registers because at most one is live out of each block.
231  LiveOutMap LiveOutCache;
232
233  // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
234  // entry in LiveOutCache.
235  BitVector LiveOutSeen;
236
237  /// LiveInBlock - Info for updateSSA() about a block where a register is
238  /// live-in.
239  /// The updateSSA caller provides DomNode and Kill inside MBB, updateSSA()
240  /// adds the computed live-in value.
241  struct LiveInBlock {
242    // Dominator tree node for the block.
243    // Cleared by updateSSA when the final value has been determined.
244    MachineDomTreeNode *DomNode;
245
246    // Live-in value filled in by updateSSA once it is known.
247    VNInfo *Value;
248
249    // Position in block where the live-in range ends, or SlotIndex() if the
250    // range passes through the block.
251    SlotIndex Kill;
252
253    LiveInBlock(MachineDomTreeNode *node) : DomNode(node), Value(0) {}
254  };
255
256  /// LiveInBlocks - List of live-in blocks used by findReachingDefs() and
257  /// updateSSA(). This list is usually empty, it exists here to avoid frequent
258  /// reallocations.
259  SmallVector<LiveInBlock, 16> LiveInBlocks;
260
261  /// defValue - define a value in RegIdx from ParentVNI at Idx.
262  /// Idx does not have to be ParentVNI->def, but it must be contained within
263  /// ParentVNI's live range in ParentLI. The new value is added to the value
264  /// map.
265  /// Return the new LI value.
266  VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
267
268  /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
269  /// of the number of defs.
270  void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
271
272  /// defFromParent - Define Reg from ParentVNI at UseIdx using either
273  /// rematerialization or a COPY from parent. Return the new value.
274  VNInfo *defFromParent(unsigned RegIdx,
275                        VNInfo *ParentVNI,
276                        SlotIndex UseIdx,
277                        MachineBasicBlock &MBB,
278                        MachineBasicBlock::iterator I);
279
280  /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
281  /// Insert PHIDefs as needed to preserve SSA form.
282  void extendRange(unsigned RegIdx, SlotIndex Idx);
283
284  /// findReachingDefs - Starting from MBB, add blocks to LiveInBlocks until all
285  /// reaching defs for LI are found.
286  /// @param LI   Live interval whose value is needed.
287  /// @param MBB  Block where LI should be live-in.
288  /// @param Kill Kill point in MBB.
289  /// @return Unique value seen, or NULL.
290  VNInfo *findReachingDefs(LiveInterval *LI, MachineBasicBlock *MBB,
291                           SlotIndex Kill);
292
293  /// updateSSA - Compute and insert PHIDefs such that all blocks in
294  // LiveInBlocks get a known live-in value. Add live ranges to the blocks.
295  void updateSSA();
296
297  /// transferValues - Transfer values to the new ranges.
298  /// Return true if any ranges were skipped.
299  bool transferValues();
300
301  /// extendPHIKillRanges - Extend the ranges of all values killed by original
302  /// parent PHIDefs.
303  void extendPHIKillRanges();
304
305  /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
306  void rewriteAssigned(bool ExtendRanges);
307
308  /// deleteRematVictims - Delete defs that are dead after rematerializing.
309  void deleteRematVictims();
310
311public:
312  /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
313  /// Newly created intervals will be appended to newIntervals.
314  SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
315              MachineDominatorTree&);
316
317  /// reset - Prepare for a new split.
318  void reset(LiveRangeEdit&);
319
320  /// Create a new virtual register and live interval.
321  /// Return the interval index, starting from 1. Interval index 0 is the
322  /// implicit complement interval.
323  unsigned openIntv();
324
325  /// currentIntv - Return the current interval index.
326  unsigned currentIntv() const { return OpenIdx; }
327
328  /// selectIntv - Select a previously opened interval index.
329  void selectIntv(unsigned Idx);
330
331  /// enterIntvBefore - Enter the open interval before the instruction at Idx.
332  /// If the parent interval is not live before Idx, a COPY is not inserted.
333  /// Return the beginning of the new live range.
334  SlotIndex enterIntvBefore(SlotIndex Idx);
335
336  /// enterIntvAtEnd - Enter the open interval at the end of MBB.
337  /// Use the open interval from he inserted copy to the MBB end.
338  /// Return the beginning of the new live range.
339  SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
340
341  /// useIntv - indicate that all instructions in MBB should use OpenLI.
342  void useIntv(const MachineBasicBlock &MBB);
343
344  /// useIntv - indicate that all instructions in range should use OpenLI.
345  void useIntv(SlotIndex Start, SlotIndex End);
346
347  /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
348  /// Return the end of the live range.
349  SlotIndex leaveIntvAfter(SlotIndex Idx);
350
351  /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
352  /// Return the end of the live range.
353  SlotIndex leaveIntvBefore(SlotIndex Idx);
354
355  /// leaveIntvAtTop - Leave the interval at the top of MBB.
356  /// Add liveness from the MBB top to the copy.
357  /// Return the end of the live range.
358  SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
359
360  /// overlapIntv - Indicate that all instructions in range should use the open
361  /// interval, but also let the complement interval be live.
362  ///
363  /// This doubles the register pressure, but is sometimes required to deal with
364  /// register uses after the last valid split point.
365  ///
366  /// The Start index should be a return value from a leaveIntv* call, and End
367  /// should be in the same basic block. The parent interval must have the same
368  /// value across the range.
369  ///
370  void overlapIntv(SlotIndex Start, SlotIndex End);
371
372  /// finish - after all the new live ranges have been created, compute the
373  /// remaining live range, and rewrite instructions to use the new registers.
374  /// @param LRMap When not null, this vector will map each live range in Edit
375  ///              back to the indices returned by openIntv.
376  ///              There may be extra indices created by dead code elimination.
377  void finish(SmallVectorImpl<unsigned> *LRMap = 0);
378
379  /// dump - print the current interval maping to dbgs().
380  void dump() const;
381
382  // ===--- High level methods ---===
383
384  /// splitSingleBlock - Split CurLI into a separate live interval around the
385  /// uses in a single block. This is intended to be used as part of a larger
386  /// split, and doesn't call finish().
387  void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
388
389  /// splitSingleBlocks - Split CurLI into a separate live interval inside each
390  /// basic block in Blocks.
391  void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
392};
393
394}
395
396#endif
397