blob: 96ccf3031e83ca815459a3e85f9a97ec294c0c62 [file] [log] [blame]
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001//===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
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#define DEBUG_TYPE "splitter"
16#include "SplitKit.h"
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +000017#include "LiveRangeEdit.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000018#include "VirtRegMap.h"
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +000019#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000020#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
23#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000024#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000027#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000029
30using namespace llvm;
31
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000032static cl::opt<bool>
33AllowSplit("spiller-splits-edges",
34 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000035
36//===----------------------------------------------------------------------===//
37// Split Analysis
38//===----------------------------------------------------------------------===//
39
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000040SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
41 const LiveIntervals &lis,
42 const MachineLoopInfo &mli)
43 : mf_(mf),
44 lis_(lis),
45 loops_(mli),
46 tii_(*mf.getTarget().getInstrInfo()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000047 curli_(0) {}
48
49void SplitAnalysis::clear() {
50 usingInstrs_.clear();
51 usingBlocks_.clear();
52 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000053 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000054}
55
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000056bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
57 MachineBasicBlock *T, *F;
58 SmallVector<MachineOperand, 4> Cond;
59 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
60}
61
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000062/// analyzeUses - Count instructions, basic blocks, and loops using curli.
63void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000064 const MachineRegisterInfo &MRI = mf_.getRegInfo();
65 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
66 MachineInstr *MI = I.skipInstruction();) {
67 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
68 continue;
69 MachineBasicBlock *MBB = MI->getParent();
70 if (usingBlocks_[MBB]++)
71 continue;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +000072 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
73 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000074 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000075 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000076 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000077 << usingInstrs_.size() << " instrs, "
78 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000079 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000080}
81
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000082// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
83// predecessor blocks, and exit blocks.
84void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
85 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000086
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000087 // Blocks in the loop.
88 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
89
90 // Predecessor blocks.
91 const MachineBasicBlock *Header = Loop->getHeader();
92 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
93 E = Header->pred_end(); I != E; ++I)
94 if (!Blocks.Loop.count(*I))
95 Blocks.Preds.insert(*I);
96
97 // Exit blocks.
98 for (MachineLoop::block_iterator I = Loop->block_begin(),
99 E = Loop->block_end(); I != E; ++I) {
100 const MachineBasicBlock *MBB = *I;
101 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
102 SE = MBB->succ_end(); SI != SE; ++SI)
103 if (!Blocks.Loop.count(*SI))
104 Blocks.Exits.insert(*SI);
105 }
106}
107
108/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
109/// and around the Loop.
110SplitAnalysis::LoopPeripheralUse SplitAnalysis::
111analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000112 LoopPeripheralUse use = ContainedInLoop;
113 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
114 I != E; ++I) {
115 const MachineBasicBlock *MBB = I->first;
116 // Is this a peripheral block?
117 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000118 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000119 if (I->second > 1) use = MultiPeripheral;
120 else use = SinglePeripheral;
121 continue;
122 }
123 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000124 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000125 continue;
126 // It must be an unrelated block.
127 return OutsideLoop;
128 }
129 return use;
130}
131
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000132/// getCriticalExits - It may be necessary to partially break critical edges
133/// leaving the loop if an exit block has phi uses of curli. Collect the exit
134/// blocks that need special treatment into CriticalExits.
135void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
136 BlockPtrSet &CriticalExits) {
137 CriticalExits.clear();
138
139 // A critical exit block contains a phi def of curli, and has a predecessor
140 // that is not in the loop nor a loop predecessor.
141 // For such an exit block, the edges carrying the new variable must be moved
142 // to a new pre-exit block.
143 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
144 I != E; ++I) {
145 const MachineBasicBlock *Succ = *I;
146 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
147 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
148 // This exit may not have curli live in at all. No need to split.
149 if (!SuccVNI)
150 continue;
151 // If this is not a PHI def, it is either using a value from before the
152 // loop, or a value defined inside the loop. Both are safe.
153 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
154 continue;
155 // This exit block does have a PHI. Does it also have a predecessor that is
156 // not a loop block or loop predecessor?
157 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
158 PE = Succ->pred_end(); PI != PE; ++PI) {
159 const MachineBasicBlock *Pred = *PI;
160 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
161 continue;
162 // This is a critical exit block, and we need to split the exit edge.
163 CriticalExits.insert(Succ);
164 break;
165 }
166 }
167}
168
169/// canSplitCriticalExits - Return true if it is possible to insert new exit
170/// blocks before the blocks in CriticalExits.
171bool
172SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
173 BlockPtrSet &CriticalExits) {
174 // If we don't allow critical edge splitting, require no critical exits.
175 if (!AllowSplit)
176 return CriticalExits.empty();
177
178 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
179 I != E; ++I) {
180 const MachineBasicBlock *Succ = *I;
181 // We want to insert a new pre-exit MBB before Succ, and change all the
182 // in-loop blocks to branch to the pre-exit instead of Succ.
183 // Check that all the in-loop predecessors can be changed.
184 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
185 PE = Succ->pred_end(); PI != PE; ++PI) {
186 const MachineBasicBlock *Pred = *PI;
187 // The external predecessors won't be altered.
188 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
189 continue;
190 if (!canAnalyzeBranch(Pred))
191 return false;
192 }
193
194 // If Succ's layout predecessor falls through, that too must be analyzable.
195 // We need to insert the pre-exit block in the gap.
196 MachineFunction::const_iterator MFI = Succ;
197 if (MFI == mf_.begin())
198 continue;
199 if (!canAnalyzeBranch(--MFI))
200 return false;
201 }
202 // No problems found.
203 return true;
204}
205
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000206void SplitAnalysis::analyze(const LiveInterval *li) {
207 clear();
208 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000209 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000210}
211
212const MachineLoop *SplitAnalysis::getBestSplitLoop() {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000213 assert(curli_ && "Call analyze() before getBestSplitLoop");
214 if (usingLoops_.empty())
215 return 0;
216
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000217 LoopPtrSet Loops;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000218 LoopBlocks Blocks;
219 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000220
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000221 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000222 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000223 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000224 const MachineLoop *Loop = I->first;
225 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000226
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000227 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000228 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000229 break;
230 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000231 // FIXME: We could split a live range with multiple uses in a peripheral
232 // block and still make progress. However, it is possible that splitting
233 // another live range will insert copies into a peripheral block, and
234 // there is a small chance we can enter an infinity loop, inserting copies
235 // forever.
236 // For safety, stick to splitting live ranges with uses outside the
237 // periphery.
238 DEBUG(dbgs() << " multiple peripheral uses in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000239 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000240 case ContainedInLoop:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000241 DEBUG(dbgs() << " contained in " << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000242 continue;
243 case SinglePeripheral:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000244 DEBUG(dbgs() << " single peripheral use in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000245 continue;
246 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000247 // Will it be possible to split around this loop?
248 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000249 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000250 << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000251 if (!canSplitCriticalExits(Blocks, CriticalExits))
252 continue;
253 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000254 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000255 }
256
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000257 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size()
258 << " candidate loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000259
260 if (Loops.empty())
261 return 0;
262
263 // Pick the earliest loop.
264 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000265 const MachineLoop *Best = 0;
266 SlotIndex BestIdx;
267 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
268 ++I) {
269 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
270 if (!Best || Idx < BestIdx)
271 Best = *I, BestIdx = Idx;
272 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000273 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000274 return Best;
275}
276
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000277/// getMultiUseBlocks - if curli has more than one use in a basic block, it
278/// may be an advantage to split curli for the duration of the block.
279bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
280 // If curli is local to one block, there is no point to splitting it.
281 if (usingBlocks_.size() <= 1)
282 return false;
283 // Add blocks with multiple uses.
284 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
285 I != E; ++I)
286 switch (I->second) {
287 case 0:
288 case 1:
289 continue;
290 case 2: {
291 // It doesn't pay to split a 2-instr block if it redefines curli.
292 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
293 VNInfo *VN2 =
294 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
295 // live-in and live-out with a different value.
296 if (VN1 && VN2 && VN1 != VN2)
297 continue;
298 } // Fall through.
299 default:
300 Blocks.insert(I->first);
301 }
302 return !Blocks.empty();
303}
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000304
305//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000306// LiveIntervalMap
307//===----------------------------------------------------------------------===//
308
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000309// Work around the fact that the std::pair constructors are broken for pointer
310// pairs in some implementations. makeVV(x, 0) works.
311static inline std::pair<const VNInfo*, VNInfo*>
312makeVV(const VNInfo *a, VNInfo *b) {
313 return std::make_pair(a, b);
314}
315
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000316void LiveIntervalMap::reset(LiveInterval *li) {
317 li_ = li;
318 valueMap_.clear();
319}
320
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000321bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
322 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
323 return i != valueMap_.end() && i->second == 0;
324}
325
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000326// defValue - Introduce a li_ def for ParentVNI that could be later than
327// ParentVNI->def.
328VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000329 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000330 assert(ParentVNI && "Mapping NULL value");
331 assert(Idx.isValid() && "Invalid SlotIndex");
332 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
333
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000334 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000335 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000336
337 // Use insert for lookup, so we can add missing values with a second lookup.
338 std::pair<ValueMap::iterator,bool> InsP =
339 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000340
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000341 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000342 if (!InsP.second)
343 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000344
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000345 return VNI;
346}
347
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000348
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000349// mapValue - Find the mapped value for ParentVNI at Idx.
350// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000351VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
352 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000353 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000354 assert(ParentVNI && "Mapping NULL value");
355 assert(Idx.isValid() && "Invalid SlotIndex");
356 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
357
358 // Use insert for lookup, so we can add missing values with a second lookup.
359 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000360 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000361
362 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000363 if (InsP.second) {
364 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000365 return InsP.first->second = li_->createValueCopy(ParentVNI,
366 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000367 }
368
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000369 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000370 if (InsP.first->second) {
371 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000372 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000373 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000374
375 // This is a complex mapped value. There may be multiple defs, and we may need
376 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000377 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000378 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
379 assert(IdxMBB && "No MBB at Idx");
380
381 // Is there a def in the same MBB we can extend?
382 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
383 return VNI;
384
385 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
386 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
387 // Perform a depth-first search for predecessor blocks where we know the
388 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
389
390 // Track MBBs where we have created or learned the dominating value.
391 // This may change during the DFS as we create new phi-defs.
392 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
393 MBBValueMap DomValue;
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000394 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
395 BlockPtrSet Visited;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000396
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000397 // Iterate over IdxMBB predecessors in a depth-first order.
398 // Skip begin() since that is always IdxMBB.
399 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
400 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
401 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000402 MachineBasicBlock *MBB = *IDFI;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000403 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000404
405 // We are operating on the restricted CFG where ParentVNI is live.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000406 if (parentli_.getVNInfoAt(End) != ParentVNI) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000407 IDFI.skipChildren();
408 continue;
409 }
410
411 // Do we have a dominating value in this block?
412 VNInfo *VNI = extendTo(MBB, End);
413 if (!VNI) {
414 ++IDFI;
415 continue;
416 }
417
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000418 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
419 Visited.erase(MBB);
420
421 // Track the path back to IdxMBB, creating phi-defs
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000422 // as needed along the way.
423 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000424 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000425 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
426 std::pair<MBBValueMap::iterator, bool> InsP =
427 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000428
429 // This is the first time we backtrack to Succ.
430 if (InsP.second)
431 continue;
432
433 // We reached Succ again with the same VNI. Nothing is going to change.
434 VNInfo *OVNI = InsP.first->second;
435 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000436 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000437
438 // Succ already has a phi-def. No need to continue.
439 SlotIndex Start = lis_.getMBBStartIdx(Succ);
440 if (OVNI->def == Start)
441 break;
442
443 // We have a collision between the old and new VNI at Succ. That means
444 // neither dominates and we need a new phi-def.
Lang Hames6e2968c2010-09-25 12:04:16 +0000445 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000446 VNI->setIsPHIDef(true);
447 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000448
449 // Replace OVNI with VNI in the remaining path.
450 for (; PI > 1 ; --PI) {
451 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
452 if (I == DomValue.end() || I->second != OVNI)
453 break;
454 I->second = VNI;
455 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000456 }
457
458 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000459 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000460 }
461
462 // The search should at least find a dominating value for IdxMBB.
463 assert(!DomValue.empty() && "Couldn't find a reaching definition");
464
465 // Since we went through the trouble of a full DFS visiting all reaching defs,
466 // the values in DomValue are now accurate. No more phi-defs are needed for
467 // these blocks, so we can color the live ranges.
468 // This makes the next mapValue call much faster.
469 VNInfo *IdxVNI = 0;
470 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
471 ++I) {
472 MachineBasicBlock *MBB = I->first;
473 VNInfo *VNI = I->second;
474 SlotIndex Start = lis_.getMBBStartIdx(MBB);
475 if (MBB == IdxMBB) {
476 // Don't add full liveness to IdxMBB, stop at Idx.
477 if (Start != Idx)
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000478 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000479 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000480 IdxVNI = VNI;
481 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000482 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000483 }
484
485 assert(IdxVNI && "Didn't find value for Idx");
486 return IdxVNI;
487}
488
489// extendTo - Find the last li_ value defined in MBB at or before Idx. The
490// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
491// Return the found VNInfo, or NULL.
492VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000493 assert(li_ && "call reset first");
494 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
495 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000496 return 0;
497 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000498 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000499 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000500 if (I->end <= Idx)
501 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000502 return I->valno;
503}
504
505// addSimpleRange - Add a simple range from parentli_ to li_.
506// ParentVNI must be live in the [Start;End) interval.
507void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
508 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000509 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000510 bool simple;
511 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
512 // A simple mapping is easy.
513 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000514 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000515 return;
516 }
517
518 // ParentVNI is a complex value. We must map per MBB.
519 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000520 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000521
522 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000523 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000524 return;
525 }
526
527 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000528 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000529
530 // Run sequence of full blocks.
531 for (++MBB; MBB != MBBE; ++MBB) {
532 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000533 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
534 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000535 }
536
537 // Final block.
538 Start = lis_.getMBBStartIdx(MBB);
539 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000540 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000541}
542
543/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
544/// All needed values whose def is not inside [Start;End) must be defined
545/// beforehand so mapValue will work.
546void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000547 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000548 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
549 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
550
551 // Check if --I begins before Start and overlaps.
552 if (I != B) {
553 --I;
554 if (I->end > Start)
555 addSimpleRange(Start, std::min(End, I->end), I->valno);
556 ++I;
557 }
558
559 // The remaining ranges begin after Start.
560 for (;I != E && I->start < End; ++I)
561 addSimpleRange(I->start, std::min(End, I->end), I->valno);
562}
563
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000564VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
565 const VNInfo *ParentVNI,
566 MachineBasicBlock &MBB,
567 MachineBasicBlock::iterator I) {
568 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
569 get(TargetOpcode::COPY);
570 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
571 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
572 VNInfo *VNI = defValue(ParentVNI, DefIdx);
573 VNI->setCopy(MI);
574 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
575 return VNI;
576}
577
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000578//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000579// Split Editor
580//===----------------------------------------------------------------------===//
581
582/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000583SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000584 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000585 : sa_(sa), lis_(lis), vrm_(vrm),
586 mri_(vrm.getMachineFunction().getRegInfo()),
587 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000588 edit_(edit),
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000589 curli_(sa_.getCurLI()),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000590 dupli_(lis_, *curli_),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000591 openli_(lis_, *curli_)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000592{
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000593 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000594}
595
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000596bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000597 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
598 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000599 return true;
600 return false;
601}
602
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000603/// Create a new virtual register and live interval.
604void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000605 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000606
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000607 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000608 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000609
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000610 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000611}
612
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000613/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
614/// not live before Idx, a COPY is not inserted.
615void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000616 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000617 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000618 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
619 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000620 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000621 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000622 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000623 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000624 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000625 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
626 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000627 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
628 *MI->getParent(), MI);
629 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
630 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000631}
632
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000633/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000634void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000635 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000636 SlotIndex End = lis_.getMBBEndIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000637 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000638 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
639 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000640 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000641 return;
642 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000643 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000644 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000645 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
646 MBB, MBB.getFirstTerminator());
647 // Make sure openli is live out of MBB.
648 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000649 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000650}
651
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000652/// useIntv - indicate that all instructions in MBB should use openli.
653void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
654 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000655}
656
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000657void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000658 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000659 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000660 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
661 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000662}
663
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000664/// leaveIntvAfter - Leave openli after the instruction at Idx.
665void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000666 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000667 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000668
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000669 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000670 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000671 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000672 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000673 return;
674 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000675 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000676
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000677 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
678 MachineBasicBlock *MBB = MII->getParent();
679 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
680 llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000681
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000682 // Finally we must make sure that openli is properly extended from Idx to the
683 // new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000684 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000685 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000686}
687
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000688/// leaveIntvAtTop - Leave the interval at the top of MBB.
689/// Currently, only one value can leave the interval.
690void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000691 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000692 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000693 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000694
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000695 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000696 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000697 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000698 return;
699 }
700
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000701 // We are going to insert a back copy, so we must have a dupli_.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000702 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
703 MBB, MBB.begin());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000704
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000705 // Finally we must make sure that openli is properly extended from Start to
706 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000707 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000708 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000709}
710
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000711/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000712/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000713void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000714 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000715
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000716 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000717 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000718 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000719}
720
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000721/// rewrite - Rewrite all uses of reg to use the new registers.
722void SplitEditor::rewrite(unsigned reg) {
723 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
724 RE = mri_.reg_end(); RI != RE;) {
725 MachineOperand &MO = RI.getOperand();
726 MachineInstr *MI = MO.getParent();
727 ++RI;
728 if (MI->isDebugValue()) {
729 DEBUG(dbgs() << "Zapping " << *MI);
730 // FIXME: We can do much better with debug values.
731 MO.setReg(0);
732 continue;
733 }
734 SlotIndex Idx = lis_.getInstructionIndex(MI);
735 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
736 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000737 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
738 ++I) {
739 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000740 if (testli->liveAt(Idx)) {
741 LI = testli;
742 break;
743 }
744 }
745 assert(LI && "No register was live at use");
746 MO.setReg(LI->reg);
747 DEBUG(dbgs() << " rewrite BB#" << MI->getParent()->getNumber() << '\t'
748 << Idx << '\t' << *MI);
749 }
750}
751
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000752void
753SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000754 // Build vector of iterator pairs from the intervals.
755 typedef std::pair<LiveInterval::const_iterator,
756 LiveInterval::const_iterator> IIPair;
757 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000758 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
759 ++LI) {
760 LiveInterval::const_iterator I = (*LI)->find(Start);
761 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000762 if (I != E)
763 Iters.push_back(std::make_pair(I, E));
764 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000765
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000766 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000767 // Break [Start;End) into segments that don't overlap any intervals.
768 for (;;) {
769 SlotIndex next = sidx, eidx = End;
770 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000771 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
772 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000773 // Interval I is overlapping [sidx;eidx). Trim sidx.
774 if (I->start <= sidx) {
775 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000776 // Move to the next run, remove iters when all are consumed.
777 I = ++Iters[i].first;
778 if (I == Iters[i].second) {
779 Iters.erase(Iters.begin() + i);
780 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000781 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000782 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000783 }
784 // Trim eidx too if needed.
785 if (I->start >= eidx)
786 continue;
787 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000788 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000789 }
790 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
791 if (sidx < eidx)
792 dupli_.addSimpleRange(sidx, eidx, VNI);
793 // If the interval end was truncated, we can try again from next.
794 if (next <= sidx)
795 break;
796 sidx = next;
797 }
798}
799
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000800void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000801 // First we need to fill in the live ranges in dupli.
802 // If values were redefined, we need a full recoloring with SSA update.
803 // If values were truncated, we only need to truncate the ranges.
804 // If values were partially rematted, we should shrink to uses.
805 // If values were fully rematted, they should be omitted.
806 // FIXME: If a single value is redefined, just move the def and truncate.
807
808 // Values that are fully contained in the split intervals.
809 SmallPtrSet<const VNInfo*, 8> deadValues;
810
811 // Map all curli values that should have live defs in dupli.
812 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
813 E = curli_->vni_end(); I != E; ++I) {
814 const VNInfo *VNI = *I;
815 // Original def is contained in the split intervals.
816 if (intervalsLiveAt(VNI->def)) {
817 // Did this value escape?
818 if (dupli_.isMapped(VNI))
819 truncatedValues.insert(VNI);
820 else
821 deadValues.insert(VNI);
822 continue;
823 }
824 // Add minimal live range at the definition.
825 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
826 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
827 }
828
829 // Add all ranges to dupli.
830 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
831 I != E; ++I) {
832 const LiveRange &LR = *I;
833 if (truncatedValues.count(LR.valno)) {
834 // recolor after removing intervals_.
835 addTruncSimpleRange(LR.start, LR.end, LR.valno);
836 } else if (!deadValues.count(LR.valno)) {
837 // recolor without truncation.
838 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
839 }
840 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000841}
842
843void SplitEditor::finish() {
844 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
845 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
846
847 // Complete dupli liveness.
848 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000849
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000850 // Get rid of unused values and set phi-kill flags.
851 dupli_.getLI()->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000852
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000853 // Now check if dupli was separated into multiple connected components.
854 ConnectedVNInfoEqClasses ConEQ(lis_);
855 if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
856 DEBUG(dbgs() << " Remainder has " << NumComp << " connected components: "
857 << *dupli_.getLI() << '\n');
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000858 // Did the remainder break up? Create intervals for all the components.
859 if (NumComp > 1) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000860 SmallVector<LiveInterval*, 8> dups;
861 dups.push_back(dupli_.getLI());
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000862 for (unsigned i = 1; i != NumComp; ++i)
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000863 dups.push_back(&edit_.create(mri_, lis_, vrm_));
864 ConEQ.Distribute(&dups[0]);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000865 // Rewrite uses to the new regs.
866 rewrite(dupli_.getLI()->reg);
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000867 }
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000868 }
869
870 // Rewrite instructions.
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000871 rewrite(curli_->reg);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000872
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000873 // Calculate spill weight and allocation hints for new intervals.
874 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000875 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
876 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000877 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000878 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000879 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
880 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000881 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000882}
883
884
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000885//===----------------------------------------------------------------------===//
886// Loop Splitting
887//===----------------------------------------------------------------------===//
888
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000889void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000890 SplitAnalysis::LoopBlocks Blocks;
891 sa_.getLoopBlocks(Loop, Blocks);
892
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +0000893 DEBUG({
894 dbgs() << " splitAroundLoop";
895 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
896 E = Blocks.Loop.end(); I != E; ++I)
897 dbgs() << " BB#" << (*I)->getNumber();
898 dbgs() << ", preds:";
899 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
900 E = Blocks.Preds.end(); I != E; ++I)
901 dbgs() << " BB#" << (*I)->getNumber();
902 dbgs() << ", exits:";
903 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
904 E = Blocks.Exits.end(); I != E; ++I)
905 dbgs() << " BB#" << (*I)->getNumber();
906 dbgs() << '\n';
907 });
908
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000909 // Break critical edges as needed.
910 SplitAnalysis::BlockPtrSet CriticalExits;
911 sa_.getCriticalExits(Blocks, CriticalExits);
912 assert(CriticalExits.empty() && "Cannot break critical exits yet");
913
914 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000915 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000916
917 // Insert copies in the predecessors.
918 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
919 E = Blocks.Preds.end(); I != E; ++I) {
920 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000921 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000922 }
923
924 // Switch all loop blocks.
925 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
926 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000927 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000928
929 // Insert back copies in the exit blocks.
930 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
931 E = Blocks.Exits.end(); I != E; ++I) {
932 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000933 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000934 }
935
936 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000937 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000938 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000939}
940
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000941
942//===----------------------------------------------------------------------===//
943// Single Block Splitting
944//===----------------------------------------------------------------------===//
945
946/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000947/// basic block in Blocks.
948void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000949 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000950 // Determine the first and last instruction using curli in each block.
951 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
952 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
953 IndexPairMap MBBRange;
954 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
955 E = sa_.usingInstrs_.end(); I != E; ++I) {
956 const MachineBasicBlock *MBB = (*I)->getParent();
957 if (!Blocks.count(MBB))
958 continue;
959 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000960 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000961 IndexPair &IP = MBBRange[MBB];
962 if (!IP.first.isValid() || Idx < IP.first)
963 IP.first = Idx;
964 if (!IP.second.isValid() || Idx > IP.second)
965 IP.second = Idx;
966 }
967
968 // Create a new interval for each block.
969 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
970 E = Blocks.end(); I != E; ++I) {
971 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000972 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000973 << IP.first << ';' << IP.second << ")\n");
974 assert(IP.first.isValid() && IP.second.isValid());
975
976 openIntv();
977 enterIntvBefore(IP.first);
978 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
979 leaveIntvAfter(IP.second);
980 closeIntv();
981 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000982 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000983}
984
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +0000985
986//===----------------------------------------------------------------------===//
987// Sub Block Splitting
988//===----------------------------------------------------------------------===//
989
990/// getBlockForInsideSplit - If curli is contained inside a single basic block,
991/// and it wou pay to subdivide the interval inside that block, return it.
992/// Otherwise return NULL. The returned block can be passed to
993/// SplitEditor::splitInsideBlock.
994const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
995 // The interval must be exclusive to one block.
996 if (usingBlocks_.size() != 1)
997 return 0;
998 // Don't to this for less than 4 instructions. We want to be sure that
999 // splitting actually reduces the instruction count per interval.
1000 if (usingInstrs_.size() < 4)
1001 return 0;
1002 return usingBlocks_.begin()->first;
1003}
1004
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001005/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1006void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001007 SmallVector<SlotIndex, 32> Uses;
1008 Uses.reserve(sa_.usingInstrs_.size());
1009 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1010 E = sa_.usingInstrs_.end(); I != E; ++I)
1011 if ((*I)->getParent() == MBB)
1012 Uses.push_back(lis_.getInstructionIndex(*I));
1013 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1014 << Uses.size() << " instructions.\n");
1015 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1016 array_pod_sort(Uses.begin(), Uses.end());
1017
1018 // Simple algorithm: Find the largest gap between uses as determined by slot
1019 // indices. Create new intervals for instructions before the gap and after the
1020 // gap.
1021 unsigned bestPos = 0;
1022 int bestGap = 0;
1023 DEBUG(dbgs() << " dist (" << Uses[0]);
1024 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1025 int g = Uses[i-1].distance(Uses[i]);
1026 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1027 if (g > bestGap)
1028 bestPos = i, bestGap = g;
1029 }
1030 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1031
1032 // bestPos points to the first use after the best gap.
1033 assert(bestPos > 0 && "Invalid gap");
1034
1035 // FIXME: Don't create intervals for low densities.
1036
1037 // First interval before the gap. Don't create single-instr intervals.
1038 if (bestPos > 1) {
1039 openIntv();
1040 enterIntvBefore(Uses.front());
1041 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1042 leaveIntvAfter(Uses[bestPos-1]);
1043 closeIntv();
1044 }
1045
1046 // Second interval after the gap.
1047 if (bestPos < Uses.size()-1) {
1048 openIntv();
1049 enterIntvBefore(Uses[bestPos]);
1050 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1051 leaveIntvAfter(Uses.back());
1052 closeIntv();
1053 }
1054
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001055 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001056}