blob: 1864e3781321d243840504c49a5495c57ee435a8 [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 Olesenf0179002010-07-26 23:44:11 +000017#include "VirtRegMap.h"
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +000018#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000023#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000028
29using namespace llvm;
30
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000031static cl::opt<bool>
32AllowSplit("spiller-splits-edges",
33 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000034
35//===----------------------------------------------------------------------===//
36// Split Analysis
37//===----------------------------------------------------------------------===//
38
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000039SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
40 const LiveIntervals &lis,
41 const MachineLoopInfo &mli)
42 : mf_(mf),
43 lis_(lis),
44 loops_(mli),
45 tii_(*mf.getTarget().getInstrInfo()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000046 curli_(0) {}
47
48void SplitAnalysis::clear() {
49 usingInstrs_.clear();
50 usingBlocks_.clear();
51 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000052 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000053}
54
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000055bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
56 MachineBasicBlock *T, *F;
57 SmallVector<MachineOperand, 4> Cond;
58 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
59}
60
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000061/// analyzeUses - Count instructions, basic blocks, and loops using curli.
62void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000063 const MachineRegisterInfo &MRI = mf_.getRegInfo();
64 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
65 MachineInstr *MI = I.skipInstruction();) {
66 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
67 continue;
68 MachineBasicBlock *MBB = MI->getParent();
69 if (usingBlocks_[MBB]++)
70 continue;
71 if (MachineLoop *Loop = loops_.getLoopFor(MBB))
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000072 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000073 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000074 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000075 << usingInstrs_.size() << " instrs, "
76 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000077 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000078}
79
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000080/// removeUse - Update statistics by noting that MI no longer uses curli.
81void SplitAnalysis::removeUse(const MachineInstr *MI) {
82 if (!usingInstrs_.erase(MI))
83 return;
84
85 // Decrement MBB count.
86 const MachineBasicBlock *MBB = MI->getParent();
87 BlockCountMap::iterator bi = usingBlocks_.find(MBB);
88 assert(bi != usingBlocks_.end() && "MBB missing");
89 assert(bi->second && "0 count in map");
90 if (--bi->second)
91 return;
92 // No more uses in MBB.
93 usingBlocks_.erase(bi);
94
95 // Decrement loop count.
96 MachineLoop *Loop = loops_.getLoopFor(MBB);
97 if (!Loop)
98 return;
99 LoopCountMap::iterator li = usingLoops_.find(Loop);
100 assert(li != usingLoops_.end() && "Loop missing");
101 assert(li->second && "0 count in map");
102 if (--li->second)
103 return;
104 // No more blocks in Loop.
105 usingLoops_.erase(li);
106}
107
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000108// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
109// predecessor blocks, and exit blocks.
110void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
111 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000112
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000113 // Blocks in the loop.
114 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
115
116 // Predecessor blocks.
117 const MachineBasicBlock *Header = Loop->getHeader();
118 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
119 E = Header->pred_end(); I != E; ++I)
120 if (!Blocks.Loop.count(*I))
121 Blocks.Preds.insert(*I);
122
123 // Exit blocks.
124 for (MachineLoop::block_iterator I = Loop->block_begin(),
125 E = Loop->block_end(); I != E; ++I) {
126 const MachineBasicBlock *MBB = *I;
127 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
128 SE = MBB->succ_end(); SI != SE; ++SI)
129 if (!Blocks.Loop.count(*SI))
130 Blocks.Exits.insert(*SI);
131 }
132}
133
134/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
135/// and around the Loop.
136SplitAnalysis::LoopPeripheralUse SplitAnalysis::
137analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000138 LoopPeripheralUse use = ContainedInLoop;
139 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
140 I != E; ++I) {
141 const MachineBasicBlock *MBB = I->first;
142 // Is this a peripheral block?
143 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000144 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000145 if (I->second > 1) use = MultiPeripheral;
146 else use = SinglePeripheral;
147 continue;
148 }
149 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000150 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000151 continue;
152 // It must be an unrelated block.
153 return OutsideLoop;
154 }
155 return use;
156}
157
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000158/// getCriticalExits - It may be necessary to partially break critical edges
159/// leaving the loop if an exit block has phi uses of curli. Collect the exit
160/// blocks that need special treatment into CriticalExits.
161void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
162 BlockPtrSet &CriticalExits) {
163 CriticalExits.clear();
164
165 // A critical exit block contains a phi def of curli, and has a predecessor
166 // that is not in the loop nor a loop predecessor.
167 // For such an exit block, the edges carrying the new variable must be moved
168 // to a new pre-exit block.
169 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
170 I != E; ++I) {
171 const MachineBasicBlock *Succ = *I;
172 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
173 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
174 // This exit may not have curli live in at all. No need to split.
175 if (!SuccVNI)
176 continue;
177 // If this is not a PHI def, it is either using a value from before the
178 // loop, or a value defined inside the loop. Both are safe.
179 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
180 continue;
181 // This exit block does have a PHI. Does it also have a predecessor that is
182 // not a loop block or loop predecessor?
183 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184 PE = Succ->pred_end(); PI != PE; ++PI) {
185 const MachineBasicBlock *Pred = *PI;
186 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
187 continue;
188 // This is a critical exit block, and we need to split the exit edge.
189 CriticalExits.insert(Succ);
190 break;
191 }
192 }
193}
194
195/// canSplitCriticalExits - Return true if it is possible to insert new exit
196/// blocks before the blocks in CriticalExits.
197bool
198SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
199 BlockPtrSet &CriticalExits) {
200 // If we don't allow critical edge splitting, require no critical exits.
201 if (!AllowSplit)
202 return CriticalExits.empty();
203
204 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
205 I != E; ++I) {
206 const MachineBasicBlock *Succ = *I;
207 // We want to insert a new pre-exit MBB before Succ, and change all the
208 // in-loop blocks to branch to the pre-exit instead of Succ.
209 // Check that all the in-loop predecessors can be changed.
210 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
211 PE = Succ->pred_end(); PI != PE; ++PI) {
212 const MachineBasicBlock *Pred = *PI;
213 // The external predecessors won't be altered.
214 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
215 continue;
216 if (!canAnalyzeBranch(Pred))
217 return false;
218 }
219
220 // If Succ's layout predecessor falls through, that too must be analyzable.
221 // We need to insert the pre-exit block in the gap.
222 MachineFunction::const_iterator MFI = Succ;
223 if (MFI == mf_.begin())
224 continue;
225 if (!canAnalyzeBranch(--MFI))
226 return false;
227 }
228 // No problems found.
229 return true;
230}
231
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000232void SplitAnalysis::analyze(const LiveInterval *li) {
233 clear();
234 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000235 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000236}
237
238const MachineLoop *SplitAnalysis::getBestSplitLoop() {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000239 assert(curli_ && "Call analyze() before getBestSplitLoop");
240 if (usingLoops_.empty())
241 return 0;
242
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000243 LoopPtrSet Loops, SecondLoops;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000244 LoopBlocks Blocks;
245 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000246
247 // Find first-class and second class candidate loops.
248 // We prefer to split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000249 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000250 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000251 const MachineLoop *Loop = I->first;
252 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000253
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000254 LoopPtrSet *LPS = 0;
255 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000256 case OutsideLoop:
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000257 LPS = &Loops;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000258 break;
259 case MultiPeripheral:
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000260 LPS = &SecondLoops;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000261 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000262 case ContainedInLoop:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000263 DEBUG(dbgs() << " contained in " << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000264 continue;
265 case SinglePeripheral:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000266 DEBUG(dbgs() << " single peripheral use in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000267 continue;
268 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000269 // Will it be possible to split around this loop?
270 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000271 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000272 << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000273 if (!canSplitCriticalExits(Blocks, CriticalExits))
274 continue;
275 // This is a possible split.
276 assert(LPS);
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000277 LPS->insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000278 }
279
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000280 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() << " + "
281 << SecondLoops.size() << " candidate loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000282
283 // If there are no first class loops available, look at second class loops.
284 if (Loops.empty())
285 Loops = SecondLoops;
286
287 if (Loops.empty())
288 return 0;
289
290 // Pick the earliest loop.
291 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000292 const MachineLoop *Best = 0;
293 SlotIndex BestIdx;
294 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
295 ++I) {
296 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
297 if (!Best || Idx < BestIdx)
298 Best = *I, BestIdx = Idx;
299 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000300 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000301 return Best;
302}
303
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000304/// getMultiUseBlocks - if curli has more than one use in a basic block, it
305/// may be an advantage to split curli for the duration of the block.
306bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
307 // If curli is local to one block, there is no point to splitting it.
308 if (usingBlocks_.size() <= 1)
309 return false;
310 // Add blocks with multiple uses.
311 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
312 I != E; ++I)
313 switch (I->second) {
314 case 0:
315 case 1:
316 continue;
317 case 2: {
318 // It doesn't pay to split a 2-instr block if it redefines curli.
319 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
320 VNInfo *VN2 =
321 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
322 // live-in and live-out with a different value.
323 if (VN1 && VN2 && VN1 != VN2)
324 continue;
325 } // Fall through.
326 default:
327 Blocks.insert(I->first);
328 }
329 return !Blocks.empty();
330}
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000331
332//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000333// LiveIntervalMap
334//===----------------------------------------------------------------------===//
335
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000336// Work around the fact that the std::pair constructors are broken for pointer
337// pairs in some implementations. makeVV(x, 0) works.
338static inline std::pair<const VNInfo*, VNInfo*>
339makeVV(const VNInfo *a, VNInfo *b) {
340 return std::make_pair(a, b);
341}
342
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000343void LiveIntervalMap::reset(LiveInterval *li) {
344 li_ = li;
345 valueMap_.clear();
346}
347
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000348bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
349 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
350 return i != valueMap_.end() && i->second == 0;
351}
352
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000353// defValue - Introduce a li_ def for ParentVNI that could be later than
354// ParentVNI->def.
355VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000356 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000357 assert(ParentVNI && "Mapping NULL value");
358 assert(Idx.isValid() && "Invalid SlotIndex");
359 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
360
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000361 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000362 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000363
364 // Use insert for lookup, so we can add missing values with a second lookup.
365 std::pair<ValueMap::iterator,bool> InsP =
366 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000367
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000368 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000369 if (!InsP.second)
370 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000371
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000372 return VNI;
373}
374
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000375
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000376// mapValue - Find the mapped value for ParentVNI at Idx.
377// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000378VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
379 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000380 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000381 assert(ParentVNI && "Mapping NULL value");
382 assert(Idx.isValid() && "Invalid SlotIndex");
383 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
384
385 // Use insert for lookup, so we can add missing values with a second lookup.
386 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000387 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000388
389 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000390 if (InsP.second) {
391 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000392 return InsP.first->second = li_->createValueCopy(ParentVNI,
393 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000394 }
395
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000396 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000397 if (InsP.first->second) {
398 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000399 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000400 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000401
402 // This is a complex mapped value. There may be multiple defs, and we may need
403 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000404 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000405 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
406 assert(IdxMBB && "No MBB at Idx");
407
408 // Is there a def in the same MBB we can extend?
409 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
410 return VNI;
411
412 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
413 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
414 // Perform a depth-first search for predecessor blocks where we know the
415 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
416
417 // Track MBBs where we have created or learned the dominating value.
418 // This may change during the DFS as we create new phi-defs.
419 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
420 MBBValueMap DomValue;
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000421 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
422 BlockPtrSet Visited;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000423
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000424 // Iterate over IdxMBB predecessors in a depth-first order.
425 // Skip begin() since that is always IdxMBB.
426 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
427 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
428 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000429 MachineBasicBlock *MBB = *IDFI;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000430 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000431
432 // We are operating on the restricted CFG where ParentVNI is live.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000433 if (parentli_.getVNInfoAt(End) != ParentVNI) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000434 IDFI.skipChildren();
435 continue;
436 }
437
438 // Do we have a dominating value in this block?
439 VNInfo *VNI = extendTo(MBB, End);
440 if (!VNI) {
441 ++IDFI;
442 continue;
443 }
444
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000445 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
446 Visited.erase(MBB);
447
448 // Track the path back to IdxMBB, creating phi-defs
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000449 // as needed along the way.
450 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000451 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000452 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
453 std::pair<MBBValueMap::iterator, bool> InsP =
454 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000455
456 // This is the first time we backtrack to Succ.
457 if (InsP.second)
458 continue;
459
460 // We reached Succ again with the same VNI. Nothing is going to change.
461 VNInfo *OVNI = InsP.first->second;
462 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000463 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000464
465 // Succ already has a phi-def. No need to continue.
466 SlotIndex Start = lis_.getMBBStartIdx(Succ);
467 if (OVNI->def == Start)
468 break;
469
470 // We have a collision between the old and new VNI at Succ. That means
471 // neither dominates and we need a new phi-def.
Lang Hames6e2968c2010-09-25 12:04:16 +0000472 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000473 VNI->setIsPHIDef(true);
474 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000475
476 // Replace OVNI with VNI in the remaining path.
477 for (; PI > 1 ; --PI) {
478 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
479 if (I == DomValue.end() || I->second != OVNI)
480 break;
481 I->second = VNI;
482 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000483 }
484
485 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000486 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000487 }
488
489 // The search should at least find a dominating value for IdxMBB.
490 assert(!DomValue.empty() && "Couldn't find a reaching definition");
491
492 // Since we went through the trouble of a full DFS visiting all reaching defs,
493 // the values in DomValue are now accurate. No more phi-defs are needed for
494 // these blocks, so we can color the live ranges.
495 // This makes the next mapValue call much faster.
496 VNInfo *IdxVNI = 0;
497 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
498 ++I) {
499 MachineBasicBlock *MBB = I->first;
500 VNInfo *VNI = I->second;
501 SlotIndex Start = lis_.getMBBStartIdx(MBB);
502 if (MBB == IdxMBB) {
503 // Don't add full liveness to IdxMBB, stop at Idx.
504 if (Start != Idx)
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000505 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000506 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000507 IdxVNI = VNI;
508 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000509 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000510 }
511
512 assert(IdxVNI && "Didn't find value for Idx");
513 return IdxVNI;
514}
515
516// extendTo - Find the last li_ value defined in MBB at or before Idx. The
517// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
518// Return the found VNInfo, or NULL.
519VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000520 assert(li_ && "call reset first");
521 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
522 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000523 return 0;
524 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000525 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000526 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000527 if (I->end <= Idx)
528 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000529 return I->valno;
530}
531
532// addSimpleRange - Add a simple range from parentli_ to li_.
533// ParentVNI must be live in the [Start;End) interval.
534void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
535 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000536 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000537 bool simple;
538 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
539 // A simple mapping is easy.
540 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000541 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000542 return;
543 }
544
545 // ParentVNI is a complex value. We must map per MBB.
546 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000547 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000548
549 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000550 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000551 return;
552 }
553
554 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000555 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000556
557 // Run sequence of full blocks.
558 for (++MBB; MBB != MBBE; ++MBB) {
559 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000560 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
561 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000562 }
563
564 // Final block.
565 Start = lis_.getMBBStartIdx(MBB);
566 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000567 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000568}
569
570/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
571/// All needed values whose def is not inside [Start;End) must be defined
572/// beforehand so mapValue will work.
573void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000574 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000575 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
576 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
577
578 // Check if --I begins before Start and overlaps.
579 if (I != B) {
580 --I;
581 if (I->end > Start)
582 addSimpleRange(Start, std::min(End, I->end), I->valno);
583 ++I;
584 }
585
586 // The remaining ranges begin after Start.
587 for (;I != E && I->start < End; ++I)
588 addSimpleRange(I->start, std::min(End, I->end), I->valno);
589}
590
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000591VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
592 const VNInfo *ParentVNI,
593 MachineBasicBlock &MBB,
594 MachineBasicBlock::iterator I) {
595 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
596 get(TargetOpcode::COPY);
597 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
598 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
599 VNInfo *VNI = defValue(ParentVNI, DefIdx);
600 VNI->setCopy(MI);
601 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
602 return VNI;
603}
604
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000605//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000606// Split Editor
607//===----------------------------------------------------------------------===//
608
609/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000610SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
Jakob Stoklund Olesen0a2b2a12010-08-13 22:56:53 +0000611 SmallVectorImpl<LiveInterval*> &intervals)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000612 : sa_(sa), lis_(lis), vrm_(vrm),
613 mri_(vrm.getMachineFunction().getRegInfo()),
614 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000615 curli_(sa_.getCurLI()),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000616 dupli_(lis_, *curli_),
617 openli_(lis_, *curli_),
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000618 intervals_(intervals),
619 firstInterval(intervals_.size())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000620{
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000621 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000622
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000623 // Make sure curli_ is assigned a stack slot, so all our intervals get the
624 // same slot as curli_.
625 if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
626 vrm_.assignVirt2StackSlot(curli_->reg);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000627
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000628}
629
630LiveInterval *SplitEditor::createInterval() {
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000631 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000632 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
633 vrm_.grow();
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000634 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000635 return &Intv;
636}
637
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000638bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
639 for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
640 if (intervals_[i]->liveAt(Idx))
641 return true;
642 return false;
643}
644
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000645/// Create a new virtual register and live interval.
646void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000647 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000648
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000649 if (!dupli_.getLI())
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000650 dupli_.reset(createInterval());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000651
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000652 openli_.reset(createInterval());
653 intervals_.push_back(openli_.getLI());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000654}
655
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000656/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
657/// not live before Idx, a COPY is not inserted.
658void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000659 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000660 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
661 if (!ParentVNI) {
662 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": not live\n");
663 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000664 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000665 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000666 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
667 assert(MI && "enterIntvBefore called with invalid index");
668 openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000669 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_.getLI()
670 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000671}
672
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000673/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000674void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000675 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000676 SlotIndex End = lis_.getMBBEndIdx(&MBB);
677 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
678 if (!ParentVNI) {
679 DEBUG(dbgs() << " enterIntvAtEnd " << End << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000680 return;
681 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000682 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000683 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
684 MBB, MBB.getFirstTerminator());
685 // Make sure openli is live out of MBB.
686 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000687 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000688}
689
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000690/// useIntv - indicate that all instructions in MBB should use openli.
691void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
692 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000693}
694
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000695void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000696 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000697 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000698 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
699 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000700}
701
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000702/// leaveIntvAfter - Leave openli after the instruction at Idx.
703void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000704 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000705
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000706 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000707 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000708 if (!ParentVNI) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000709 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000710 return;
711 }
712
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000713 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
714 MachineBasicBlock *MBB = MII->getParent();
715 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
716 llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000717
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000718 // Finally we must make sure that openli is properly extended from Idx to the
719 // new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000720 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000721 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_.getLI()
722 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000723}
724
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000725/// leaveIntvAtTop - Leave the interval at the top of MBB.
726/// Currently, only one value can leave the interval.
727void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000728 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000729
730 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000731 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000732
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000733 // Is curli even live-in to MBB?
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000734 if (!ParentVNI) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000735 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000736 return;
737 }
738
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000739 // We are going to insert a back copy, so we must have a dupli_.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000740 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
741 MBB, MBB.begin());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000742
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000743 // Finally we must make sure that openli is properly extended from Start to
744 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000745 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000746 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000747 << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000748}
749
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000750/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000751/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000752void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000753 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000754
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000755 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000756 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000757 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000758}
759
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000760void
761SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
762 SlotIndex sidx = Start;
763
764 // Break [Start;End) into segments that don't overlap any intervals.
765 for (;;) {
766 SlotIndex next = sidx, eidx = End;
767 // Find overlapping intervals.
768 for (int i = firstInterval, e = intervals_.size(); i != e && sidx < eidx;
769 ++i) {
770 LiveInterval::const_iterator I = intervals_[i]->find(sidx);
771 LiveInterval::const_iterator E = intervals_[i]->end();
772 if (I == E)
773 continue;
774 // Interval I is overlapping [sidx;eidx). Trim sidx.
775 if (I->start <= sidx) {
776 sidx = I->end;
777 if (++I == E)
778 continue;
779 }
780 // Trim eidx too if needed.
781 if (I->start >= eidx)
782 continue;
783 eidx = I->start;
784 if (I->end > next)
785 next = I->end;
786 }
787 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
788 if (sidx < eidx)
789 dupli_.addSimpleRange(sidx, eidx, VNI);
790 // If the interval end was truncated, we can try again from next.
791 if (next <= sidx)
792 break;
793 sidx = next;
794 }
795}
796
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000797/// rewrite - after all the new live ranges have been created, rewrite
798/// instructions using curli to use the new intervals.
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000799void SplitEditor::rewrite() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000800 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000801
802 // First we need to fill in the live ranges in dupli.
803 // If values were redefined, we need a full recoloring with SSA update.
804 // If values were truncated, we only need to truncate the ranges.
805 // If values were partially rematted, we should shrink to uses.
806 // If values were fully rematted, they should be omitted.
807 // FIXME: If a single value is redefined, just move the def and truncate.
808
809 // Values that are fully contained in the split intervals.
810 SmallPtrSet<const VNInfo*, 8> deadValues;
811
812 // Map all curli values that should have live defs in dupli.
813 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
814 E = curli_->vni_end(); I != E; ++I) {
815 const VNInfo *VNI = *I;
816 // Original def is contained in the split intervals.
817 if (intervalsLiveAt(VNI->def)) {
818 // Did this value escape?
819 if (dupli_.isMapped(VNI))
820 truncatedValues.insert(VNI);
821 else
822 deadValues.insert(VNI);
823 continue;
824 }
825 // Add minimal live range at the definition.
826 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
827 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
828 }
829
830 // Add all ranges to dupli.
831 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
832 I != E; ++I) {
833 const LiveRange &LR = *I;
834 if (truncatedValues.count(LR.valno)) {
835 // recolor after removing intervals_.
836 addTruncSimpleRange(LR.start, LR.end, LR.valno);
837 } else if (!deadValues.count(LR.valno)) {
838 // recolor without truncation.
839 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
840 }
841 }
842
843
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000844 const LiveInterval *curli = sa_.getCurLI();
845 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
846 RE = mri_.reg_end(); RI != RE;) {
847 MachineOperand &MO = RI.getOperand();
848 MachineInstr *MI = MO.getParent();
849 ++RI;
850 if (MI->isDebugValue()) {
851 DEBUG(dbgs() << "Zapping " << *MI);
852 // FIXME: We can do much better with debug values.
853 MO.setReg(0);
854 continue;
855 }
856 SlotIndex Idx = lis_.getInstructionIndex(MI);
857 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000858 LiveInterval *LI = dupli_.getLI();
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000859 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
860 LiveInterval *testli = intervals_[i];
861 if (testli->liveAt(Idx)) {
862 LI = testli;
863 break;
864 }
865 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000866 if (LI) {
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000867 MO.setReg(LI->reg);
Jakob Stoklund Olesen00667a52010-08-13 01:05:23 +0000868 sa_.removeUse(MI);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000869 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
870 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000871 }
872
873 // dupli_ goes in last, after rewriting.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000874 if (dupli_.getLI()) {
875 if (dupli_.getLI()->empty()) {
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000876 DEBUG(dbgs() << " dupli became empty?\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000877 lis_.removeInterval(dupli_.getLI()->reg);
878 dupli_.reset(0);
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000879 } else {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000880 dupli_.getLI()->RenumberValues(lis_);
881 intervals_.push_back(dupli_.getLI());
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000882 }
Jakob Stoklund Olesen23436592010-08-06 18:46:59 +0000883 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000884
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000885 // Calculate spill weight and allocation hints for new intervals.
886 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
887 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
888 LiveInterval &li = *intervals_[i];
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000889 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000890 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000891 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
892 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000893 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000894}
895
896
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000897//===----------------------------------------------------------------------===//
898// Loop Splitting
899//===----------------------------------------------------------------------===//
900
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000901void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000902 SplitAnalysis::LoopBlocks Blocks;
903 sa_.getLoopBlocks(Loop, Blocks);
904
905 // Break critical edges as needed.
906 SplitAnalysis::BlockPtrSet CriticalExits;
907 sa_.getCriticalExits(Blocks, CriticalExits);
908 assert(CriticalExits.empty() && "Cannot break critical exits yet");
909
910 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000911 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000912
913 // Insert copies in the predecessors.
914 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
915 E = Blocks.Preds.end(); I != E; ++I) {
916 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000917 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000918 }
919
920 // Switch all loop blocks.
921 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
922 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000923 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000924
925 // Insert back copies in the exit blocks.
926 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
927 E = Blocks.Exits.end(); I != E; ++I) {
928 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000929 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000930 }
931
932 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000933 closeIntv();
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000934 rewrite();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000935}
936
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000937
938//===----------------------------------------------------------------------===//
939// Single Block Splitting
940//===----------------------------------------------------------------------===//
941
942/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000943/// basic block in Blocks.
944void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000945 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000946 // Determine the first and last instruction using curli in each block.
947 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
948 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
949 IndexPairMap MBBRange;
950 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
951 E = sa_.usingInstrs_.end(); I != E; ++I) {
952 const MachineBasicBlock *MBB = (*I)->getParent();
953 if (!Blocks.count(MBB))
954 continue;
955 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000956 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000957 IndexPair &IP = MBBRange[MBB];
958 if (!IP.first.isValid() || Idx < IP.first)
959 IP.first = Idx;
960 if (!IP.second.isValid() || Idx > IP.second)
961 IP.second = Idx;
962 }
963
964 // Create a new interval for each block.
965 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
966 E = Blocks.end(); I != E; ++I) {
967 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000968 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000969 << IP.first << ';' << IP.second << ")\n");
970 assert(IP.first.isValid() && IP.second.isValid());
971
972 openIntv();
973 enterIntvBefore(IP.first);
974 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
975 leaveIntvAfter(IP.second);
976 closeIntv();
977 }
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000978 rewrite();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000979}
980
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +0000981
982//===----------------------------------------------------------------------===//
983// Sub Block Splitting
984//===----------------------------------------------------------------------===//
985
986/// getBlockForInsideSplit - If curli is contained inside a single basic block,
987/// and it wou pay to subdivide the interval inside that block, return it.
988/// Otherwise return NULL. The returned block can be passed to
989/// SplitEditor::splitInsideBlock.
990const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
991 // The interval must be exclusive to one block.
992 if (usingBlocks_.size() != 1)
993 return 0;
994 // Don't to this for less than 4 instructions. We want to be sure that
995 // splitting actually reduces the instruction count per interval.
996 if (usingInstrs_.size() < 4)
997 return 0;
998 return usingBlocks_.begin()->first;
999}
1000
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001001/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1002void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001003 SmallVector<SlotIndex, 32> Uses;
1004 Uses.reserve(sa_.usingInstrs_.size());
1005 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1006 E = sa_.usingInstrs_.end(); I != E; ++I)
1007 if ((*I)->getParent() == MBB)
1008 Uses.push_back(lis_.getInstructionIndex(*I));
1009 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1010 << Uses.size() << " instructions.\n");
1011 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1012 array_pod_sort(Uses.begin(), Uses.end());
1013
1014 // Simple algorithm: Find the largest gap between uses as determined by slot
1015 // indices. Create new intervals for instructions before the gap and after the
1016 // gap.
1017 unsigned bestPos = 0;
1018 int bestGap = 0;
1019 DEBUG(dbgs() << " dist (" << Uses[0]);
1020 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1021 int g = Uses[i-1].distance(Uses[i]);
1022 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1023 if (g > bestGap)
1024 bestPos = i, bestGap = g;
1025 }
1026 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1027
1028 // bestPos points to the first use after the best gap.
1029 assert(bestPos > 0 && "Invalid gap");
1030
1031 // FIXME: Don't create intervals for low densities.
1032
1033 // First interval before the gap. Don't create single-instr intervals.
1034 if (bestPos > 1) {
1035 openIntv();
1036 enterIntvBefore(Uses.front());
1037 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1038 leaveIntvAfter(Uses[bestPos-1]);
1039 closeIntv();
1040 }
1041
1042 // Second interval after the gap.
1043 if (bestPos < Uses.size()-1) {
1044 openIntv();
1045 enterIntvBefore(Uses[bestPos]);
1046 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1047 leaveIntvAfter(Uses.back());
1048 closeIntv();
1049 }
1050
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001051 rewrite();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001052}