blob: 81a58674bb3815331519f0393f4cd54dba7b17d9 [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 Olesen532de3d2010-10-22 20:28:21 +000082void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
83 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
84 unsigned count = usingBlocks_.lookup(*I);
85 OS << " BB#" << (*I)->getNumber();
86 if (count)
87 OS << '(' << count << ')';
88 }
89}
90
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000091// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
92// predecessor blocks, and exit blocks.
93void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
94 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000095
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000096 // Blocks in the loop.
97 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
98
99 // Predecessor blocks.
100 const MachineBasicBlock *Header = Loop->getHeader();
101 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
102 E = Header->pred_end(); I != E; ++I)
103 if (!Blocks.Loop.count(*I))
104 Blocks.Preds.insert(*I);
105
106 // Exit blocks.
107 for (MachineLoop::block_iterator I = Loop->block_begin(),
108 E = Loop->block_end(); I != E; ++I) {
109 const MachineBasicBlock *MBB = *I;
110 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
111 SE = MBB->succ_end(); SI != SE; ++SI)
112 if (!Blocks.Loop.count(*SI))
113 Blocks.Exits.insert(*SI);
114 }
115}
116
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000117void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
118 OS << "Loop:";
119 print(B.Loop, OS);
120 OS << ", preds:";
121 print(B.Preds, OS);
122 OS << ", exits:";
123 print(B.Exits, OS);
124}
125
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000126/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
127/// and around the Loop.
128SplitAnalysis::LoopPeripheralUse SplitAnalysis::
129analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000130 LoopPeripheralUse use = ContainedInLoop;
131 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
132 I != E; ++I) {
133 const MachineBasicBlock *MBB = I->first;
134 // Is this a peripheral block?
135 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000136 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000137 if (I->second > 1) use = MultiPeripheral;
138 else use = SinglePeripheral;
139 continue;
140 }
141 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000142 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000143 continue;
144 // It must be an unrelated block.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000145 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000146 return OutsideLoop;
147 }
148 return use;
149}
150
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000151/// getCriticalExits - It may be necessary to partially break critical edges
152/// leaving the loop if an exit block has phi uses of curli. Collect the exit
153/// blocks that need special treatment into CriticalExits.
154void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
155 BlockPtrSet &CriticalExits) {
156 CriticalExits.clear();
157
158 // A critical exit block contains a phi def of curli, and has a predecessor
159 // that is not in the loop nor a loop predecessor.
160 // For such an exit block, the edges carrying the new variable must be moved
161 // to a new pre-exit block.
162 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
163 I != E; ++I) {
164 const MachineBasicBlock *Succ = *I;
165 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
166 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
167 // This exit may not have curli live in at all. No need to split.
168 if (!SuccVNI)
169 continue;
170 // If this is not a PHI def, it is either using a value from before the
171 // loop, or a value defined inside the loop. Both are safe.
172 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
173 continue;
174 // This exit block does have a PHI. Does it also have a predecessor that is
175 // not a loop block or loop predecessor?
176 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
177 PE = Succ->pred_end(); PI != PE; ++PI) {
178 const MachineBasicBlock *Pred = *PI;
179 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
180 continue;
181 // This is a critical exit block, and we need to split the exit edge.
182 CriticalExits.insert(Succ);
183 break;
184 }
185 }
186}
187
188/// canSplitCriticalExits - Return true if it is possible to insert new exit
189/// blocks before the blocks in CriticalExits.
190bool
191SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
192 BlockPtrSet &CriticalExits) {
193 // If we don't allow critical edge splitting, require no critical exits.
194 if (!AllowSplit)
195 return CriticalExits.empty();
196
197 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
198 I != E; ++I) {
199 const MachineBasicBlock *Succ = *I;
200 // We want to insert a new pre-exit MBB before Succ, and change all the
201 // in-loop blocks to branch to the pre-exit instead of Succ.
202 // Check that all the in-loop predecessors can be changed.
203 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
204 PE = Succ->pred_end(); PI != PE; ++PI) {
205 const MachineBasicBlock *Pred = *PI;
206 // The external predecessors won't be altered.
207 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
208 continue;
209 if (!canAnalyzeBranch(Pred))
210 return false;
211 }
212
213 // If Succ's layout predecessor falls through, that too must be analyzable.
214 // We need to insert the pre-exit block in the gap.
215 MachineFunction::const_iterator MFI = Succ;
216 if (MFI == mf_.begin())
217 continue;
218 if (!canAnalyzeBranch(--MFI))
219 return false;
220 }
221 // No problems found.
222 return true;
223}
224
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000225void SplitAnalysis::analyze(const LiveInterval *li) {
226 clear();
227 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000228 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000229}
230
231const MachineLoop *SplitAnalysis::getBestSplitLoop() {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000232 assert(curli_ && "Call analyze() before getBestSplitLoop");
233 if (usingLoops_.empty())
234 return 0;
235
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000236 LoopPtrSet Loops;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000237 LoopBlocks Blocks;
238 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000239
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000240 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000241 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000242 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000243 const MachineLoop *Loop = I->first;
244 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000245 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000246
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000247 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000248 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000249 break;
250 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000251 // FIXME: We could split a live range with multiple uses in a peripheral
252 // block and still make progress. However, it is possible that splitting
253 // another live range will insert copies into a peripheral block, and
254 // there is a small chance we can enter an infinity loop, inserting copies
255 // forever.
256 // For safety, stick to splitting live ranges with uses outside the
257 // periphery.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000258 DEBUG(dbgs() << ": multiple peripheral uses\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000259 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000260 case ContainedInLoop:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000261 DEBUG(dbgs() << ": fully contained\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000262 continue;
263 case SinglePeripheral:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000264 DEBUG(dbgs() << ": single peripheral use\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000265 continue;
266 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000267 // Will it be possible to split around this loop?
268 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000269 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000270 if (!canSplitCriticalExits(Blocks, CriticalExits))
271 continue;
272 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000273 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000274 }
275
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000276 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size()
277 << " candidate loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000278
279 if (Loops.empty())
280 return 0;
281
282 // Pick the earliest loop.
283 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000284 const MachineLoop *Best = 0;
285 SlotIndex BestIdx;
286 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
287 ++I) {
288 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
289 if (!Best || Idx < BestIdx)
290 Best = *I, BestIdx = Idx;
291 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000292 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000293 return Best;
294}
295
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000296/// getMultiUseBlocks - if curli has more than one use in a basic block, it
297/// may be an advantage to split curli for the duration of the block.
298bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
299 // If curli is local to one block, there is no point to splitting it.
300 if (usingBlocks_.size() <= 1)
301 return false;
302 // Add blocks with multiple uses.
303 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
304 I != E; ++I)
305 switch (I->second) {
306 case 0:
307 case 1:
308 continue;
309 case 2: {
310 // It doesn't pay to split a 2-instr block if it redefines curli.
311 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
312 VNInfo *VN2 =
313 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
314 // live-in and live-out with a different value.
315 if (VN1 && VN2 && VN1 != VN2)
316 continue;
317 } // Fall through.
318 default:
319 Blocks.insert(I->first);
320 }
321 return !Blocks.empty();
322}
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000323
324//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000325// LiveIntervalMap
326//===----------------------------------------------------------------------===//
327
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000328// Work around the fact that the std::pair constructors are broken for pointer
329// pairs in some implementations. makeVV(x, 0) works.
330static inline std::pair<const VNInfo*, VNInfo*>
331makeVV(const VNInfo *a, VNInfo *b) {
332 return std::make_pair(a, b);
333}
334
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000335void LiveIntervalMap::reset(LiveInterval *li) {
336 li_ = li;
337 valueMap_.clear();
338}
339
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000340bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
341 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
342 return i != valueMap_.end() && i->second == 0;
343}
344
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000345// defValue - Introduce a li_ def for ParentVNI that could be later than
346// ParentVNI->def.
347VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000348 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000349 assert(ParentVNI && "Mapping NULL value");
350 assert(Idx.isValid() && "Invalid SlotIndex");
351 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
352
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000353 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000354 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000355
356 // Use insert for lookup, so we can add missing values with a second lookup.
357 std::pair<ValueMap::iterator,bool> InsP =
358 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000359
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000360 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000361 if (!InsP.second)
362 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000363
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000364 return VNI;
365}
366
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000367
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000368// mapValue - Find the mapped value for ParentVNI at Idx.
369// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000370VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
371 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000372 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000373 assert(ParentVNI && "Mapping NULL value");
374 assert(Idx.isValid() && "Invalid SlotIndex");
375 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
376
377 // Use insert for lookup, so we can add missing values with a second lookup.
378 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000379 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000380
381 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000382 if (InsP.second) {
383 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000384 return InsP.first->second = li_->createValueCopy(ParentVNI,
385 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000386 }
387
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000388 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000389 if (InsP.first->second) {
390 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000391 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000392 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000393
394 // This is a complex mapped value. There may be multiple defs, and we may need
395 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000396 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000397 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
398 assert(IdxMBB && "No MBB at Idx");
399
400 // Is there a def in the same MBB we can extend?
401 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
402 return VNI;
403
404 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
405 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
406 // Perform a depth-first search for predecessor blocks where we know the
407 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
408
409 // Track MBBs where we have created or learned the dominating value.
410 // This may change during the DFS as we create new phi-defs.
411 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
412 MBBValueMap DomValue;
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000413 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
414 BlockPtrSet Visited;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000415
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000416 // Iterate over IdxMBB predecessors in a depth-first order.
417 // Skip begin() since that is always IdxMBB.
418 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
419 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
420 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000421 MachineBasicBlock *MBB = *IDFI;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000422 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000423
424 // We are operating on the restricted CFG where ParentVNI is live.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000425 if (parentli_.getVNInfoAt(End) != ParentVNI) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000426 IDFI.skipChildren();
427 continue;
428 }
429
430 // Do we have a dominating value in this block?
431 VNInfo *VNI = extendTo(MBB, End);
432 if (!VNI) {
433 ++IDFI;
434 continue;
435 }
436
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000437 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
438 Visited.erase(MBB);
439
440 // Track the path back to IdxMBB, creating phi-defs
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000441 // as needed along the way.
442 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000443 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000444 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
445 std::pair<MBBValueMap::iterator, bool> InsP =
446 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000447
448 // This is the first time we backtrack to Succ.
449 if (InsP.second)
450 continue;
451
452 // We reached Succ again with the same VNI. Nothing is going to change.
453 VNInfo *OVNI = InsP.first->second;
454 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000455 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000456
457 // Succ already has a phi-def. No need to continue.
458 SlotIndex Start = lis_.getMBBStartIdx(Succ);
459 if (OVNI->def == Start)
460 break;
461
462 // We have a collision between the old and new VNI at Succ. That means
463 // neither dominates and we need a new phi-def.
Lang Hames6e2968c2010-09-25 12:04:16 +0000464 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000465 VNI->setIsPHIDef(true);
466 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000467
468 // Replace OVNI with VNI in the remaining path.
469 for (; PI > 1 ; --PI) {
470 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
471 if (I == DomValue.end() || I->second != OVNI)
472 break;
473 I->second = VNI;
474 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000475 }
476
477 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000478 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000479 }
480
481 // The search should at least find a dominating value for IdxMBB.
482 assert(!DomValue.empty() && "Couldn't find a reaching definition");
483
484 // Since we went through the trouble of a full DFS visiting all reaching defs,
485 // the values in DomValue are now accurate. No more phi-defs are needed for
486 // these blocks, so we can color the live ranges.
487 // This makes the next mapValue call much faster.
488 VNInfo *IdxVNI = 0;
489 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
490 ++I) {
491 MachineBasicBlock *MBB = I->first;
492 VNInfo *VNI = I->second;
493 SlotIndex Start = lis_.getMBBStartIdx(MBB);
494 if (MBB == IdxMBB) {
495 // Don't add full liveness to IdxMBB, stop at Idx.
496 if (Start != Idx)
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000497 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000498 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000499 IdxVNI = VNI;
500 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000501 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000502 }
503
504 assert(IdxVNI && "Didn't find value for Idx");
505 return IdxVNI;
506}
507
508// extendTo - Find the last li_ value defined in MBB at or before Idx. The
509// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
510// Return the found VNInfo, or NULL.
511VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000512 assert(li_ && "call reset first");
513 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
514 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000515 return 0;
516 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000517 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000518 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000519 if (I->end <= Idx)
520 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000521 return I->valno;
522}
523
524// addSimpleRange - Add a simple range from parentli_ to li_.
525// ParentVNI must be live in the [Start;End) interval.
526void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
527 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000528 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000529 bool simple;
530 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
531 // A simple mapping is easy.
532 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000533 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000534 return;
535 }
536
537 // ParentVNI is a complex value. We must map per MBB.
538 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000539 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000540
541 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000542 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000543 return;
544 }
545
546 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000547 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000548
549 // Run sequence of full blocks.
550 for (++MBB; MBB != MBBE; ++MBB) {
551 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000552 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
553 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000554 }
555
556 // Final block.
557 Start = lis_.getMBBStartIdx(MBB);
558 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000559 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000560}
561
562/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
563/// All needed values whose def is not inside [Start;End) must be defined
564/// beforehand so mapValue will work.
565void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000566 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000567 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
568 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
569
570 // Check if --I begins before Start and overlaps.
571 if (I != B) {
572 --I;
573 if (I->end > Start)
574 addSimpleRange(Start, std::min(End, I->end), I->valno);
575 ++I;
576 }
577
578 // The remaining ranges begin after Start.
579 for (;I != E && I->start < End; ++I)
580 addSimpleRange(I->start, std::min(End, I->end), I->valno);
581}
582
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000583VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
584 const VNInfo *ParentVNI,
585 MachineBasicBlock &MBB,
586 MachineBasicBlock::iterator I) {
587 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
588 get(TargetOpcode::COPY);
589 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
590 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
591 VNInfo *VNI = defValue(ParentVNI, DefIdx);
592 VNI->setCopy(MI);
593 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
594 return VNI;
595}
596
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000597//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000598// Split Editor
599//===----------------------------------------------------------------------===//
600
601/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000602SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000603 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000604 : sa_(sa), lis_(lis), vrm_(vrm),
605 mri_(vrm.getMachineFunction().getRegInfo()),
606 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000607 edit_(edit),
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000608 dupli_(lis_, edit.getParent()),
609 openli_(lis_, edit.getParent())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000610{
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000611}
612
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000613bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000614 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
615 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000616 return true;
617 return false;
618}
619
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000620/// Create a new virtual register and live interval.
621void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000622 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000623
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000624 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000625 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000626
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000627 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000628}
629
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000630/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
631/// not live before Idx, a COPY is not inserted.
632void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000633 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000634 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000635 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getUseIndex());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000636 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000637 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000638 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000639 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000640 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000641 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000642 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
643 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000644 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000645 *MI->getParent(), MI);
646 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
647 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000648}
649
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000650/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000651void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000652 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000653 SlotIndex End = lis_.getMBBEndIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000654 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000655 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End.getPrevSlot());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000656 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000657 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000658 return;
659 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000660 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000661 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000662 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000663 MBB, MBB.getFirstTerminator());
664 // Make sure openli is live out of MBB.
665 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000666 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000667}
668
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000669/// useIntv - indicate that all instructions in MBB should use openli.
670void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
671 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000672}
673
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000674void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000675 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000676 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000677 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
678 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000679}
680
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000681/// leaveIntvAfter - Leave openli after the instruction at Idx.
682void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000683 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000684 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000685
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000686 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000687 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getBoundaryIndex());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000688 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000689 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000690 return;
691 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000692 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000693
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000694 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
695 MachineBasicBlock *MBB = MII->getParent();
696 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
697 llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000698
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000699 // Finally we must make sure that openli is properly extended from Idx to the
700 // new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000701 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000702 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000703}
704
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000705/// leaveIntvAtTop - Leave the interval at the top of MBB.
706/// Currently, only one value can leave the interval.
707void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000708 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000709 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000710 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000711
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000712 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000713 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000714 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000715 return;
716 }
717
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000718 // We are going to insert a back copy, so we must have a dupli_.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000719 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
720 MBB, MBB.begin());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000721
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000722 // Finally we must make sure that openli is properly extended from Start to
723 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000724 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000725 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000726}
727
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000728/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000729/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000730void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000731 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000732
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000733 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000734 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000735 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000736}
737
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000738/// rewrite - Rewrite all uses of reg to use the new registers.
739void SplitEditor::rewrite(unsigned reg) {
740 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
741 RE = mri_.reg_end(); RI != RE;) {
742 MachineOperand &MO = RI.getOperand();
743 MachineInstr *MI = MO.getParent();
744 ++RI;
745 if (MI->isDebugValue()) {
746 DEBUG(dbgs() << "Zapping " << *MI);
747 // FIXME: We can do much better with debug values.
748 MO.setReg(0);
749 continue;
750 }
751 SlotIndex Idx = lis_.getInstructionIndex(MI);
752 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
753 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000754 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
755 ++I) {
756 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000757 if (testli->liveAt(Idx)) {
758 LI = testli;
759 break;
760 }
761 }
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000762 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000763 assert(LI && "No register was live at use");
764 MO.setReg(LI->reg);
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000765 DEBUG(dbgs() << '\t' << *MI);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000766 }
767}
768
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000769void
770SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000771 // Build vector of iterator pairs from the intervals.
772 typedef std::pair<LiveInterval::const_iterator,
773 LiveInterval::const_iterator> IIPair;
774 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000775 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
776 ++LI) {
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000777 if (*LI == dupli_.getLI())
778 continue;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000779 LiveInterval::const_iterator I = (*LI)->find(Start);
780 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000781 if (I != E)
782 Iters.push_back(std::make_pair(I, E));
783 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000784
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000785 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000786 // Break [Start;End) into segments that don't overlap any intervals.
787 for (;;) {
788 SlotIndex next = sidx, eidx = End;
789 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000790 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
791 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000792 // Interval I is overlapping [sidx;eidx). Trim sidx.
793 if (I->start <= sidx) {
794 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000795 // Move to the next run, remove iters when all are consumed.
796 I = ++Iters[i].first;
797 if (I == Iters[i].second) {
798 Iters.erase(Iters.begin() + i);
799 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000800 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000801 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000802 }
803 // Trim eidx too if needed.
804 if (I->start >= eidx)
805 continue;
806 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000807 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000808 }
809 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
810 if (sidx < eidx)
811 dupli_.addSimpleRange(sidx, eidx, VNI);
812 // If the interval end was truncated, we can try again from next.
813 if (next <= sidx)
814 break;
815 sidx = next;
816 }
817}
818
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000819void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000820 // First we need to fill in the live ranges in dupli.
821 // If values were redefined, we need a full recoloring with SSA update.
822 // If values were truncated, we only need to truncate the ranges.
823 // If values were partially rematted, we should shrink to uses.
824 // If values were fully rematted, they should be omitted.
825 // FIXME: If a single value is redefined, just move the def and truncate.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000826 LiveInterval &parent = edit_.getParent();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000827
828 // Values that are fully contained in the split intervals.
829 SmallPtrSet<const VNInfo*, 8> deadValues;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000830 // Map all curli values that should have live defs in dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000831 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
832 E = parent.vni_end(); I != E; ++I) {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000833 const VNInfo *VNI = *I;
834 // Original def is contained in the split intervals.
835 if (intervalsLiveAt(VNI->def)) {
836 // Did this value escape?
837 if (dupli_.isMapped(VNI))
838 truncatedValues.insert(VNI);
839 else
840 deadValues.insert(VNI);
841 continue;
842 }
843 // Add minimal live range at the definition.
844 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
845 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
846 }
847
848 // Add all ranges to dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000849 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000850 I != E; ++I) {
851 const LiveRange &LR = *I;
852 if (truncatedValues.count(LR.valno)) {
853 // recolor after removing intervals_.
854 addTruncSimpleRange(LR.start, LR.end, LR.valno);
855 } else if (!deadValues.count(LR.valno)) {
856 // recolor without truncation.
857 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
858 }
859 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000860}
861
862void SplitEditor::finish() {
863 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
864 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
865
866 // Complete dupli liveness.
867 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000868
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000869 // Get rid of unused values and set phi-kill flags.
870 dupli_.getLI()->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000871
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000872 // Now check if dupli was separated into multiple connected components.
873 ConnectedVNInfoEqClasses ConEQ(lis_);
874 if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
875 DEBUG(dbgs() << " Remainder has " << NumComp << " connected components: "
876 << *dupli_.getLI() << '\n');
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000877 // Did the remainder break up? Create intervals for all the components.
878 if (NumComp > 1) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000879 SmallVector<LiveInterval*, 8> dups;
880 dups.push_back(dupli_.getLI());
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000881 for (unsigned i = 1; i != NumComp; ++i)
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000882 dups.push_back(&edit_.create(mri_, lis_, vrm_));
883 ConEQ.Distribute(&dups[0]);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000884 // Rewrite uses to the new regs.
885 rewrite(dupli_.getLI()->reg);
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000886 }
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000887 }
888
889 // Rewrite instructions.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000890 rewrite(edit_.getReg());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000891
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000892 // Calculate spill weight and allocation hints for new intervals.
893 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000894 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
895 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000896 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000897 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000898 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
899 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000900 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000901}
902
903
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000904//===----------------------------------------------------------------------===//
905// Loop Splitting
906//===----------------------------------------------------------------------===//
907
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000908void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000909 SplitAnalysis::LoopBlocks Blocks;
910 sa_.getLoopBlocks(Loop, Blocks);
911
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +0000912 DEBUG({
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000913 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +0000914 });
915
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000916 // Break critical edges as needed.
917 SplitAnalysis::BlockPtrSet CriticalExits;
918 sa_.getCriticalExits(Blocks, CriticalExits);
919 assert(CriticalExits.empty() && "Cannot break critical exits yet");
920
921 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000922 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000923
924 // Insert copies in the predecessors.
925 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
926 E = Blocks.Preds.end(); I != E; ++I) {
927 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000928 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000929 }
930
931 // Switch all loop blocks.
932 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
933 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000934 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000935
936 // Insert back copies in the exit blocks.
937 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
938 E = Blocks.Exits.end(); I != E; ++I) {
939 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000940 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000941 }
942
943 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000944 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000945 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000946}
947
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000948
949//===----------------------------------------------------------------------===//
950// Single Block Splitting
951//===----------------------------------------------------------------------===//
952
953/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000954/// basic block in Blocks.
955void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000956 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000957 // Determine the first and last instruction using curli in each block.
958 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
959 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
960 IndexPairMap MBBRange;
961 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
962 E = sa_.usingInstrs_.end(); I != E; ++I) {
963 const MachineBasicBlock *MBB = (*I)->getParent();
964 if (!Blocks.count(MBB))
965 continue;
966 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000967 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000968 IndexPair &IP = MBBRange[MBB];
969 if (!IP.first.isValid() || Idx < IP.first)
970 IP.first = Idx;
971 if (!IP.second.isValid() || Idx > IP.second)
972 IP.second = Idx;
973 }
974
975 // Create a new interval for each block.
976 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
977 E = Blocks.end(); I != E; ++I) {
978 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000979 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000980 << IP.first << ';' << IP.second << ")\n");
981 assert(IP.first.isValid() && IP.second.isValid());
982
983 openIntv();
984 enterIntvBefore(IP.first);
985 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
986 leaveIntvAfter(IP.second);
987 closeIntv();
988 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000989 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000990}
991
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +0000992
993//===----------------------------------------------------------------------===//
994// Sub Block Splitting
995//===----------------------------------------------------------------------===//
996
997/// getBlockForInsideSplit - If curli is contained inside a single basic block,
998/// and it wou pay to subdivide the interval inside that block, return it.
999/// Otherwise return NULL. The returned block can be passed to
1000/// SplitEditor::splitInsideBlock.
1001const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1002 // The interval must be exclusive to one block.
1003 if (usingBlocks_.size() != 1)
1004 return 0;
1005 // Don't to this for less than 4 instructions. We want to be sure that
1006 // splitting actually reduces the instruction count per interval.
1007 if (usingInstrs_.size() < 4)
1008 return 0;
1009 return usingBlocks_.begin()->first;
1010}
1011
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001012/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1013void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001014 SmallVector<SlotIndex, 32> Uses;
1015 Uses.reserve(sa_.usingInstrs_.size());
1016 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1017 E = sa_.usingInstrs_.end(); I != E; ++I)
1018 if ((*I)->getParent() == MBB)
1019 Uses.push_back(lis_.getInstructionIndex(*I));
1020 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1021 << Uses.size() << " instructions.\n");
1022 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1023 array_pod_sort(Uses.begin(), Uses.end());
1024
1025 // Simple algorithm: Find the largest gap between uses as determined by slot
1026 // indices. Create new intervals for instructions before the gap and after the
1027 // gap.
1028 unsigned bestPos = 0;
1029 int bestGap = 0;
1030 DEBUG(dbgs() << " dist (" << Uses[0]);
1031 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1032 int g = Uses[i-1].distance(Uses[i]);
1033 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1034 if (g > bestGap)
1035 bestPos = i, bestGap = g;
1036 }
1037 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1038
1039 // bestPos points to the first use after the best gap.
1040 assert(bestPos > 0 && "Invalid gap");
1041
1042 // FIXME: Don't create intervals for low densities.
1043
1044 // First interval before the gap. Don't create single-instr intervals.
1045 if (bestPos > 1) {
1046 openIntv();
1047 enterIntvBefore(Uses.front());
1048 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1049 leaveIntvAfter(Uses[bestPos-1]);
1050 closeIntv();
1051 }
1052
1053 // Second interval after the gap.
1054 if (bestPos < Uses.size()-1) {
1055 openIntv();
1056 enterIntvBefore(Uses[bestPos]);
1057 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1058 leaveIntvAfter(Uses.back());
1059 closeIntv();
1060 }
1061
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001062 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001063}